blob: 3e69e96fbee9c619d64c092078479df23c4ecbb4 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
rspangler@google.com49fdf182009-10-10 00:57:34 +000016
Darin Petkov6a5b3222010-07-13 14:55:28 -070017#include "update_engine/omaha_request_action.h"
Darin Petkov85ced132010-09-01 10:20:56 -070018
Andrew de los Reyes08c4e272010-04-15 14:02:17 -070019#include <inttypes.h>
Darin Petkov85ced132010-09-01 10:20:56 -070020
David Zeuthene8ed8632014-07-24 13:38:10 -040021#include <map>
rspangler@google.com49fdf182009-10-10 00:57:34 +000022#include <sstream>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070023#include <string>
David Zeuthene8ed8632014-07-24 13:38:10 -040024#include <vector>
rspangler@google.com49fdf182009-10-10 00:57:34 +000025
David Zeuthen8f191b22013-08-06 12:27:50 -070026#include <base/bind.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070027#include <base/logging.h>
28#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070029#include <base/strings/string_number_conversions.h>
30#include <base/strings/string_util.h>
31#include <base/strings/stringprintf.h>
32#include <base/time/time.h>
David Zeuthene8ed8632014-07-24 13:38:10 -040033#include <expat.h>
Alex Deymoa2591792015-11-17 00:39:40 -030034#include <metrics/metrics_library.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000035
Alex Deymo39910dc2015-11-09 17:04:30 -080036#include "update_engine/common/action_pipe.h"
37#include "update_engine/common/constants.h"
38#include "update_engine/common/hardware_interface.h"
39#include "update_engine/common/hash_calculator.h"
40#include "update_engine/common/platform_constants.h"
41#include "update_engine/common/prefs_interface.h"
42#include "update_engine/common/utils.h"
Alex Deymof6ee0162015-07-31 12:35:22 -070043#include "update_engine/connection_manager.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080044#include "update_engine/metrics.h"
45#include "update_engine/metrics_utils.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070046#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070047#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080048#include "update_engine/payload_state_interface.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000049
Darin Petkov1cbd78f2010-07-29 12:38:34 -070050using base::Time;
51using base::TimeDelta;
David Zeuthene8ed8632014-07-24 13:38:10 -040052using std::map;
rspangler@google.com49fdf182009-10-10 00:57:34 +000053using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040054using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000055
56namespace chromeos_update_engine {
57
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080058// List of custom pair tags that we interpret in the Omaha Response:
59static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080060static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070061static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080062// Deprecated: "IsDelta"
63static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080064static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
65static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
66// Deprecated: "ManifestSignatureRsa"
67// Deprecated: "ManifestSize"
68static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
69static const char* kTagMetadataSize = "MetadataSize";
70static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070071// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080072static const char* kTagPrompt = "Prompt";
73static const char* kTagSha256 = "sha256";
David Zeuthen8f191b22013-08-06 12:27:50 -070074static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
75static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
David Zeuthene7f89172013-10-31 10:21:04 -070076static const char* kTagPublicKeyRsa = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080077
Alex Deymoac41a822015-09-15 20:52:53 -070078static const char* kOmahaUpdaterVersion = "0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +000079
Alex Deymoac41a822015-09-15 20:52:53 -070080namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +000081
Darin Petkov1cbd78f2010-07-29 12:38:34 -070082// Returns an XML ping element attribute assignment with attribute
83// |name| and value |ping_days| if |ping_days| has a value that needs
84// to be sent, or an empty string otherwise.
85string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -070086 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -070087 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -070088 return "";
89}
90
91// Returns an XML ping element if any of the elapsed days need to be
92// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -070093string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -070094 string ping_active = GetPingAttribute("a", ping_active_days);
95 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
96 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -070097 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -070098 ping_active.c_str(),
99 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700100 }
101 return "";
102}
103
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700104// Returns an XML that goes into the body of the <app> element of the Omaha
105// request based on the given parameters.
106string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700107 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700108 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700109 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700110 int ping_active_days,
111 int ping_roll_call_days,
112 PrefsInterface* prefs) {
113 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700114 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700115 if (include_ping)
116 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700117 if (!ping_only) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700118 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700119 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700120 "></updatecheck>\n",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700121 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700122
Darin Petkov265f2902011-05-09 15:17:40 -0700123 // If this is the first update check after a reboot following a previous
124 // update, generate an event containing the previous version number. If
125 // the previous version preference file doesn't exist the event is still
126 // generated with a previous version of 0.0.0.0 -- this is relevant for
127 // older clients or new installs. The previous version event is not sent
128 // for ping-only requests because they come before the client has
Alex Deymo87c08862015-10-30 21:56:55 -0700129 // rebooted. The previous version event is also not sent if it was already
130 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700131 string prev_version;
132 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
133 prev_version = "0.0.0.0";
134 }
Alex Deymo87c08862015-10-30 21:56:55 -0700135 // We only store a non-empty previous version value after a successful
136 // update in the previous boot. After reporting it back to the server,
137 // we clear the previous version value so it doesn't get reported again.
138 if (!prev_version.empty()) {
139 app_body += base::StringPrintf(
140 " <event eventtype=\"%d\" eventresult=\"%d\" "
141 "previousversion=\"%s\"></event>\n",
Alex Deymo9fded1e2015-11-05 12:31:19 -0800142 OmahaEvent::kTypeRebootedAfterUpdate,
143 OmahaEvent::kResultSuccess,
Alex Deymo87c08862015-10-30 21:56:55 -0700144 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
145 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
146 << "Unable to reset the previous version.";
147 }
Darin Petkov95508da2011-01-05 12:42:29 -0800148 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700149 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800150 // The error code is an optional attribute so append it only if the result
151 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700152 string error_code;
153 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700154 error_code = base::StringPrintf(" errorcode=\"%d\"",
155 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700156 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700157 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700158 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700159 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700160 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700161
162 return app_body;
163}
164
Alex Deymo8e18f932015-03-27 16:16:59 -0700165// Returns the cohort* argument to include in the <app> tag for the passed
166// |arg_name| and |prefs_key|, if any. The return value is suitable to
167// concatenate to the list of arguments and includes a space at the end.
168string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700169 const string arg_name,
170 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700171 // There's nothing wrong with not having a given cohort setting, so we check
172 // existance first to avoid the warning log message.
173 if (!prefs->Exists(prefs_key))
174 return "";
175 string cohort_value;
176 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
177 return "";
178 // This is a sanity check to avoid sending a huge XML file back to Ohama due
179 // to a compromised stateful partition making the update check fail in low
180 // network environments envent after a reboot.
181 if (cohort_value.size() > 1024) {
182 LOG(WARNING) << "The omaha cohort setting " << arg_name
183 << " has a too big value, which must be an error or an "
184 "attacker trying to inhibit updates.";
185 return "";
186 }
187
Alex Deymob0d74eb2015-03-30 17:59:17 -0700188 string escaped_xml_value;
189 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
190 LOG(WARNING) << "The omaha cohort setting " << arg_name
191 << " is ASCII-7 invalid, ignoring it.";
192 return "";
193 }
194
Alex Deymo8e18f932015-03-27 16:16:59 -0700195 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700196 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700197}
198
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700199// Returns an XML that corresponds to the entire <app> node of the Omaha
200// request based on the given parameters.
201string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700202 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700203 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700204 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700205 int ping_active_days,
206 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800207 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700208 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700209 string app_body = GetAppBody(event, params, ping_only, include_ping,
210 ping_active_days, ping_roll_call_days,
211 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700212 string app_versions;
213
214 // If we are upgrading to a more stable channel and we are allowed to do
215 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
216 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700217 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700218 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
219 << "on downgrading to the version in the more stable channel";
220 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700221 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700222 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700223 app_versions = "version=\"" +
224 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700225 }
226
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700227 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700228 string app_channels =
229 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
230 if (params->current_channel() != download_channel) {
231 app_channels += "from_track=\"" + XmlEncodeWithDefault(
232 params->current_channel(), "") + "\" ";
233 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700234
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700235 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700236
David Zeuthen639aa362014-02-03 16:23:44 -0800237 // If install_date_days is not set (e.g. its value is -1 ), don't
238 // include the attribute.
239 string install_date_in_days_str = "";
240 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700241 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
242 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800243 }
244
Alex Deymo8e18f932015-03-27 16:16:59 -0700245 string app_cohort_args;
246 app_cohort_args += GetCohortArgXml(system_state->prefs(),
247 "cohort", kPrefsOmahaCohort);
248 app_cohort_args += GetCohortArgXml(system_state->prefs(),
249 "cohorthint", kPrefsOmahaCohortHint);
250 app_cohort_args += GetCohortArgXml(system_state->prefs(),
251 "cohortname", kPrefsOmahaCohortName);
252
Alex Deymob0d74eb2015-03-30 17:59:17 -0700253 string app_xml = " <app "
254 "appid=\"" + XmlEncodeWithDefault(params->GetAppId(), "") + "\" " +
255 app_cohort_args +
256 app_versions +
257 app_channels +
258 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
259 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
260 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
261 "delta_okay=\"" + delta_okay_str + "\" "
262 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
263 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
264 install_date_in_days_str +
265 ">\n" +
266 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700267 " </app>\n";
268
269 return app_xml;
270}
271
272// Returns an XML that corresponds to the entire <os> node of the Omaha
273// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700274string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700275 string os_xml =" <os "
276 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
277 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
278 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
279 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700280 return os_xml;
281}
282
283// Returns an XML that corresponds to the entire Omaha request based on the
284// given parameters.
285string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700286 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700287 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700288 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700289 int ping_active_days,
290 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800291 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700292 SystemState* system_state) {
293 string os_xml = GetOsXml(params);
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700294 string app_xml = GetAppXml(event, params, ping_only, include_ping,
295 ping_active_days, ping_roll_call_days,
296 install_date_in_days, system_state);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700297
Alex Vakulenko75039d72014-03-25 12:36:28 -0700298 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700299 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700300
Alex Deymoac41a822015-09-15 20:52:53 -0700301 string updater_version = XmlEncodeWithDefault(
302 base::StringPrintf("%s-%s",
303 constants::kOmahaUpdaterID,
304 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700305 string request_xml =
306 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700307 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700308 "version=\"" + updater_version + "\" "
309 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700310 install_source +
311 "ismachine=\"1\">\n") +
312 os_xml +
313 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700314 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700315
316 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000317}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700318
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700319} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000320
David Zeuthene8ed8632014-07-24 13:38:10 -0400321// Struct used for holding data obtained when parsing the XML.
322struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400323 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
324
325 // Pointer to the expat XML_Parser object.
326 XML_Parser xml_parser;
327
David Zeuthene8ed8632014-07-24 13:38:10 -0400328 // This is the state of the parser as it's processing the XML.
329 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400330 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400331 string current_path;
332
333 // These are the values extracted from the XML.
Alex Deymo8e18f932015-03-27 16:16:59 -0700334 string app_cohort;
335 string app_cohorthint;
336 string app_cohortname;
337 bool app_cohort_set = false;
338 bool app_cohorthint_set = false;
339 bool app_cohortname_set = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400340 string updatecheck_status;
341 string updatecheck_poll_interval;
342 string daystart_elapsed_days;
343 string daystart_elapsed_seconds;
344 vector<string> url_codebase;
345 string package_name;
346 string package_size;
347 string manifest_version;
348 map<string, string> action_postinstall_attrs;
349};
350
351namespace {
352
353// Callback function invoked by expat.
354void ParserHandlerStart(void* user_data, const XML_Char* element,
355 const XML_Char** attr) {
356 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
357
358 if (data->failed)
359 return;
360
361 data->current_path += string("/") + element;
362
363 map<string, string> attrs;
364 if (attr != nullptr) {
365 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
366 string key = attr[n];
367 string value = attr[n + 1];
368 attrs[key] = value;
369 }
370 }
371
Alex Deymo8e18f932015-03-27 16:16:59 -0700372 if (data->current_path == "/response/app") {
373 if (attrs.find("cohort") != attrs.end()) {
374 data->app_cohort_set = true;
375 data->app_cohort = attrs["cohort"];
376 }
377 if (attrs.find("cohorthint") != attrs.end()) {
378 data->app_cohorthint_set = true;
379 data->app_cohorthint = attrs["cohorthint"];
380 }
381 if (attrs.find("cohortname") != attrs.end()) {
382 data->app_cohortname_set = true;
383 data->app_cohortname = attrs["cohortname"];
384 }
385 } else if (data->current_path == "/response/app/updatecheck") {
David Zeuthene8ed8632014-07-24 13:38:10 -0400386 // There is only supposed to be a single <updatecheck> element.
387 data->updatecheck_status = attrs["status"];
388 data->updatecheck_poll_interval = attrs["PollInterval"];
389 } else if (data->current_path == "/response/daystart") {
390 // Get the install-date.
391 data->daystart_elapsed_days = attrs["elapsed_days"];
392 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
393 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
394 // Look at all <url> elements.
395 data->url_codebase.push_back(attrs["codebase"]);
396 } else if (data->package_name.empty() && data->current_path ==
397 "/response/app/updatecheck/manifest/packages/package") {
398 // Only look at the first <package>.
399 data->package_name = attrs["name"];
400 data->package_size = attrs["size"];
401 } else if (data->current_path == "/response/app/updatecheck/manifest") {
402 // Get the version.
403 data->manifest_version = attrs[kTagVersion];
404 } else if (data->current_path ==
405 "/response/app/updatecheck/manifest/actions/action") {
406 // We only care about the postinstall action.
407 if (attrs["event"] == "postinstall") {
408 data->action_postinstall_attrs = attrs;
409 }
410 }
411}
412
413// Callback function invoked by expat.
414void ParserHandlerEnd(void* user_data, const XML_Char* element) {
415 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
416 if (data->failed)
417 return;
418
419 const string path_suffix = string("/") + element;
420
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700421 if (!base::EndsWith(data->current_path, path_suffix, true)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400422 LOG(ERROR) << "Unexpected end element '" << element
423 << "' with current_path='" << data->current_path << "'";
424 data->failed = true;
425 return;
426 }
427 data->current_path.resize(data->current_path.size() - path_suffix.size());
428}
429
David Zeuthenf3e28012014-08-26 18:23:52 -0400430// Callback function invoked by expat.
431//
432// This is called for entity declarations. Since Omaha is guaranteed
433// to never return any XML with entities our course of action is to
434// just stop parsing. This avoids potential resource exhaustion
435// problems AKA the "billion laughs". CVE-2013-0340.
436void ParserHandlerEntityDecl(void *user_data,
437 const XML_Char *entity_name,
438 int is_parameter_entity,
439 const XML_Char *value,
440 int value_length,
441 const XML_Char *base,
442 const XML_Char *system_id,
443 const XML_Char *public_id,
444 const XML_Char *notation_name) {
445 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
446
447 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
448 data->failed = true;
449 data->entity_decl = true;
450 XML_StopParser(data->xml_parser, false);
451}
452
David Zeuthene8ed8632014-07-24 13:38:10 -0400453} // namespace
454
Alex Deymob0d74eb2015-03-30 17:59:17 -0700455bool XmlEncode(const string& input, string* output) {
456 if (std::find_if(input.begin(), input.end(),
457 [](const char c){return c & 0x80;}) != input.end()) {
458 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
459 utils::HexDumpString(input);
460 return false;
461 }
Alex Deymocc457852015-06-18 18:35:50 -0700462 output->clear();
463 // We need at least input.size() space in the output, but the code below will
464 // handle it if we need more.
465 output->reserve(input.size());
466 for (char c : input) {
467 switch (c) {
468 case '\"':
469 output->append("&quot;");
470 break;
471 case '\'':
472 output->append("&apos;");
473 break;
474 case '&':
475 output->append("&amp;");
476 break;
477 case '<':
478 output->append("&lt;");
479 break;
480 case '>':
481 output->append("&gt;");
482 break;
483 default:
484 output->push_back(c);
485 }
486 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700487 return true;
488}
489
490string XmlEncodeWithDefault(const string& input, const string& default_value) {
491 string output;
492 if (XmlEncode(input, &output))
493 return output;
494 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000495}
496
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800497OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700498 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700499 HttpFetcher* http_fetcher,
500 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800501 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700502 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700503 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700504 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700505 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700506 ping_roll_call_days_(0) {
507 params_ = system_state->request_params();
508}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000509
Darin Petkov6a5b3222010-07-13 14:55:28 -0700510OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000511
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700512// Calculates the value to use for the ping days parameter.
513int OmahaRequestAction::CalculatePingDays(const string& key) {
514 int days = kNeverPinged;
515 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800516 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700517 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
518 if (days < 0) {
519 // If |days| is negative, then the system clock must have jumped
520 // back in time since the ping was sent. Mark the value so that
521 // it doesn't get sent to the server but we still update the
522 // last ping daystart preference. This way the next ping time
523 // will be correct, hopefully.
524 days = kPingTimeJump;
525 LOG(WARNING) <<
526 "System clock jumped back in time. Resetting ping daystarts.";
527 }
528 }
529 return days;
530}
531
532void OmahaRequestAction::InitPingDays() {
533 // We send pings only along with update checks, not with events.
534 if (IsEvent()) {
535 return;
536 }
537 // TODO(petkov): Figure a way to distinguish active use pings
538 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700539 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700540 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
541 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
542}
543
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700544bool OmahaRequestAction::ShouldPing() const {
545 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
546 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
547 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
548 if (powerwash_count > 0) {
549 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
550 << "powerwash_count is " << powerwash_count;
551 return false;
552 }
553 return true;
554 }
555 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
556}
557
David Zeuthen639aa362014-02-03 16:23:44 -0800558// static
559int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
560 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700561 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800562 return -1;
563
564 // If we have the value stored on disk, just return it.
565 int64_t stored_value;
566 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
567 // Convert and sanity-check.
568 int install_date_days = static_cast<int>(stored_value);
569 if (install_date_days >= 0)
570 return install_date_days;
571 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
572 << install_date_days << " looks suspicious.";
573 prefs->Delete(kPrefsInstallDateDays);
574 }
575
576 // Otherwise, if OOBE is not complete then do nothing and wait for
577 // ParseResponse() to call ParseInstallDate() and then
578 // PersistInstallDate() to set the kPrefsInstallDateDays state
579 // variable. Once that is done, we'll then report back in future
580 // Omaha requests. This works exactly because OOBE triggers an
581 // update check.
582 //
583 // However, if OOBE is complete and the kPrefsInstallDateDays state
584 // variable is not set, there are two possibilities
585 //
586 // 1. The update check in OOBE failed so we never got a response
587 // from Omaha (no network etc.); or
588 //
589 // 2. OOBE was done on an older version that didn't write to the
590 // kPrefsInstallDateDays state variable.
591 //
592 // In both cases, we approximate the install date by simply
593 // inspecting the timestamp of when OOBE happened.
594
595 Time time_of_oobe;
Alex Deymobccbc382014-04-03 13:38:55 -0700596 if (!system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800597 LOG(INFO) << "Not generating Omaha InstallData as we have "
598 << "no prefs file and OOBE is not complete.";
599 return -1;
600 }
601
602 int num_days;
603 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
604 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
605 << "as its value '" << utils::ToString(time_of_oobe)
606 << "' looks suspicious.";
607 return -1;
608 }
609
610 // Persist this to disk, for future use.
611 if (!OmahaRequestAction::PersistInstallDate(system_state,
612 num_days,
613 kProvisionedFromOOBEMarker))
614 return -1;
615
616 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
617 << num_days << " days";
618
619 return num_days;
620}
621
Darin Petkov6a5b3222010-07-13 14:55:28 -0700622void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000623 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700624 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700625 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700626 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700627 return;
628 }
David Zeuthen639aa362014-02-03 16:23:44 -0800629
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700630 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700631 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700632 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700633 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700634 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800635 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800636 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700637 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700638
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800639 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
640 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700641 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700642 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700643 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000644}
645
Darin Petkov6a5b3222010-07-13 14:55:28 -0700646void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000647 http_fetcher_->TerminateTransfer();
648}
649
650// We just store the response in the buffer. Once we've received all bytes,
651// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700652void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800653 const void* bytes,
654 size_t length) {
655 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
656 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000657}
658
659namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000660
661// Parses a 64 bit base-10 int from a string and returns it. Returns 0
662// on error. If the string contains "0", that's indistinguishable from
663// error.
664off_t ParseInt(const string& str) {
665 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700666 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000667 if (rc < 1) {
668 // failure
669 return 0;
670 }
671 return ret;
672}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700673
David Zeuthene8ed8632014-07-24 13:38:10 -0400674// Parses |str| and returns |true| if, and only if, its value is "true".
675bool ParseBool(const string& str) {
676 return str == "true";
677}
678
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700679// Update the last ping day preferences based on the server daystart
680// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400681bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700682 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400683 TEST_AND_RETURN_FALSE(
684 base::StringToInt64(parser_data->daystart_elapsed_seconds,
685 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700686 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
687
688 // Remember the local time that matches the server's last midnight
689 // time.
690 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
691 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
692 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
693 return true;
694}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700695} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000696
David Zeuthene8ed8632014-07-24 13:38:10 -0400697bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700698 OmahaResponse* output_object,
699 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400700 if (parser_data->updatecheck_status.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700701 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700702 return false;
703 }
704
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800705 // chromium-os:37289: The PollInterval is not supported by Omaha server
706 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700707 // slow down the request rate from the server-side. Note that the PollInterval
708 // is not persisted, so it has to be sent by the server on every response to
709 // guarantee that the scheduler uses this value (otherwise, if the device got
710 // rebooted after the last server-indicated value, it'll revert to the default
711 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
712 // based on the assumption that we perform an update check every hour so that
713 // the max value of 8 will roughly be equivalent to one work day. If we decide
714 // to use PollInterval permanently, we should update the
715 // max_update_checks_allowed to take PollInterval into account. Note: The
716 // parsing for PollInterval happens even before parsing of the status because
717 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400718 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700719 &output_object->poll_interval);
720
David Zeuthen639aa362014-02-03 16:23:44 -0800721 // Check for the "elapsed_days" attribute in the "daystart"
722 // element. This is the number of days since Jan 1 2007, 0:00
723 // PST. If we don't have a persisted value of the Omaha InstallDate,
724 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400725 if (ParseInstallDate(parser_data, output_object) &&
726 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800727 // Since output_object->install_date_days is never negative, the
728 // elapsed_days -> install-date calculation is reduced to simply
729 // rounding down to the nearest number divisible by 7.
730 int remainder = output_object->install_date_days % 7;
731 int install_date_days_rounded =
732 output_object->install_date_days - remainder;
733 if (PersistInstallDate(system_state_,
734 install_date_days_rounded,
735 kProvisionedFromOmahaResponse)) {
736 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
737 << install_date_days_rounded << " days";
738 }
739 }
740
Alex Deymo00d79ac2015-06-29 15:41:49 -0700741 // We persist the cohorts sent by omaha even if the status is "noupdate".
742 if (parser_data->app_cohort_set)
743 PersistCohortData(kPrefsOmahaCohort, parser_data->app_cohort);
744 if (parser_data->app_cohorthint_set)
745 PersistCohortData(kPrefsOmahaCohortHint, parser_data->app_cohorthint);
746 if (parser_data->app_cohortname_set)
747 PersistCohortData(kPrefsOmahaCohortName, parser_data->app_cohortname);
748
David Zeuthene8ed8632014-07-24 13:38:10 -0400749 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700750 return false;
751
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800752 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
753 // appends the package name to the URLs populated in this method.
David Zeuthene8ed8632014-07-24 13:38:10 -0400754 if (!ParseUrls(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 (!ParsePackage(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700758 return false;
759
David Zeuthene8ed8632014-07-24 13:38:10 -0400760 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700761 return false;
762
763 return true;
764}
765
David Zeuthene8ed8632014-07-24 13:38:10 -0400766bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700767 OmahaResponse* output_object,
768 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400769 const string& status = parser_data->updatecheck_status;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700770 if (status == "noupdate") {
771 LOG(INFO) << "No update.";
772 output_object->update_exists = false;
773 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700774 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700775 return false;
776 }
777
778 if (status != "ok") {
779 LOG(ERROR) << "Unknown Omaha response status: " << status;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700780 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700781 return false;
782 }
783
784 return true;
785}
786
David Zeuthene8ed8632014-07-24 13:38:10 -0400787bool OmahaRequestAction::ParseUrls(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700788 OmahaResponse* output_object,
789 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400790 if (parser_data->url_codebase.empty()) {
791 LOG(ERROR) << "No Omaha Response URLs";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700792 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700793 return false;
794 }
795
David Zeuthene8ed8632014-07-24 13:38:10 -0400796 LOG(INFO) << "Found " << parser_data->url_codebase.size() << " url(s)";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800797 output_object->payload_urls.clear();
David Zeuthene8ed8632014-07-24 13:38:10 -0400798 for (const auto& codebase : parser_data->url_codebase) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800799 if (codebase.empty()) {
800 LOG(ERROR) << "Omaha Response URL has empty codebase";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700801 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800802 return false;
803 }
804 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700805 }
806
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700807 return true;
808}
809
David Zeuthene8ed8632014-07-24 13:38:10 -0400810bool OmahaRequestAction::ParsePackage(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700811 OmahaResponse* output_object,
812 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400813 if (parser_data->package_name.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700814 LOG(ERROR) << "Omaha Response has empty package name";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700815 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700816 return false;
817 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800818
819 // Append the package name to each URL in our list so that we don't
820 // propagate the urlBase vs packageName distinctions beyond this point.
821 // From now on, we only need to use payload_urls.
David Zeuthene8ed8632014-07-24 13:38:10 -0400822 for (auto& payload_url : output_object->payload_urls)
823 payload_url += parser_data->package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700824
825 // Parse the payload size.
David Zeuthene8ed8632014-07-24 13:38:10 -0400826 off_t size = ParseInt(parser_data->package_size);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700827 if (size <= 0) {
828 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700829 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700830 return false;
831 }
832 output_object->size = size;
833
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800834 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700835
836 return true;
837}
838
David Zeuthene8ed8632014-07-24 13:38:10 -0400839bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700840 OmahaResponse* output_object,
841 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400842 output_object->version = parser_data->manifest_version;
Chris Sosa3b748432013-06-20 16:42:59 -0700843 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700844 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700845 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700846 return false;
847 }
848
849 LOG(INFO) << "Received omaha response to update to version "
850 << output_object->version;
851
David Zeuthene8ed8632014-07-24 13:38:10 -0400852 map<string, string> attrs = parser_data->action_postinstall_attrs;
853 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700854 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700855 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700856 return false;
857 }
858
David Zeuthene8ed8632014-07-24 13:38:10 -0400859 output_object->hash = attrs[kTagSha256];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700860 if (output_object->hash.empty()) {
861 LOG(ERROR) << "Omaha Response has empty sha256 value";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700862 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700863 return false;
864 }
865
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800866 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -0400867 output_object->more_info_url = attrs[kTagMoreInfo];
868 output_object->metadata_size = ParseInt(attrs[kTagMetadataSize]);
869 output_object->metadata_signature = attrs[kTagMetadataSignatureRsa];
870 output_object->prompt = ParseBool(attrs[kTagPrompt]);
871 output_object->deadline = attrs[kTagDeadline];
872 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700873 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -0400874 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700875 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -0400876 ParseBool(attrs[kTagDisableP2PForSharing]);
877 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800878
David Zeuthene8ed8632014-07-24 13:38:10 -0400879 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800880 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800881 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700882
David Zeuthene8ed8632014-07-24 13:38:10 -0400883 output_object->is_delta_payload = ParseBool(attrs[kTagIsDeltaPayload]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800884
885 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -0400886 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800887
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700888 return true;
889}
890
David Zeuthene8ed8632014-07-24 13:38:10 -0400891// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000892// and fill in the appropriate fields of the output object. Also, notifies
893// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700894void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
895 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000896 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800897 string current_response(response_buffer_.begin(), response_buffer_.end());
898 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700899
Gilad Arnold74b5f552014-10-07 08:17:16 -0700900 PayloadStateInterface* const payload_state = system_state_->payload_state();
901
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700902 // Events are best effort transactions -- assume they always succeed.
903 if (IsEvent()) {
904 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800905 if (event_->result == OmahaEvent::kResultError && successful &&
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700906 system_state_->hardware()->IsOfficialBuild()) {
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800907 LOG(INFO) << "Signalling Crash Reporter.";
908 utils::ScheduleCrashReporterUpload();
909 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700910 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700911 return;
912 }
913
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700914 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700915 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700916 int code = GetHTTPResponseCode();
917 // Makes sure we send sane error values.
918 if (code < 0 || code >= 1000) {
919 code = 999;
920 }
David Zeuthena99981f2013-04-29 13:42:47 -0700921 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700922 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000923 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700924 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000925
David Zeuthene8ed8632014-07-24 13:38:10 -0400926 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400927 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400928 XML_SetUserData(parser, &parser_data);
929 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400930 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800931 XML_Status res = XML_Parse(
932 parser,
933 reinterpret_cast<const char*>(response_buffer_.data()),
934 response_buffer_.size(),
935 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400936 XML_ParserFree(parser);
937
938 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700939 LOG(ERROR) << "Omaha response not valid XML: "
940 << XML_ErrorString(XML_GetErrorCode(parser))
941 << " at line " << XML_GetCurrentLineNumber(parser)
942 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400943 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
944 if (response_buffer_.empty()) {
945 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
946 } else if (parser_data.entity_decl) {
947 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
948 }
949 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000950 return;
951 }
952
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700953 // Update the last ping day preferences based on the server daystart response
954 // even if we didn't send a ping. Omaha always includes the daystart in the
955 // response, but log the error if it didn't.
956 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
957 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700958
Thieu Le116fda32011-04-19 11:01:54 -0700959 if (!HasOutputPipe()) {
960 // Just set success to whether or not the http transfer succeeded,
961 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700962 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700963 return;
964 }
965
Darin Petkov6a5b3222010-07-13 14:55:28 -0700966 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400967 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000968 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700969 output_object.update_exists = true;
970 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000971
Chris Sosa77f79e82014-06-02 18:16:24 -0700972 if (ShouldIgnoreUpdate(output_object)) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700973 output_object.update_exists = false;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700974 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700975 return;
976 }
977
David Zeuthen8f191b22013-08-06 12:27:50 -0700978 // If Omaha says to disable p2p, respect that
979 if (output_object.disable_p2p_for_downloading) {
980 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
981 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700982 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700983 }
984 if (output_object.disable_p2p_for_sharing) {
985 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
986 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700987 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700988 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800989
990 // Update the payload state with the current response. The payload state
991 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800992 // from what's stored already. We are updating the payload state as late
993 // as possible in this method so that if a new release gets pushed and then
994 // got pulled back due to some issues, we don't want to clear our internal
995 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800996 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800997
David Zeuthen8f191b22013-08-06 12:27:50 -0700998 // It could be we've already exceeded the deadline for when p2p is
999 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001000 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001001 payload_state->P2PNewAttempt();
1002 if (!payload_state->P2PAttemptAllowed()) {
1003 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1004 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001005 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001006 }
1007 }
1008
1009 // From here on, we'll complete stuff in CompleteProcessing() so
1010 // disable |completer| since we'll create a new one in that
1011 // function.
1012 completer.set_should_complete(false);
1013
1014 // If we're allowed to use p2p for downloading we do not pay
1015 // attention to wall-clock-based waiting if the URL is indeed
1016 // available via p2p. Therefore, check if the file is available via
1017 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001018 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001019 LookupPayloadViaP2P(output_object);
1020 } else {
1021 CompleteProcessing();
1022 }
1023}
1024
1025void OmahaRequestAction::CompleteProcessing() {
1026 ScopedActionCompleter completer(processor_, this);
1027 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1028 PayloadStateInterface* payload_state = system_state_->payload_state();
1029
1030 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001031 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001032 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001033 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001034 return;
1035 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001036
Chris Sosa20f005c2013-09-05 13:53:08 -07001037 if (payload_state->ShouldBackoffDownload()) {
1038 output_object.update_exists = false;
1039 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1040 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001041 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001042 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001043 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001044 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001045}
1046
1047void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1048 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1049 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001050 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001051 } else {
1052 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1053 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001054 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001055 }
1056 CompleteProcessing();
1057}
1058
1059void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001060 // If the device is in the middle of an update, the state variables
1061 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1062 // tracks the offset and length of the operation currently in
1063 // progress. The offset is based from the end of the manifest which
1064 // is kPrefsManifestMetadataSize bytes long.
1065 //
1066 // To make forward progress and avoid deadlocks, we need to find a
1067 // peer that has at least the entire operation we're currently
1068 // working on. Otherwise we may end up in a situation where two
1069 // devices bounce back and forth downloading from each other,
1070 // neither making any forward progress until one of them decides to
1071 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1072 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001073 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001074 int64_t manifest_metadata_size = 0;
1075 int64_t next_data_offset = 0;
1076 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001077 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001078 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1079 &manifest_metadata_size) &&
1080 manifest_metadata_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001081 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001082 &next_data_offset) &&
1083 next_data_offset != -1 &&
1084 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1085 &next_data_length)) {
1086 minimum_size = manifest_metadata_size + next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001087 }
1088
1089 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001090 if (system_state_->p2p_manager()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001091 LOG(INFO) << "Checking if payload is available via p2p, file_id="
1092 << file_id << " minimum_size=" << minimum_size;
1093 system_state_->p2p_manager()->LookupUrlForFile(
1094 file_id,
1095 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001096 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001097 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1098 base::Unretained(this)));
1099 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001100}
1101
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001102bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001103 if (params_->interactive()) {
1104 LOG(INFO) << "Not deferring download because update is interactive.";
1105 return false;
1106 }
1107
David Zeuthen8f191b22013-08-06 12:27:50 -07001108 // If we're using p2p to download _and_ we have a p2p URL, we never
1109 // defer the download. This is because the download will always
1110 // happen from a peer on the LAN and we've been waiting in line for
1111 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001112 const PayloadStateInterface* payload_state = system_state_->payload_state();
1113 if (payload_state->GetUsingP2PForDownloading() &&
1114 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001115 LOG(INFO) << "Download not deferred because download "
1116 << "will happen from a local peer (via p2p).";
1117 return false;
1118 }
1119
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001120 // We should defer the downloads only if we've first satisfied the
1121 // wall-clock-based-waiting period and then the update-check-based waiting
1122 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001123 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001124 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1125 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001126 return false;
1127 }
1128
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001129 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001130 case kWallClockWaitNotSatisfied:
1131 // We haven't even satisfied the first condition, passing the
1132 // wall-clock-based waiting period, so we should defer the downloads
1133 // until that happens.
1134 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1135 return true;
1136
1137 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1138 LOG(INFO) << "wall-clock-based-wait satisfied and "
1139 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001140 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001141
1142 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1143 // Wall-clock-based waiting period is satisfied, and it's determined
1144 // that we do not need the update-check-based wait. so no need to
1145 // defer downloads.
1146 LOG(INFO) << "wall-clock-based-wait satisfied and "
1147 << "update-check-based-wait is not required.";
1148 return false;
1149
1150 default:
1151 // Returning false for this default case so we err on the
1152 // side of downloading updates than deferring in case of any bugs.
1153 NOTREACHED();
1154 return false;
1155 }
1156}
1157
1158OmahaRequestAction::WallClockWaitResult
1159OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001160 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001161 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001162 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001163
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001164 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1165 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1166 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001167 // Note: This timestamp could be that of ANY update we saw in the past
1168 // (not necessarily this particular update we're considering to apply)
1169 // but never got to apply because of some reason (e.g. stop AU policy,
1170 // updates being pulled out from Omaha, changes in target version prefix,
1171 // new update being rolled out, etc.). But for the purposes of scattering
1172 // it doesn't matter which update the timestamp corresponds to. i.e.
1173 // the clock starts ticking the first time we see an update and we're
1174 // ready to apply when the random wait period is satisfied relative to
1175 // that first seen timestamp.
1176 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1177 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1178 << utils::ToString(update_first_seen_at);
1179 } else {
1180 // This seems like an unexpected error where the persisted value exists
1181 // but it's not readable for some reason. Just skip scattering in this
1182 // case to be safe.
1183 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1184 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1185 }
1186 } else {
1187 update_first_seen_at = Time::Now();
1188 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001189 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1190 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001191 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1192 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001193 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001194 // This seems like an unexpected error where the value cannot be
1195 // persisted for some reason. Just skip scattering in this
1196 // case to be safe.
1197 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1198 << utils::ToString(update_first_seen_at)
1199 << " cannot be persisted";
1200 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1201 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001202 }
1203
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001204 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001205 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001206 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001207
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001208 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001209 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001210 << ", Time Elapsed = "
1211 << utils::FormatSecs(elapsed_time.InSeconds())
1212 << ", MaxDaysToScatter = "
1213 << max_scatter_period.InDays();
1214
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001215 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001216 // The deadline is set for all rules which serve a delta update from a
1217 // previous FSI, which means this update will be applied mostly in OOBE
1218 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1219 // quickly.
1220 LOG(INFO) << "Not scattering as deadline flag is set";
1221 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1222 }
1223
1224 if (max_scatter_period.InDays() == 0) {
1225 // This means the Omaha rule creator decides that this rule
1226 // should not be scattered irrespective of the policy.
1227 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1228 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1229 }
1230
1231 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001232 // This means we've waited more than the upperbound wait in the rule
1233 // from the time we first saw a valid update available to us.
1234 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001235 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1236 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1237 }
1238
1239 // This means we are required to participate in scattering.
1240 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001241 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001242 if (remaining_wait_time.InSeconds() <= 0) {
1243 // Yes, it's our turn now.
1244 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1245
1246 // But we can't download until the update-check-count-based wait is also
1247 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001248 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001249 kWallClockWaitDoneButUpdateCheckWaitRequired :
1250 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1251 }
1252
1253 // Not our turn yet, so we have to wait until our turn to
1254 // help scatter the downloads across all clients of the enterprise.
1255 LOG(INFO) << "Update deferred for another "
1256 << utils::FormatSecs(remaining_wait_time.InSeconds())
1257 << " per policy.";
1258 return kWallClockWaitNotSatisfied;
1259}
1260
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001261bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001262 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001263
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001264 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1265 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1266 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001267 // We are unable to read the update check count from file for some reason.
1268 // So let's proceed anyway so as to not stall the update.
1269 LOG(ERROR) << "Unable to read update check count. "
1270 << "Skipping update-check-count-based-wait.";
1271 return true;
1272 }
1273 } else {
1274 // This file does not exist. This means we haven't started our update
1275 // check count down yet, so this is the right time to start the count down.
1276 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001277 params_->min_update_checks_needed(),
1278 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001279
1280 LOG(INFO) << "Randomly picked update check count value = "
1281 << update_check_count_value;
1282
1283 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001284 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1285 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001286 // We weren't able to write the update check count file for some reason.
1287 // So let's proceed anyway so as to not stall the update.
1288 LOG(ERROR) << "Unable to write update check count. "
1289 << "Skipping update-check-count-based-wait.";
1290 return true;
1291 }
1292 }
1293
1294 if (update_check_count_value == 0) {
1295 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1296 return true;
1297 }
1298
1299 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001300 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001301 // We err on the side of skipping scattering logic instead of stalling
1302 // a machine from receiving any updates in case of any unexpected state.
1303 LOG(ERROR) << "Invalid value for update check count detected. "
1304 << "Skipping update-check-count-based-wait.";
1305 return true;
1306 }
1307
1308 // Legal value, we need to wait for more update checks to happen
1309 // until this becomes 0.
1310 LOG(INFO) << "Deferring Omaha updates for another "
1311 << update_check_count_value
1312 << " update checks per policy";
1313 return false;
1314}
1315
David Zeuthen639aa362014-02-03 16:23:44 -08001316// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001317bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001318 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001319 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001320 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001321 &elapsed_days))
1322 return false;
1323
1324 if (elapsed_days < 0)
1325 return false;
1326
1327 output_object->install_date_days = elapsed_days;
1328 return true;
1329}
1330
1331// static
1332bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1333 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001334 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001335 return false;
1336
1337 return prefs->Exists(kPrefsInstallDateDays);
1338}
1339
1340// static
1341bool OmahaRequestAction::PersistInstallDate(
1342 SystemState *system_state,
1343 int install_date_days,
1344 InstallDateProvisioningSource source) {
1345 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1346
1347 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001348 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001349 return false;
1350
1351 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1352 return false;
1353
Alex Deymoaf9a8632015-09-23 18:51:48 -07001354 string metric_name = metrics::kMetricInstallDateProvisioningSource;
David Zeuthen33bae492014-02-25 16:16:18 -08001355 system_state->metrics_lib()->SendEnumToUMA(
1356 metric_name,
1357 static_cast<int>(source), // Sample.
1358 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001359
1360 return true;
1361}
1362
Alex Deymo8e18f932015-03-27 16:16:59 -07001363bool OmahaRequestAction::PersistCohortData(
1364 const string& prefs_key,
1365 const string& new_value) {
1366 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1367 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1368 return system_state_->prefs()->Delete(prefs_key);
1369 } else if (!new_value.empty()) {
1370 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1371 return system_state_->prefs()->SetString(prefs_key, new_value);
1372 }
1373 return true;
1374}
1375
David Zeuthen33bae492014-02-25 16:16:18 -08001376void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1377 // We only want to report this on "update check".
1378 if (ping_only_ || event_ != nullptr)
1379 return;
1380
1381 metrics::CheckResult result = metrics::CheckResult::kUnset;
1382 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1383 metrics::DownloadErrorCode download_error_code =
1384 metrics::DownloadErrorCode::kUnset;
1385
1386 // Regular update attempt.
1387 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001388 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001389 // OK, we parsed the response successfully but that does
1390 // necessarily mean that an update is available.
1391 if (HasOutputPipe()) {
1392 const OmahaResponse& response = GetOutputObject();
1393 if (response.update_exists) {
1394 result = metrics::CheckResult::kUpdateAvailable;
1395 reaction = metrics::CheckReaction::kUpdating;
1396 } else {
1397 result = metrics::CheckResult::kNoUpdateAvailable;
1398 }
1399 } else {
1400 result = metrics::CheckResult::kNoUpdateAvailable;
1401 }
1402 break;
1403
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001404 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001405 result = metrics::CheckResult::kUpdateAvailable;
1406 reaction = metrics::CheckReaction::kIgnored;
1407 break;
1408
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001409 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001410 result = metrics::CheckResult::kUpdateAvailable;
1411 reaction = metrics::CheckReaction::kDeferring;
1412 break;
1413
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001414 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001415 result = metrics::CheckResult::kUpdateAvailable;
1416 reaction = metrics::CheckReaction::kBackingOff;
1417 break;
1418
1419 default:
1420 // We report two flavors of errors, "Download errors" and "Parsing
1421 // error". Try to convert to the former and if that doesn't work
1422 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001423 metrics::DownloadErrorCode tmp_error =
1424 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001425 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1426 result = metrics::CheckResult::kDownloadError;
1427 download_error_code = tmp_error;
1428 } else {
1429 result = metrics::CheckResult::kParsingError;
1430 }
1431 break;
1432 }
1433
1434 metrics::ReportUpdateCheckMetrics(system_state_,
1435 result, reaction, download_error_code);
1436}
1437
Chris Sosa77f79e82014-06-02 18:16:24 -07001438bool OmahaRequestAction::ShouldIgnoreUpdate(
1439 const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001440 // Note: policy decision to not update to a version we rolled back from.
1441 string rollback_version =
1442 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001443 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001444 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001445 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001446 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1447 return true;
1448 }
1449 }
1450
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001451 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001452 LOG(INFO) << "Update is not allowed over current connection.";
1453 return true;
1454 }
1455
1456 // Note: We could technically delete the UpdateFirstSeenAt state when we
1457 // return true. If we do, it'll mean a device has to restart the
1458 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1459 // turned on again. On the other hand, it also increases the chance of update
1460 // starvation if an admin turns AU on/off more frequently. We choose to err on
1461 // the side of preventing starvation at the cost of not applying scattering in
1462 // those cases.
1463 return false;
1464}
1465
1466bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
1467 NetworkConnectionType type;
1468 NetworkTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001469 ConnectionManagerInterface* connection_manager =
1470 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001471 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001472 LOG(INFO) << "We could not determine our connection type. "
1473 << "Defaulting to allow updates.";
1474 return true;
1475 }
1476 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1477 LOG(INFO) << "We are connected via "
Alex Deymof6ee0162015-07-31 12:35:22 -07001478 << ConnectionManager::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001479 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1480 return is_allowed;
1481}
1482
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001483} // namespace chromeos_update_engine