blob: 8f405e8dcc33619d0c212fcad5c1ad531b786ba7 [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
Alex Deymo87c08862015-10-30 21:56:55 -0700126 // rebooted. The previous version event is also not sent if it was already
127 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700128 string prev_version;
129 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
130 prev_version = "0.0.0.0";
131 }
Alex Deymo87c08862015-10-30 21:56:55 -0700132 // We only store a non-empty previous version value after a successful
133 // update in the previous boot. After reporting it back to the server,
134 // we clear the previous version value so it doesn't get reported again.
135 if (!prev_version.empty()) {
136 app_body += base::StringPrintf(
137 " <event eventtype=\"%d\" eventresult=\"%d\" "
138 "previousversion=\"%s\"></event>\n",
139 OmahaEvent::kTypeUpdateComplete,
140 OmahaEvent::kResultSuccessReboot,
141 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
142 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
143 << "Unable to reset the previous version.";
144 }
Darin Petkov95508da2011-01-05 12:42:29 -0800145 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700146 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800147 // The error code is an optional attribute so append it only if the result
148 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700149 string error_code;
150 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700151 error_code = base::StringPrintf(" errorcode=\"%d\"",
152 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700153 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700154 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700155 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700156 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700157 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700158
159 return app_body;
160}
161
Alex Deymo8e18f932015-03-27 16:16:59 -0700162// Returns the cohort* argument to include in the <app> tag for the passed
163// |arg_name| and |prefs_key|, if any. The return value is suitable to
164// concatenate to the list of arguments and includes a space at the end.
165string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700166 const string arg_name,
167 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700168 // There's nothing wrong with not having a given cohort setting, so we check
169 // existance first to avoid the warning log message.
170 if (!prefs->Exists(prefs_key))
171 return "";
172 string cohort_value;
173 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
174 return "";
175 // This is a sanity check to avoid sending a huge XML file back to Ohama due
176 // to a compromised stateful partition making the update check fail in low
177 // network environments envent after a reboot.
178 if (cohort_value.size() > 1024) {
179 LOG(WARNING) << "The omaha cohort setting " << arg_name
180 << " has a too big value, which must be an error or an "
181 "attacker trying to inhibit updates.";
182 return "";
183 }
184
Alex Deymob0d74eb2015-03-30 17:59:17 -0700185 string escaped_xml_value;
186 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
187 LOG(WARNING) << "The omaha cohort setting " << arg_name
188 << " is ASCII-7 invalid, ignoring it.";
189 return "";
190 }
191
Alex Deymo8e18f932015-03-27 16:16:59 -0700192 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700193 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700194}
195
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700196// Returns an XML that corresponds to the entire <app> node of the Omaha
197// request based on the given parameters.
198string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700199 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700200 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700201 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700202 int ping_active_days,
203 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800204 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700205 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700206 string app_body = GetAppBody(event, params, ping_only, include_ping,
207 ping_active_days, ping_roll_call_days,
208 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700209 string app_versions;
210
211 // If we are upgrading to a more stable channel and we are allowed to do
212 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
213 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700214 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700215 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
216 << "on downgrading to the version in the more stable channel";
217 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700218 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700219 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700220 app_versions = "version=\"" +
221 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700222 }
223
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700224 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700225 string app_channels =
226 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
227 if (params->current_channel() != download_channel) {
228 app_channels += "from_track=\"" + XmlEncodeWithDefault(
229 params->current_channel(), "") + "\" ";
230 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700231
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700232 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700233
David Zeuthen639aa362014-02-03 16:23:44 -0800234 // If install_date_days is not set (e.g. its value is -1 ), don't
235 // include the attribute.
236 string install_date_in_days_str = "";
237 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700238 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
239 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800240 }
241
Alex Deymo8e18f932015-03-27 16:16:59 -0700242 string app_cohort_args;
243 app_cohort_args += GetCohortArgXml(system_state->prefs(),
244 "cohort", kPrefsOmahaCohort);
245 app_cohort_args += GetCohortArgXml(system_state->prefs(),
246 "cohorthint", kPrefsOmahaCohortHint);
247 app_cohort_args += GetCohortArgXml(system_state->prefs(),
248 "cohortname", kPrefsOmahaCohortName);
249
Alex Deymob0d74eb2015-03-30 17:59:17 -0700250 string app_xml = " <app "
251 "appid=\"" + XmlEncodeWithDefault(params->GetAppId(), "") + "\" " +
252 app_cohort_args +
253 app_versions +
254 app_channels +
255 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
256 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
257 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
258 "delta_okay=\"" + delta_okay_str + "\" "
259 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
260 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
261 install_date_in_days_str +
262 ">\n" +
263 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700264 " </app>\n";
265
266 return app_xml;
267}
268
269// Returns an XML that corresponds to the entire <os> node of the Omaha
270// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700271string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700272 string os_xml =" <os "
273 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
274 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
275 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
276 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700277 return os_xml;
278}
279
280// Returns an XML that corresponds to the entire Omaha request based on the
281// given parameters.
282string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700283 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700284 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700285 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700286 int ping_active_days,
287 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800288 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700289 SystemState* system_state) {
290 string os_xml = GetOsXml(params);
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700291 string app_xml = GetAppXml(event, params, ping_only, include_ping,
292 ping_active_days, ping_roll_call_days,
293 install_date_in_days, system_state);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700294
Alex Vakulenko75039d72014-03-25 12:36:28 -0700295 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700296 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700297
Alex Deymoac41a822015-09-15 20:52:53 -0700298 string updater_version = XmlEncodeWithDefault(
299 base::StringPrintf("%s-%s",
300 constants::kOmahaUpdaterID,
301 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700302 string request_xml =
303 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700304 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700305 "version=\"" + updater_version + "\" "
306 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700307 install_source +
308 "ismachine=\"1\">\n") +
309 os_xml +
310 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700311 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700312
313 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000314}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700315
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700316} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000317
David Zeuthene8ed8632014-07-24 13:38:10 -0400318// Struct used for holding data obtained when parsing the XML.
319struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400320 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
321
322 // Pointer to the expat XML_Parser object.
323 XML_Parser xml_parser;
324
David Zeuthene8ed8632014-07-24 13:38:10 -0400325 // This is the state of the parser as it's processing the XML.
326 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400327 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400328 string current_path;
329
330 // These are the values extracted from the XML.
Alex Deymo8e18f932015-03-27 16:16:59 -0700331 string app_cohort;
332 string app_cohorthint;
333 string app_cohortname;
334 bool app_cohort_set = false;
335 bool app_cohorthint_set = false;
336 bool app_cohortname_set = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400337 string updatecheck_status;
338 string updatecheck_poll_interval;
339 string daystart_elapsed_days;
340 string daystart_elapsed_seconds;
341 vector<string> url_codebase;
342 string package_name;
343 string package_size;
344 string manifest_version;
345 map<string, string> action_postinstall_attrs;
346};
347
348namespace {
349
350// Callback function invoked by expat.
351void ParserHandlerStart(void* user_data, const XML_Char* element,
352 const XML_Char** attr) {
353 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
354
355 if (data->failed)
356 return;
357
358 data->current_path += string("/") + element;
359
360 map<string, string> attrs;
361 if (attr != nullptr) {
362 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
363 string key = attr[n];
364 string value = attr[n + 1];
365 attrs[key] = value;
366 }
367 }
368
Alex Deymo8e18f932015-03-27 16:16:59 -0700369 if (data->current_path == "/response/app") {
370 if (attrs.find("cohort") != attrs.end()) {
371 data->app_cohort_set = true;
372 data->app_cohort = attrs["cohort"];
373 }
374 if (attrs.find("cohorthint") != attrs.end()) {
375 data->app_cohorthint_set = true;
376 data->app_cohorthint = attrs["cohorthint"];
377 }
378 if (attrs.find("cohortname") != attrs.end()) {
379 data->app_cohortname_set = true;
380 data->app_cohortname = attrs["cohortname"];
381 }
382 } else if (data->current_path == "/response/app/updatecheck") {
David Zeuthene8ed8632014-07-24 13:38:10 -0400383 // There is only supposed to be a single <updatecheck> element.
384 data->updatecheck_status = attrs["status"];
385 data->updatecheck_poll_interval = attrs["PollInterval"];
386 } else if (data->current_path == "/response/daystart") {
387 // Get the install-date.
388 data->daystart_elapsed_days = attrs["elapsed_days"];
389 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
390 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
391 // Look at all <url> elements.
392 data->url_codebase.push_back(attrs["codebase"]);
393 } else if (data->package_name.empty() && data->current_path ==
394 "/response/app/updatecheck/manifest/packages/package") {
395 // Only look at the first <package>.
396 data->package_name = attrs["name"];
397 data->package_size = attrs["size"];
398 } else if (data->current_path == "/response/app/updatecheck/manifest") {
399 // Get the version.
400 data->manifest_version = attrs[kTagVersion];
401 } else if (data->current_path ==
402 "/response/app/updatecheck/manifest/actions/action") {
403 // We only care about the postinstall action.
404 if (attrs["event"] == "postinstall") {
405 data->action_postinstall_attrs = attrs;
406 }
407 }
408}
409
410// Callback function invoked by expat.
411void ParserHandlerEnd(void* user_data, const XML_Char* element) {
412 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
413 if (data->failed)
414 return;
415
416 const string path_suffix = string("/") + element;
417
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700418 if (!base::EndsWith(data->current_path, path_suffix, true)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400419 LOG(ERROR) << "Unexpected end element '" << element
420 << "' with current_path='" << data->current_path << "'";
421 data->failed = true;
422 return;
423 }
424 data->current_path.resize(data->current_path.size() - path_suffix.size());
425}
426
David Zeuthenf3e28012014-08-26 18:23:52 -0400427// Callback function invoked by expat.
428//
429// This is called for entity declarations. Since Omaha is guaranteed
430// to never return any XML with entities our course of action is to
431// just stop parsing. This avoids potential resource exhaustion
432// problems AKA the "billion laughs". CVE-2013-0340.
433void ParserHandlerEntityDecl(void *user_data,
434 const XML_Char *entity_name,
435 int is_parameter_entity,
436 const XML_Char *value,
437 int value_length,
438 const XML_Char *base,
439 const XML_Char *system_id,
440 const XML_Char *public_id,
441 const XML_Char *notation_name) {
442 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
443
444 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
445 data->failed = true;
446 data->entity_decl = true;
447 XML_StopParser(data->xml_parser, false);
448}
449
David Zeuthene8ed8632014-07-24 13:38:10 -0400450} // namespace
451
Alex Deymob0d74eb2015-03-30 17:59:17 -0700452bool XmlEncode(const string& input, string* output) {
453 if (std::find_if(input.begin(), input.end(),
454 [](const char c){return c & 0x80;}) != input.end()) {
455 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
456 utils::HexDumpString(input);
457 return false;
458 }
Alex Deymocc457852015-06-18 18:35:50 -0700459 output->clear();
460 // We need at least input.size() space in the output, but the code below will
461 // handle it if we need more.
462 output->reserve(input.size());
463 for (char c : input) {
464 switch (c) {
465 case '\"':
466 output->append("&quot;");
467 break;
468 case '\'':
469 output->append("&apos;");
470 break;
471 case '&':
472 output->append("&amp;");
473 break;
474 case '<':
475 output->append("&lt;");
476 break;
477 case '>':
478 output->append("&gt;");
479 break;
480 default:
481 output->push_back(c);
482 }
483 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700484 return true;
485}
486
487string XmlEncodeWithDefault(const string& input, const string& default_value) {
488 string output;
489 if (XmlEncode(input, &output))
490 return output;
491 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000492}
493
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800494OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700495 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700496 HttpFetcher* http_fetcher,
497 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800498 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700499 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700500 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700501 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700502 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700503 ping_roll_call_days_(0) {
504 params_ = system_state->request_params();
505}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000506
Darin Petkov6a5b3222010-07-13 14:55:28 -0700507OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000508
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700509// Calculates the value to use for the ping days parameter.
510int OmahaRequestAction::CalculatePingDays(const string& key) {
511 int days = kNeverPinged;
512 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800513 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700514 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
515 if (days < 0) {
516 // If |days| is negative, then the system clock must have jumped
517 // back in time since the ping was sent. Mark the value so that
518 // it doesn't get sent to the server but we still update the
519 // last ping daystart preference. This way the next ping time
520 // will be correct, hopefully.
521 days = kPingTimeJump;
522 LOG(WARNING) <<
523 "System clock jumped back in time. Resetting ping daystarts.";
524 }
525 }
526 return days;
527}
528
529void OmahaRequestAction::InitPingDays() {
530 // We send pings only along with update checks, not with events.
531 if (IsEvent()) {
532 return;
533 }
534 // TODO(petkov): Figure a way to distinguish active use pings
535 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700536 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700537 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
538 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
539}
540
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700541bool OmahaRequestAction::ShouldPing() const {
542 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
543 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
544 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
545 if (powerwash_count > 0) {
546 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
547 << "powerwash_count is " << powerwash_count;
548 return false;
549 }
550 return true;
551 }
552 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
553}
554
David Zeuthen639aa362014-02-03 16:23:44 -0800555// static
556int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
557 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700558 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800559 return -1;
560
561 // If we have the value stored on disk, just return it.
562 int64_t stored_value;
563 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
564 // Convert and sanity-check.
565 int install_date_days = static_cast<int>(stored_value);
566 if (install_date_days >= 0)
567 return install_date_days;
568 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
569 << install_date_days << " looks suspicious.";
570 prefs->Delete(kPrefsInstallDateDays);
571 }
572
573 // Otherwise, if OOBE is not complete then do nothing and wait for
574 // ParseResponse() to call ParseInstallDate() and then
575 // PersistInstallDate() to set the kPrefsInstallDateDays state
576 // variable. Once that is done, we'll then report back in future
577 // Omaha requests. This works exactly because OOBE triggers an
578 // update check.
579 //
580 // However, if OOBE is complete and the kPrefsInstallDateDays state
581 // variable is not set, there are two possibilities
582 //
583 // 1. The update check in OOBE failed so we never got a response
584 // from Omaha (no network etc.); or
585 //
586 // 2. OOBE was done on an older version that didn't write to the
587 // kPrefsInstallDateDays state variable.
588 //
589 // In both cases, we approximate the install date by simply
590 // inspecting the timestamp of when OOBE happened.
591
592 Time time_of_oobe;
Alex Deymobccbc382014-04-03 13:38:55 -0700593 if (!system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800594 LOG(INFO) << "Not generating Omaha InstallData as we have "
595 << "no prefs file and OOBE is not complete.";
596 return -1;
597 }
598
599 int num_days;
600 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
601 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
602 << "as its value '" << utils::ToString(time_of_oobe)
603 << "' looks suspicious.";
604 return -1;
605 }
606
607 // Persist this to disk, for future use.
608 if (!OmahaRequestAction::PersistInstallDate(system_state,
609 num_days,
610 kProvisionedFromOOBEMarker))
611 return -1;
612
613 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
614 << num_days << " days";
615
616 return num_days;
617}
618
Darin Petkov6a5b3222010-07-13 14:55:28 -0700619void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000620 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700621 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700622 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700623 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700624 return;
625 }
David Zeuthen639aa362014-02-03 16:23:44 -0800626
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700627 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700628 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700629 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700630 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700631 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800632 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800633 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700634 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700635
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800636 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
637 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700638 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700639 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700640 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000641}
642
Darin Petkov6a5b3222010-07-13 14:55:28 -0700643void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000644 http_fetcher_->TerminateTransfer();
645}
646
647// We just store the response in the buffer. Once we've received all bytes,
648// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700649void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800650 const void* bytes,
651 size_t length) {
652 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
653 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000654}
655
656namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000657
658// Parses a 64 bit base-10 int from a string and returns it. Returns 0
659// on error. If the string contains "0", that's indistinguishable from
660// error.
661off_t ParseInt(const string& str) {
662 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700663 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000664 if (rc < 1) {
665 // failure
666 return 0;
667 }
668 return ret;
669}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700670
David Zeuthene8ed8632014-07-24 13:38:10 -0400671// Parses |str| and returns |true| if, and only if, its value is "true".
672bool ParseBool(const string& str) {
673 return str == "true";
674}
675
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700676// Update the last ping day preferences based on the server daystart
677// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400678bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700679 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400680 TEST_AND_RETURN_FALSE(
681 base::StringToInt64(parser_data->daystart_elapsed_seconds,
682 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700683 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
684
685 // Remember the local time that matches the server's last midnight
686 // time.
687 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
688 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
689 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
690 return true;
691}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700692} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000693
David Zeuthene8ed8632014-07-24 13:38:10 -0400694bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700695 OmahaResponse* output_object,
696 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400697 if (parser_data->updatecheck_status.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700698 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700699 return false;
700 }
701
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800702 // chromium-os:37289: The PollInterval is not supported by Omaha server
703 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700704 // slow down the request rate from the server-side. Note that the PollInterval
705 // is not persisted, so it has to be sent by the server on every response to
706 // guarantee that the scheduler uses this value (otherwise, if the device got
707 // rebooted after the last server-indicated value, it'll revert to the default
708 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
709 // based on the assumption that we perform an update check every hour so that
710 // the max value of 8 will roughly be equivalent to one work day. If we decide
711 // to use PollInterval permanently, we should update the
712 // max_update_checks_allowed to take PollInterval into account. Note: The
713 // parsing for PollInterval happens even before parsing of the status because
714 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400715 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700716 &output_object->poll_interval);
717
David Zeuthen639aa362014-02-03 16:23:44 -0800718 // Check for the "elapsed_days" attribute in the "daystart"
719 // element. This is the number of days since Jan 1 2007, 0:00
720 // PST. If we don't have a persisted value of the Omaha InstallDate,
721 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400722 if (ParseInstallDate(parser_data, output_object) &&
723 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800724 // Since output_object->install_date_days is never negative, the
725 // elapsed_days -> install-date calculation is reduced to simply
726 // rounding down to the nearest number divisible by 7.
727 int remainder = output_object->install_date_days % 7;
728 int install_date_days_rounded =
729 output_object->install_date_days - remainder;
730 if (PersistInstallDate(system_state_,
731 install_date_days_rounded,
732 kProvisionedFromOmahaResponse)) {
733 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
734 << install_date_days_rounded << " days";
735 }
736 }
737
Alex Deymo00d79ac2015-06-29 15:41:49 -0700738 // We persist the cohorts sent by omaha even if the status is "noupdate".
739 if (parser_data->app_cohort_set)
740 PersistCohortData(kPrefsOmahaCohort, parser_data->app_cohort);
741 if (parser_data->app_cohorthint_set)
742 PersistCohortData(kPrefsOmahaCohortHint, parser_data->app_cohorthint);
743 if (parser_data->app_cohortname_set)
744 PersistCohortData(kPrefsOmahaCohortName, parser_data->app_cohortname);
745
David Zeuthene8ed8632014-07-24 13:38:10 -0400746 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700747 return false;
748
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800749 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
750 // appends the package name to the URLs populated in this method.
David Zeuthene8ed8632014-07-24 13:38:10 -0400751 if (!ParseUrls(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700752 return false;
753
David Zeuthene8ed8632014-07-24 13:38:10 -0400754 if (!ParsePackage(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700755 return false;
756
David Zeuthene8ed8632014-07-24 13:38:10 -0400757 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700758 return false;
759
760 return true;
761}
762
David Zeuthene8ed8632014-07-24 13:38:10 -0400763bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700764 OmahaResponse* output_object,
765 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400766 const string& status = parser_data->updatecheck_status;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700767 if (status == "noupdate") {
768 LOG(INFO) << "No update.";
769 output_object->update_exists = false;
770 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700771 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700772 return false;
773 }
774
775 if (status != "ok") {
776 LOG(ERROR) << "Unknown Omaha response status: " << status;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700777 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700778 return false;
779 }
780
781 return true;
782}
783
David Zeuthene8ed8632014-07-24 13:38:10 -0400784bool OmahaRequestAction::ParseUrls(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700785 OmahaResponse* output_object,
786 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400787 if (parser_data->url_codebase.empty()) {
788 LOG(ERROR) << "No Omaha Response URLs";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700789 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700790 return false;
791 }
792
David Zeuthene8ed8632014-07-24 13:38:10 -0400793 LOG(INFO) << "Found " << parser_data->url_codebase.size() << " url(s)";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800794 output_object->payload_urls.clear();
David Zeuthene8ed8632014-07-24 13:38:10 -0400795 for (const auto& codebase : parser_data->url_codebase) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800796 if (codebase.empty()) {
797 LOG(ERROR) << "Omaha Response URL has empty codebase";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700798 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800799 return false;
800 }
801 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700802 }
803
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700804 return true;
805}
806
David Zeuthene8ed8632014-07-24 13:38:10 -0400807bool OmahaRequestAction::ParsePackage(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700808 OmahaResponse* output_object,
809 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400810 if (parser_data->package_name.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700811 LOG(ERROR) << "Omaha Response has empty package name";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700812 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700813 return false;
814 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800815
816 // Append the package name to each URL in our list so that we don't
817 // propagate the urlBase vs packageName distinctions beyond this point.
818 // From now on, we only need to use payload_urls.
David Zeuthene8ed8632014-07-24 13:38:10 -0400819 for (auto& payload_url : output_object->payload_urls)
820 payload_url += parser_data->package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700821
822 // Parse the payload size.
David Zeuthene8ed8632014-07-24 13:38:10 -0400823 off_t size = ParseInt(parser_data->package_size);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700824 if (size <= 0) {
825 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700826 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700827 return false;
828 }
829 output_object->size = size;
830
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800831 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700832
833 return true;
834}
835
David Zeuthene8ed8632014-07-24 13:38:10 -0400836bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700837 OmahaResponse* output_object,
838 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400839 output_object->version = parser_data->manifest_version;
Chris Sosa3b748432013-06-20 16:42:59 -0700840 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700841 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700842 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700843 return false;
844 }
845
846 LOG(INFO) << "Received omaha response to update to version "
847 << output_object->version;
848
David Zeuthene8ed8632014-07-24 13:38:10 -0400849 map<string, string> attrs = parser_data->action_postinstall_attrs;
850 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700851 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700852 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700853 return false;
854 }
855
David Zeuthene8ed8632014-07-24 13:38:10 -0400856 output_object->hash = attrs[kTagSha256];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700857 if (output_object->hash.empty()) {
858 LOG(ERROR) << "Omaha Response has empty sha256 value";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700859 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700860 return false;
861 }
862
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800863 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -0400864 output_object->more_info_url = attrs[kTagMoreInfo];
865 output_object->metadata_size = ParseInt(attrs[kTagMetadataSize]);
866 output_object->metadata_signature = attrs[kTagMetadataSignatureRsa];
867 output_object->prompt = ParseBool(attrs[kTagPrompt]);
868 output_object->deadline = attrs[kTagDeadline];
869 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700870 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -0400871 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700872 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -0400873 ParseBool(attrs[kTagDisableP2PForSharing]);
874 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800875
David Zeuthene8ed8632014-07-24 13:38:10 -0400876 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800877 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800878 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700879
David Zeuthene8ed8632014-07-24 13:38:10 -0400880 output_object->is_delta_payload = ParseBool(attrs[kTagIsDeltaPayload]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800881
882 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -0400883 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800884
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700885 return true;
886}
887
David Zeuthene8ed8632014-07-24 13:38:10 -0400888// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000889// and fill in the appropriate fields of the output object. Also, notifies
890// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700891void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
892 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000893 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800894 string current_response(response_buffer_.begin(), response_buffer_.end());
895 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700896
Gilad Arnold74b5f552014-10-07 08:17:16 -0700897 PayloadStateInterface* const payload_state = system_state_->payload_state();
898
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700899 // Events are best effort transactions -- assume they always succeed.
900 if (IsEvent()) {
901 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800902 if (event_->result == OmahaEvent::kResultError && successful &&
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700903 system_state_->hardware()->IsOfficialBuild()) {
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800904 LOG(INFO) << "Signalling Crash Reporter.";
905 utils::ScheduleCrashReporterUpload();
906 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700907 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700908 return;
909 }
910
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700911 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700912 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700913 int code = GetHTTPResponseCode();
914 // Makes sure we send sane error values.
915 if (code < 0 || code >= 1000) {
916 code = 999;
917 }
David Zeuthena99981f2013-04-29 13:42:47 -0700918 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700919 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000920 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700921 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000922
David Zeuthene8ed8632014-07-24 13:38:10 -0400923 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400924 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400925 XML_SetUserData(parser, &parser_data);
926 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400927 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800928 XML_Status res = XML_Parse(
929 parser,
930 reinterpret_cast<const char*>(response_buffer_.data()),
931 response_buffer_.size(),
932 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400933 XML_ParserFree(parser);
934
935 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700936 LOG(ERROR) << "Omaha response not valid XML: "
937 << XML_ErrorString(XML_GetErrorCode(parser))
938 << " at line " << XML_GetCurrentLineNumber(parser)
939 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400940 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
941 if (response_buffer_.empty()) {
942 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
943 } else if (parser_data.entity_decl) {
944 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
945 }
946 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000947 return;
948 }
949
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700950 // Update the last ping day preferences based on the server daystart response
951 // even if we didn't send a ping. Omaha always includes the daystart in the
952 // response, but log the error if it didn't.
953 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
954 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700955
Thieu Le116fda32011-04-19 11:01:54 -0700956 if (!HasOutputPipe()) {
957 // Just set success to whether or not the http transfer succeeded,
958 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700959 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700960 return;
961 }
962
Darin Petkov6a5b3222010-07-13 14:55:28 -0700963 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400964 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000965 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700966 output_object.update_exists = true;
967 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000968
Chris Sosa77f79e82014-06-02 18:16:24 -0700969 if (ShouldIgnoreUpdate(output_object)) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700970 output_object.update_exists = false;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700971 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700972 return;
973 }
974
David Zeuthen8f191b22013-08-06 12:27:50 -0700975 // If Omaha says to disable p2p, respect that
976 if (output_object.disable_p2p_for_downloading) {
977 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
978 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700979 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700980 }
981 if (output_object.disable_p2p_for_sharing) {
982 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
983 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700984 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700985 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800986
987 // Update the payload state with the current response. The payload state
988 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800989 // from what's stored already. We are updating the payload state as late
990 // as possible in this method so that if a new release gets pushed and then
991 // got pulled back due to some issues, we don't want to clear our internal
992 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800993 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800994
David Zeuthen8f191b22013-08-06 12:27:50 -0700995 // It could be we've already exceeded the deadline for when p2p is
996 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700997 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -0700998 payload_state->P2PNewAttempt();
999 if (!payload_state->P2PAttemptAllowed()) {
1000 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1001 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001002 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001003 }
1004 }
1005
1006 // From here on, we'll complete stuff in CompleteProcessing() so
1007 // disable |completer| since we'll create a new one in that
1008 // function.
1009 completer.set_should_complete(false);
1010
1011 // If we're allowed to use p2p for downloading we do not pay
1012 // attention to wall-clock-based waiting if the URL is indeed
1013 // available via p2p. Therefore, check if the file is available via
1014 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001015 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001016 LookupPayloadViaP2P(output_object);
1017 } else {
1018 CompleteProcessing();
1019 }
1020}
1021
1022void OmahaRequestAction::CompleteProcessing() {
1023 ScopedActionCompleter completer(processor_, this);
1024 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1025 PayloadStateInterface* payload_state = system_state_->payload_state();
1026
1027 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001028 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001029 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001030 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001031 return;
1032 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001033
Chris Sosa20f005c2013-09-05 13:53:08 -07001034 if (payload_state->ShouldBackoffDownload()) {
1035 output_object.update_exists = false;
1036 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1037 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001038 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001039 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001040 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001041 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001042}
1043
1044void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1045 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1046 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001047 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001048 } else {
1049 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1050 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001051 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001052 }
1053 CompleteProcessing();
1054}
1055
1056void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001057 // If the device is in the middle of an update, the state variables
1058 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1059 // tracks the offset and length of the operation currently in
1060 // progress. The offset is based from the end of the manifest which
1061 // is kPrefsManifestMetadataSize bytes long.
1062 //
1063 // To make forward progress and avoid deadlocks, we need to find a
1064 // peer that has at least the entire operation we're currently
1065 // working on. Otherwise we may end up in a situation where two
1066 // devices bounce back and forth downloading from each other,
1067 // neither making any forward progress until one of them decides to
1068 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1069 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001070 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001071 int64_t manifest_metadata_size = 0;
1072 int64_t next_data_offset = 0;
1073 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001074 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001075 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1076 &manifest_metadata_size) &&
1077 manifest_metadata_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001078 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001079 &next_data_offset) &&
1080 next_data_offset != -1 &&
1081 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1082 &next_data_length)) {
1083 minimum_size = manifest_metadata_size + next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001084 }
1085
1086 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001087 if (system_state_->p2p_manager()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001088 LOG(INFO) << "Checking if payload is available via p2p, file_id="
1089 << file_id << " minimum_size=" << minimum_size;
1090 system_state_->p2p_manager()->LookupUrlForFile(
1091 file_id,
1092 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001093 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001094 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1095 base::Unretained(this)));
1096 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001097}
1098
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001099bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001100 if (params_->interactive()) {
1101 LOG(INFO) << "Not deferring download because update is interactive.";
1102 return false;
1103 }
1104
David Zeuthen8f191b22013-08-06 12:27:50 -07001105 // If we're using p2p to download _and_ we have a p2p URL, we never
1106 // defer the download. This is because the download will always
1107 // happen from a peer on the LAN and we've been waiting in line for
1108 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001109 const PayloadStateInterface* payload_state = system_state_->payload_state();
1110 if (payload_state->GetUsingP2PForDownloading() &&
1111 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001112 LOG(INFO) << "Download not deferred because download "
1113 << "will happen from a local peer (via p2p).";
1114 return false;
1115 }
1116
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001117 // We should defer the downloads only if we've first satisfied the
1118 // wall-clock-based-waiting period and then the update-check-based waiting
1119 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001120 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001121 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1122 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001123 return false;
1124 }
1125
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001126 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001127 case kWallClockWaitNotSatisfied:
1128 // We haven't even satisfied the first condition, passing the
1129 // wall-clock-based waiting period, so we should defer the downloads
1130 // until that happens.
1131 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1132 return true;
1133
1134 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1135 LOG(INFO) << "wall-clock-based-wait satisfied and "
1136 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001137 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001138
1139 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1140 // Wall-clock-based waiting period is satisfied, and it's determined
1141 // that we do not need the update-check-based wait. so no need to
1142 // defer downloads.
1143 LOG(INFO) << "wall-clock-based-wait satisfied and "
1144 << "update-check-based-wait is not required.";
1145 return false;
1146
1147 default:
1148 // Returning false for this default case so we err on the
1149 // side of downloading updates than deferring in case of any bugs.
1150 NOTREACHED();
1151 return false;
1152 }
1153}
1154
1155OmahaRequestAction::WallClockWaitResult
1156OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001157 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001158 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001159 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001160
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001161 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1162 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1163 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001164 // Note: This timestamp could be that of ANY update we saw in the past
1165 // (not necessarily this particular update we're considering to apply)
1166 // but never got to apply because of some reason (e.g. stop AU policy,
1167 // updates being pulled out from Omaha, changes in target version prefix,
1168 // new update being rolled out, etc.). But for the purposes of scattering
1169 // it doesn't matter which update the timestamp corresponds to. i.e.
1170 // the clock starts ticking the first time we see an update and we're
1171 // ready to apply when the random wait period is satisfied relative to
1172 // that first seen timestamp.
1173 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1174 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1175 << utils::ToString(update_first_seen_at);
1176 } else {
1177 // This seems like an unexpected error where the persisted value exists
1178 // but it's not readable for some reason. Just skip scattering in this
1179 // case to be safe.
1180 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1181 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1182 }
1183 } else {
1184 update_first_seen_at = Time::Now();
1185 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001186 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1187 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001188 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1189 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001190 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001191 // This seems like an unexpected error where the value cannot be
1192 // persisted for some reason. Just skip scattering in this
1193 // case to be safe.
1194 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1195 << utils::ToString(update_first_seen_at)
1196 << " cannot be persisted";
1197 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1198 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001199 }
1200
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001201 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001202 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001203 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001204
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001205 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001206 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001207 << ", Time Elapsed = "
1208 << utils::FormatSecs(elapsed_time.InSeconds())
1209 << ", MaxDaysToScatter = "
1210 << max_scatter_period.InDays();
1211
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001212 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001213 // The deadline is set for all rules which serve a delta update from a
1214 // previous FSI, which means this update will be applied mostly in OOBE
1215 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1216 // quickly.
1217 LOG(INFO) << "Not scattering as deadline flag is set";
1218 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1219 }
1220
1221 if (max_scatter_period.InDays() == 0) {
1222 // This means the Omaha rule creator decides that this rule
1223 // should not be scattered irrespective of the policy.
1224 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1225 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1226 }
1227
1228 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001229 // This means we've waited more than the upperbound wait in the rule
1230 // from the time we first saw a valid update available to us.
1231 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001232 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1233 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1234 }
1235
1236 // This means we are required to participate in scattering.
1237 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001238 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001239 if (remaining_wait_time.InSeconds() <= 0) {
1240 // Yes, it's our turn now.
1241 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1242
1243 // But we can't download until the update-check-count-based wait is also
1244 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001245 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001246 kWallClockWaitDoneButUpdateCheckWaitRequired :
1247 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1248 }
1249
1250 // Not our turn yet, so we have to wait until our turn to
1251 // help scatter the downloads across all clients of the enterprise.
1252 LOG(INFO) << "Update deferred for another "
1253 << utils::FormatSecs(remaining_wait_time.InSeconds())
1254 << " per policy.";
1255 return kWallClockWaitNotSatisfied;
1256}
1257
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001258bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001259 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001260
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001261 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1262 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1263 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001264 // We are unable to read the update check count from file for some reason.
1265 // So let's proceed anyway so as to not stall the update.
1266 LOG(ERROR) << "Unable to read update check count. "
1267 << "Skipping update-check-count-based-wait.";
1268 return true;
1269 }
1270 } else {
1271 // This file does not exist. This means we haven't started our update
1272 // check count down yet, so this is the right time to start the count down.
1273 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001274 params_->min_update_checks_needed(),
1275 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001276
1277 LOG(INFO) << "Randomly picked update check count value = "
1278 << update_check_count_value;
1279
1280 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001281 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1282 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001283 // We weren't able to write the update check count file for some reason.
1284 // So let's proceed anyway so as to not stall the update.
1285 LOG(ERROR) << "Unable to write update check count. "
1286 << "Skipping update-check-count-based-wait.";
1287 return true;
1288 }
1289 }
1290
1291 if (update_check_count_value == 0) {
1292 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1293 return true;
1294 }
1295
1296 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001297 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001298 // We err on the side of skipping scattering logic instead of stalling
1299 // a machine from receiving any updates in case of any unexpected state.
1300 LOG(ERROR) << "Invalid value for update check count detected. "
1301 << "Skipping update-check-count-based-wait.";
1302 return true;
1303 }
1304
1305 // Legal value, we need to wait for more update checks to happen
1306 // until this becomes 0.
1307 LOG(INFO) << "Deferring Omaha updates for another "
1308 << update_check_count_value
1309 << " update checks per policy";
1310 return false;
1311}
1312
David Zeuthen639aa362014-02-03 16:23:44 -08001313// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001314bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001315 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001316 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001317 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001318 &elapsed_days))
1319 return false;
1320
1321 if (elapsed_days < 0)
1322 return false;
1323
1324 output_object->install_date_days = elapsed_days;
1325 return true;
1326}
1327
1328// static
1329bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1330 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001331 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001332 return false;
1333
1334 return prefs->Exists(kPrefsInstallDateDays);
1335}
1336
1337// static
1338bool OmahaRequestAction::PersistInstallDate(
1339 SystemState *system_state,
1340 int install_date_days,
1341 InstallDateProvisioningSource source) {
1342 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1343
1344 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001345 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001346 return false;
1347
1348 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1349 return false;
1350
Alex Deymoaf9a8632015-09-23 18:51:48 -07001351 string metric_name = metrics::kMetricInstallDateProvisioningSource;
David Zeuthen33bae492014-02-25 16:16:18 -08001352 system_state->metrics_lib()->SendEnumToUMA(
1353 metric_name,
1354 static_cast<int>(source), // Sample.
1355 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001356
1357 return true;
1358}
1359
Alex Deymo8e18f932015-03-27 16:16:59 -07001360bool OmahaRequestAction::PersistCohortData(
1361 const string& prefs_key,
1362 const string& new_value) {
1363 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1364 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1365 return system_state_->prefs()->Delete(prefs_key);
1366 } else if (!new_value.empty()) {
1367 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1368 return system_state_->prefs()->SetString(prefs_key, new_value);
1369 }
1370 return true;
1371}
1372
David Zeuthen33bae492014-02-25 16:16:18 -08001373void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1374 // We only want to report this on "update check".
1375 if (ping_only_ || event_ != nullptr)
1376 return;
1377
1378 metrics::CheckResult result = metrics::CheckResult::kUnset;
1379 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1380 metrics::DownloadErrorCode download_error_code =
1381 metrics::DownloadErrorCode::kUnset;
1382
1383 // Regular update attempt.
1384 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001385 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001386 // OK, we parsed the response successfully but that does
1387 // necessarily mean that an update is available.
1388 if (HasOutputPipe()) {
1389 const OmahaResponse& response = GetOutputObject();
1390 if (response.update_exists) {
1391 result = metrics::CheckResult::kUpdateAvailable;
1392 reaction = metrics::CheckReaction::kUpdating;
1393 } else {
1394 result = metrics::CheckResult::kNoUpdateAvailable;
1395 }
1396 } else {
1397 result = metrics::CheckResult::kNoUpdateAvailable;
1398 }
1399 break;
1400
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001401 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001402 result = metrics::CheckResult::kUpdateAvailable;
1403 reaction = metrics::CheckReaction::kIgnored;
1404 break;
1405
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001406 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001407 result = metrics::CheckResult::kUpdateAvailable;
1408 reaction = metrics::CheckReaction::kDeferring;
1409 break;
1410
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001411 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001412 result = metrics::CheckResult::kUpdateAvailable;
1413 reaction = metrics::CheckReaction::kBackingOff;
1414 break;
1415
1416 default:
1417 // We report two flavors of errors, "Download errors" and "Parsing
1418 // error". Try to convert to the former and if that doesn't work
1419 // we know it's the latter.
1420 metrics::DownloadErrorCode tmp_error = utils::GetDownloadErrorCode(code);
1421 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1422 result = metrics::CheckResult::kDownloadError;
1423 download_error_code = tmp_error;
1424 } else {
1425 result = metrics::CheckResult::kParsingError;
1426 }
1427 break;
1428 }
1429
1430 metrics::ReportUpdateCheckMetrics(system_state_,
1431 result, reaction, download_error_code);
1432}
1433
Chris Sosa77f79e82014-06-02 18:16:24 -07001434bool OmahaRequestAction::ShouldIgnoreUpdate(
1435 const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001436 // Note: policy decision to not update to a version we rolled back from.
1437 string rollback_version =
1438 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001439 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001440 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001441 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001442 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1443 return true;
1444 }
1445 }
1446
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001447 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001448 LOG(INFO) << "Update is not allowed over current connection.";
1449 return true;
1450 }
1451
1452 // Note: We could technically delete the UpdateFirstSeenAt state when we
1453 // return true. If we do, it'll mean a device has to restart the
1454 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1455 // turned on again. On the other hand, it also increases the chance of update
1456 // starvation if an admin turns AU on/off more frequently. We choose to err on
1457 // the side of preventing starvation at the cost of not applying scattering in
1458 // those cases.
1459 return false;
1460}
1461
1462bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
1463 NetworkConnectionType type;
1464 NetworkTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001465 ConnectionManagerInterface* connection_manager =
1466 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001467 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001468 LOG(INFO) << "We could not determine our connection type. "
1469 << "Defaulting to allow updates.";
1470 return true;
1471 }
1472 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1473 LOG(INFO) << "We are connected via "
Alex Deymof6ee0162015-07-31 12:35:22 -07001474 << ConnectionManager::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001475 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1476 return is_allowed;
1477}
1478
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001479} // namespace chromeos_update_engine