blob: 3d2dac1baebd09a548446e6aadcdcb2bdf1e80be [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"
Sen Jiang255e22b2016-05-20 16:15:29 -070043#include "update_engine/connection_manager_interface.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 Deymo14ad88e2016-06-29 12:30:14 -070080// X-GoogleUpdate headers.
81static const char* kXGoogleUpdateInteractivity = "X-GoogleUpdate-Interactivity";
82static const char* kXGoogleUpdateAppId = "X-GoogleUpdate-AppId";
83static const char* kXGoogleUpdateUpdater = "X-GoogleUpdate-Updater";
84
Alex Deymob3fa53b2016-04-18 19:57:58 -070085// updatecheck attributes (without the underscore prefix).
86static const char* kEolAttr = "eol";
87
Alex Deymoac41a822015-09-15 20:52:53 -070088namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +000089
Darin Petkov1cbd78f2010-07-29 12:38:34 -070090// Returns an XML ping element attribute assignment with attribute
91// |name| and value |ping_days| if |ping_days| has a value that needs
92// to be sent, or an empty string otherwise.
93string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -070094 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -070095 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -070096 return "";
97}
98
99// Returns an XML ping element if any of the elapsed days need to be
100// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700101string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700102 string ping_active = GetPingAttribute("a", ping_active_days);
103 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
104 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700105 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700106 ping_active.c_str(),
107 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700108 }
109 return "";
110}
111
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700112// Returns an XML that goes into the body of the <app> element of the Omaha
113// request based on the given parameters.
114string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700115 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700116 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700117 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700118 int ping_active_days,
119 int ping_roll_call_days,
120 PrefsInterface* prefs) {
121 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700122 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700123 if (include_ping)
124 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700125 if (!ping_only) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700126 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700127 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700128 "></updatecheck>\n",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700129 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700130
Darin Petkov265f2902011-05-09 15:17:40 -0700131 // If this is the first update check after a reboot following a previous
132 // update, generate an event containing the previous version number. If
133 // the previous version preference file doesn't exist the event is still
134 // generated with a previous version of 0.0.0.0 -- this is relevant for
135 // older clients or new installs. The previous version event is not sent
136 // for ping-only requests because they come before the client has
Alex Deymo87c08862015-10-30 21:56:55 -0700137 // rebooted. The previous version event is also not sent if it was already
138 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700139 string prev_version;
140 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
141 prev_version = "0.0.0.0";
142 }
Alex Deymo87c08862015-10-30 21:56:55 -0700143 // We only store a non-empty previous version value after a successful
144 // update in the previous boot. After reporting it back to the server,
145 // we clear the previous version value so it doesn't get reported again.
146 if (!prev_version.empty()) {
147 app_body += base::StringPrintf(
148 " <event eventtype=\"%d\" eventresult=\"%d\" "
149 "previousversion=\"%s\"></event>\n",
Alex Deymo9fded1e2015-11-05 12:31:19 -0800150 OmahaEvent::kTypeRebootedAfterUpdate,
151 OmahaEvent::kResultSuccess,
Alex Deymo87c08862015-10-30 21:56:55 -0700152 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
153 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
154 << "Unable to reset the previous version.";
155 }
Darin Petkov95508da2011-01-05 12:42:29 -0800156 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700157 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800158 // The error code is an optional attribute so append it only if the result
159 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700160 string error_code;
161 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700162 error_code = base::StringPrintf(" errorcode=\"%d\"",
163 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700164 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700165 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700166 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700167 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700168 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700169
170 return app_body;
171}
172
Alex Deymo8e18f932015-03-27 16:16:59 -0700173// Returns the cohort* argument to include in the <app> tag for the passed
174// |arg_name| and |prefs_key|, if any. The return value is suitable to
175// concatenate to the list of arguments and includes a space at the end.
176string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700177 const string arg_name,
178 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700179 // There's nothing wrong with not having a given cohort setting, so we check
180 // existance first to avoid the warning log message.
181 if (!prefs->Exists(prefs_key))
182 return "";
183 string cohort_value;
184 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
185 return "";
186 // This is a sanity check to avoid sending a huge XML file back to Ohama due
187 // to a compromised stateful partition making the update check fail in low
188 // network environments envent after a reboot.
189 if (cohort_value.size() > 1024) {
190 LOG(WARNING) << "The omaha cohort setting " << arg_name
191 << " has a too big value, which must be an error or an "
192 "attacker trying to inhibit updates.";
193 return "";
194 }
195
Alex Deymob0d74eb2015-03-30 17:59:17 -0700196 string escaped_xml_value;
197 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
198 LOG(WARNING) << "The omaha cohort setting " << arg_name
199 << " is ASCII-7 invalid, ignoring it.";
200 return "";
201 }
202
Alex Deymo8e18f932015-03-27 16:16:59 -0700203 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700204 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700205}
206
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700207// Returns an XML that corresponds to the entire <app> node of the Omaha
208// request based on the given parameters.
209string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700210 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700211 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700212 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700213 int ping_active_days,
214 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800215 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700216 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700217 string app_body = GetAppBody(event, params, ping_only, include_ping,
218 ping_active_days, ping_roll_call_days,
219 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700220 string app_versions;
221
222 // If we are upgrading to a more stable channel and we are allowed to do
223 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
224 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700225 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700226 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
227 << "on downgrading to the version in the more stable channel";
228 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700229 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700230 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700231 app_versions = "version=\"" +
232 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700233 }
234
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700235 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700236 string app_channels =
237 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
238 if (params->current_channel() != download_channel) {
239 app_channels += "from_track=\"" + XmlEncodeWithDefault(
240 params->current_channel(), "") + "\" ";
241 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700242
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700243 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700244
David Zeuthen639aa362014-02-03 16:23:44 -0800245 // If install_date_days is not set (e.g. its value is -1 ), don't
246 // include the attribute.
247 string install_date_in_days_str = "";
248 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700249 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
250 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800251 }
252
Alex Deymo8e18f932015-03-27 16:16:59 -0700253 string app_cohort_args;
254 app_cohort_args += GetCohortArgXml(system_state->prefs(),
255 "cohort", kPrefsOmahaCohort);
256 app_cohort_args += GetCohortArgXml(system_state->prefs(),
257 "cohorthint", kPrefsOmahaCohortHint);
258 app_cohort_args += GetCohortArgXml(system_state->prefs(),
259 "cohortname", kPrefsOmahaCohortName);
260
Alex Deymob0d74eb2015-03-30 17:59:17 -0700261 string app_xml = " <app "
262 "appid=\"" + XmlEncodeWithDefault(params->GetAppId(), "") + "\" " +
263 app_cohort_args +
264 app_versions +
265 app_channels +
266 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
267 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
268 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
269 "delta_okay=\"" + delta_okay_str + "\" "
270 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
271 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
272 install_date_in_days_str +
273 ">\n" +
274 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700275 " </app>\n";
276
277 return app_xml;
278}
279
280// Returns an XML that corresponds to the entire <os> node of the Omaha
281// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700282string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700283 string os_xml =" <os "
284 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
285 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
286 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
287 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700288 return os_xml;
289}
290
291// Returns an XML that corresponds to the entire Omaha request based on the
292// given parameters.
293string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700294 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700295 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700296 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700297 int ping_active_days,
298 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800299 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700300 SystemState* system_state) {
301 string os_xml = GetOsXml(params);
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700302 string app_xml = GetAppXml(event, params, ping_only, include_ping,
303 ping_active_days, ping_roll_call_days,
304 install_date_in_days, system_state);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700305
Alex Vakulenko75039d72014-03-25 12:36:28 -0700306 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700307 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700308
Alex Deymoac41a822015-09-15 20:52:53 -0700309 string updater_version = XmlEncodeWithDefault(
310 base::StringPrintf("%s-%s",
311 constants::kOmahaUpdaterID,
312 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700313 string request_xml =
314 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700315 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700316 "version=\"" + updater_version + "\" "
317 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700318 install_source +
319 "ismachine=\"1\">\n") +
320 os_xml +
321 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700322 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700323
324 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000325}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700326
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700327} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000328
David Zeuthene8ed8632014-07-24 13:38:10 -0400329// Struct used for holding data obtained when parsing the XML.
330struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400331 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
332
333 // Pointer to the expat XML_Parser object.
334 XML_Parser xml_parser;
335
David Zeuthene8ed8632014-07-24 13:38:10 -0400336 // This is the state of the parser as it's processing the XML.
337 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400338 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400339 string current_path;
340
341 // These are the values extracted from the XML.
Alex Deymo8e18f932015-03-27 16:16:59 -0700342 string app_cohort;
343 string app_cohorthint;
344 string app_cohortname;
345 bool app_cohort_set = false;
346 bool app_cohorthint_set = false;
347 bool app_cohortname_set = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400348 string updatecheck_status;
349 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700350 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400351 string daystart_elapsed_days;
352 string daystart_elapsed_seconds;
353 vector<string> url_codebase;
354 string package_name;
355 string package_size;
356 string manifest_version;
357 map<string, string> action_postinstall_attrs;
358};
359
360namespace {
361
362// Callback function invoked by expat.
363void ParserHandlerStart(void* user_data, const XML_Char* element,
364 const XML_Char** attr) {
365 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
366
367 if (data->failed)
368 return;
369
370 data->current_path += string("/") + element;
371
372 map<string, string> attrs;
373 if (attr != nullptr) {
374 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
375 string key = attr[n];
376 string value = attr[n + 1];
377 attrs[key] = value;
378 }
379 }
380
Alex Deymo8e18f932015-03-27 16:16:59 -0700381 if (data->current_path == "/response/app") {
382 if (attrs.find("cohort") != attrs.end()) {
383 data->app_cohort_set = true;
384 data->app_cohort = attrs["cohort"];
385 }
386 if (attrs.find("cohorthint") != attrs.end()) {
387 data->app_cohorthint_set = true;
388 data->app_cohorthint = attrs["cohorthint"];
389 }
390 if (attrs.find("cohortname") != attrs.end()) {
391 data->app_cohortname_set = true;
392 data->app_cohortname = attrs["cohortname"];
393 }
394 } else if (data->current_path == "/response/app/updatecheck") {
David Zeuthene8ed8632014-07-24 13:38:10 -0400395 // There is only supposed to be a single <updatecheck> element.
396 data->updatecheck_status = attrs["status"];
397 data->updatecheck_poll_interval = attrs["PollInterval"];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700398 // Omaha sends arbitrary key-value pairs as extra attributes starting with
399 // an underscore.
400 for (const auto& attr : attrs) {
401 if (!attr.first.empty() && attr.first[0] == '_')
402 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
403 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400404 } else if (data->current_path == "/response/daystart") {
405 // Get the install-date.
406 data->daystart_elapsed_days = attrs["elapsed_days"];
407 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
408 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
409 // Look at all <url> elements.
410 data->url_codebase.push_back(attrs["codebase"]);
411 } else if (data->package_name.empty() && data->current_path ==
412 "/response/app/updatecheck/manifest/packages/package") {
413 // Only look at the first <package>.
414 data->package_name = attrs["name"];
415 data->package_size = attrs["size"];
416 } else if (data->current_path == "/response/app/updatecheck/manifest") {
417 // Get the version.
418 data->manifest_version = attrs[kTagVersion];
419 } else if (data->current_path ==
420 "/response/app/updatecheck/manifest/actions/action") {
421 // We only care about the postinstall action.
422 if (attrs["event"] == "postinstall") {
423 data->action_postinstall_attrs = attrs;
424 }
425 }
426}
427
428// Callback function invoked by expat.
429void ParserHandlerEnd(void* user_data, const XML_Char* element) {
430 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
431 if (data->failed)
432 return;
433
434 const string path_suffix = string("/") + element;
435
Alex Vakulenko0103c362016-01-20 07:56:15 -0800436 if (!base::EndsWith(data->current_path, path_suffix,
437 base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400438 LOG(ERROR) << "Unexpected end element '" << element
439 << "' with current_path='" << data->current_path << "'";
440 data->failed = true;
441 return;
442 }
443 data->current_path.resize(data->current_path.size() - path_suffix.size());
444}
445
David Zeuthenf3e28012014-08-26 18:23:52 -0400446// Callback function invoked by expat.
447//
448// This is called for entity declarations. Since Omaha is guaranteed
449// to never return any XML with entities our course of action is to
450// just stop parsing. This avoids potential resource exhaustion
451// problems AKA the "billion laughs". CVE-2013-0340.
452void ParserHandlerEntityDecl(void *user_data,
453 const XML_Char *entity_name,
454 int is_parameter_entity,
455 const XML_Char *value,
456 int value_length,
457 const XML_Char *base,
458 const XML_Char *system_id,
459 const XML_Char *public_id,
460 const XML_Char *notation_name) {
461 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
462
463 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
464 data->failed = true;
465 data->entity_decl = true;
466 XML_StopParser(data->xml_parser, false);
467}
468
David Zeuthene8ed8632014-07-24 13:38:10 -0400469} // namespace
470
Alex Deymob0d74eb2015-03-30 17:59:17 -0700471bool XmlEncode(const string& input, string* output) {
472 if (std::find_if(input.begin(), input.end(),
473 [](const char c){return c & 0x80;}) != input.end()) {
474 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
475 utils::HexDumpString(input);
476 return false;
477 }
Alex Deymocc457852015-06-18 18:35:50 -0700478 output->clear();
479 // We need at least input.size() space in the output, but the code below will
480 // handle it if we need more.
481 output->reserve(input.size());
482 for (char c : input) {
483 switch (c) {
484 case '\"':
485 output->append("&quot;");
486 break;
487 case '\'':
488 output->append("&apos;");
489 break;
490 case '&':
491 output->append("&amp;");
492 break;
493 case '<':
494 output->append("&lt;");
495 break;
496 case '>':
497 output->append("&gt;");
498 break;
499 default:
500 output->push_back(c);
501 }
502 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700503 return true;
504}
505
506string XmlEncodeWithDefault(const string& input, const string& default_value) {
507 string output;
508 if (XmlEncode(input, &output))
509 return output;
510 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000511}
512
Alex Deymoc1c17b42015-11-23 03:53:15 -0300513OmahaRequestAction::OmahaRequestAction(
514 SystemState* system_state,
515 OmahaEvent* event,
516 std::unique_ptr<HttpFetcher> http_fetcher,
517 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800518 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700519 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300520 http_fetcher_(std::move(http_fetcher)),
Thieu Le116fda32011-04-19 11:01:54 -0700521 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700522 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700523 ping_roll_call_days_(0) {
524 params_ = system_state->request_params();
525}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000526
Darin Petkov6a5b3222010-07-13 14:55:28 -0700527OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000528
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700529// Calculates the value to use for the ping days parameter.
530int OmahaRequestAction::CalculatePingDays(const string& key) {
531 int days = kNeverPinged;
532 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800533 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700534 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
535 if (days < 0) {
536 // If |days| is negative, then the system clock must have jumped
537 // back in time since the ping was sent. Mark the value so that
538 // it doesn't get sent to the server but we still update the
539 // last ping daystart preference. This way the next ping time
540 // will be correct, hopefully.
541 days = kPingTimeJump;
542 LOG(WARNING) <<
543 "System clock jumped back in time. Resetting ping daystarts.";
544 }
545 }
546 return days;
547}
548
549void OmahaRequestAction::InitPingDays() {
550 // We send pings only along with update checks, not with events.
551 if (IsEvent()) {
552 return;
553 }
554 // TODO(petkov): Figure a way to distinguish active use pings
555 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700556 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700557 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
558 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
559}
560
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700561bool OmahaRequestAction::ShouldPing() const {
562 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
563 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
564 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
565 if (powerwash_count > 0) {
566 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
567 << "powerwash_count is " << powerwash_count;
568 return false;
569 }
570 return true;
571 }
572 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
573}
574
David Zeuthen639aa362014-02-03 16:23:44 -0800575// static
576int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
577 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700578 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800579 return -1;
580
581 // If we have the value stored on disk, just return it.
582 int64_t stored_value;
583 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
584 // Convert and sanity-check.
585 int install_date_days = static_cast<int>(stored_value);
586 if (install_date_days >= 0)
587 return install_date_days;
588 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
589 << install_date_days << " looks suspicious.";
590 prefs->Delete(kPrefsInstallDateDays);
591 }
592
593 // Otherwise, if OOBE is not complete then do nothing and wait for
594 // ParseResponse() to call ParseInstallDate() and then
595 // PersistInstallDate() to set the kPrefsInstallDateDays state
596 // variable. Once that is done, we'll then report back in future
597 // Omaha requests. This works exactly because OOBE triggers an
598 // update check.
599 //
600 // However, if OOBE is complete and the kPrefsInstallDateDays state
601 // variable is not set, there are two possibilities
602 //
603 // 1. The update check in OOBE failed so we never got a response
604 // from Omaha (no network etc.); or
605 //
606 // 2. OOBE was done on an older version that didn't write to the
607 // kPrefsInstallDateDays state variable.
608 //
609 // In both cases, we approximate the install date by simply
610 // inspecting the timestamp of when OOBE happened.
611
612 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700613 if (!system_state->hardware()->IsOOBEEnabled() ||
614 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800615 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700616 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800617 return -1;
618 }
619
620 int num_days;
621 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
622 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
623 << "as its value '" << utils::ToString(time_of_oobe)
624 << "' looks suspicious.";
625 return -1;
626 }
627
628 // Persist this to disk, for future use.
629 if (!OmahaRequestAction::PersistInstallDate(system_state,
630 num_days,
631 kProvisionedFromOOBEMarker))
632 return -1;
633
634 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
635 << num_days << " days";
636
637 return num_days;
638}
639
Darin Petkov6a5b3222010-07-13 14:55:28 -0700640void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000641 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700642 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700643 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700644 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700645 return;
646 }
David Zeuthen639aa362014-02-03 16:23:44 -0800647
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700648 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700649 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700650 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700651 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700652 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800653 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800654 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700655 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700656
Alex Deymo14ad88e2016-06-29 12:30:14 -0700657 // Set X-GoogleUpdate headers.
658 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
659 params_->interactive() ? "fg" : "bg");
660 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
661 http_fetcher_->SetHeader(
662 kXGoogleUpdateUpdater,
663 base::StringPrintf(
664 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
665
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800666 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
667 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700668 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700669 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700670 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000671}
672
Darin Petkov6a5b3222010-07-13 14:55:28 -0700673void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000674 http_fetcher_->TerminateTransfer();
675}
676
677// We just store the response in the buffer. Once we've received all bytes,
678// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700679void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800680 const void* bytes,
681 size_t length) {
682 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
683 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000684}
685
686namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000687
688// Parses a 64 bit base-10 int from a string and returns it. Returns 0
689// on error. If the string contains "0", that's indistinguishable from
690// error.
691off_t ParseInt(const string& str) {
692 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700693 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000694 if (rc < 1) {
695 // failure
696 return 0;
697 }
698 return ret;
699}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700700
David Zeuthene8ed8632014-07-24 13:38:10 -0400701// Parses |str| and returns |true| if, and only if, its value is "true".
702bool ParseBool(const string& str) {
703 return str == "true";
704}
705
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700706// Update the last ping day preferences based on the server daystart
707// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400708bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700709 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400710 TEST_AND_RETURN_FALSE(
711 base::StringToInt64(parser_data->daystart_elapsed_seconds,
712 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700713 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
714
715 // Remember the local time that matches the server's last midnight
716 // time.
717 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
718 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
719 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
720 return true;
721}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700722} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000723
David Zeuthene8ed8632014-07-24 13:38:10 -0400724bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700725 OmahaResponse* output_object,
726 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400727 if (parser_data->updatecheck_status.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700728 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700729 return false;
730 }
731
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800732 // chromium-os:37289: The PollInterval is not supported by Omaha server
733 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700734 // slow down the request rate from the server-side. Note that the PollInterval
735 // is not persisted, so it has to be sent by the server on every response to
736 // guarantee that the scheduler uses this value (otherwise, if the device got
737 // rebooted after the last server-indicated value, it'll revert to the default
738 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
739 // based on the assumption that we perform an update check every hour so that
740 // the max value of 8 will roughly be equivalent to one work day. If we decide
741 // to use PollInterval permanently, we should update the
742 // max_update_checks_allowed to take PollInterval into account. Note: The
743 // parsing for PollInterval happens even before parsing of the status because
744 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400745 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700746 &output_object->poll_interval);
747
David Zeuthen639aa362014-02-03 16:23:44 -0800748 // Check for the "elapsed_days" attribute in the "daystart"
749 // element. This is the number of days since Jan 1 2007, 0:00
750 // PST. If we don't have a persisted value of the Omaha InstallDate,
751 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400752 if (ParseInstallDate(parser_data, output_object) &&
753 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800754 // Since output_object->install_date_days is never negative, the
755 // elapsed_days -> install-date calculation is reduced to simply
756 // rounding down to the nearest number divisible by 7.
757 int remainder = output_object->install_date_days % 7;
758 int install_date_days_rounded =
759 output_object->install_date_days - remainder;
760 if (PersistInstallDate(system_state_,
761 install_date_days_rounded,
762 kProvisionedFromOmahaResponse)) {
763 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
764 << install_date_days_rounded << " days";
765 }
766 }
767
Alex Deymo00d79ac2015-06-29 15:41:49 -0700768 // We persist the cohorts sent by omaha even if the status is "noupdate".
769 if (parser_data->app_cohort_set)
770 PersistCohortData(kPrefsOmahaCohort, parser_data->app_cohort);
771 if (parser_data->app_cohorthint_set)
772 PersistCohortData(kPrefsOmahaCohortHint, parser_data->app_cohorthint);
773 if (parser_data->app_cohortname_set)
774 PersistCohortData(kPrefsOmahaCohortName, parser_data->app_cohortname);
775
Alex Deymob3fa53b2016-04-18 19:57:58 -0700776 // Parse the updatecheck attributes.
777 PersistEolStatus(parser_data->updatecheck_attrs);
778
David Zeuthene8ed8632014-07-24 13:38:10 -0400779 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700780 return false;
781
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800782 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
783 // appends the package name to the URLs populated in this method.
David Zeuthene8ed8632014-07-24 13:38:10 -0400784 if (!ParseUrls(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700785 return false;
786
David Zeuthene8ed8632014-07-24 13:38:10 -0400787 if (!ParsePackage(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700788 return false;
789
David Zeuthene8ed8632014-07-24 13:38:10 -0400790 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700791 return false;
792
793 return true;
794}
795
David Zeuthene8ed8632014-07-24 13:38:10 -0400796bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700797 OmahaResponse* output_object,
798 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400799 const string& status = parser_data->updatecheck_status;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700800 if (status == "noupdate") {
801 LOG(INFO) << "No update.";
802 output_object->update_exists = false;
803 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700804 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700805 return false;
806 }
807
808 if (status != "ok") {
809 LOG(ERROR) << "Unknown Omaha response status: " << status;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700810 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700811 return false;
812 }
813
814 return true;
815}
816
David Zeuthene8ed8632014-07-24 13:38:10 -0400817bool OmahaRequestAction::ParseUrls(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700818 OmahaResponse* output_object,
819 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400820 if (parser_data->url_codebase.empty()) {
821 LOG(ERROR) << "No Omaha Response URLs";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700822 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700823 return false;
824 }
825
David Zeuthene8ed8632014-07-24 13:38:10 -0400826 LOG(INFO) << "Found " << parser_data->url_codebase.size() << " url(s)";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800827 output_object->payload_urls.clear();
David Zeuthene8ed8632014-07-24 13:38:10 -0400828 for (const auto& codebase : parser_data->url_codebase) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800829 if (codebase.empty()) {
830 LOG(ERROR) << "Omaha Response URL has empty codebase";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700831 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800832 return false;
833 }
834 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700835 }
836
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700837 return true;
838}
839
David Zeuthene8ed8632014-07-24 13:38:10 -0400840bool OmahaRequestAction::ParsePackage(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700841 OmahaResponse* output_object,
842 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400843 if (parser_data->package_name.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700844 LOG(ERROR) << "Omaha Response has empty package name";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700845 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700846 return false;
847 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800848
849 // Append the package name to each URL in our list so that we don't
850 // propagate the urlBase vs packageName distinctions beyond this point.
851 // From now on, we only need to use payload_urls.
David Zeuthene8ed8632014-07-24 13:38:10 -0400852 for (auto& payload_url : output_object->payload_urls)
853 payload_url += parser_data->package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700854
855 // Parse the payload size.
David Zeuthene8ed8632014-07-24 13:38:10 -0400856 off_t size = ParseInt(parser_data->package_size);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700857 if (size <= 0) {
858 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
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 output_object->size = size;
863
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800864 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700865
866 return true;
867}
868
David Zeuthene8ed8632014-07-24 13:38:10 -0400869bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700870 OmahaResponse* output_object,
871 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400872 output_object->version = parser_data->manifest_version;
Chris Sosa3b748432013-06-20 16:42:59 -0700873 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700874 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700875 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700876 return false;
877 }
878
879 LOG(INFO) << "Received omaha response to update to version "
880 << output_object->version;
881
David Zeuthene8ed8632014-07-24 13:38:10 -0400882 map<string, string> attrs = parser_data->action_postinstall_attrs;
883 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700884 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700885 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700886 return false;
887 }
888
David Zeuthene8ed8632014-07-24 13:38:10 -0400889 output_object->hash = attrs[kTagSha256];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700890 if (output_object->hash.empty()) {
891 LOG(ERROR) << "Omaha Response has empty sha256 value";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700892 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700893 return false;
894 }
895
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800896 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -0400897 output_object->more_info_url = attrs[kTagMoreInfo];
898 output_object->metadata_size = ParseInt(attrs[kTagMetadataSize]);
899 output_object->metadata_signature = attrs[kTagMetadataSignatureRsa];
900 output_object->prompt = ParseBool(attrs[kTagPrompt]);
901 output_object->deadline = attrs[kTagDeadline];
902 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700903 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -0400904 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700905 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -0400906 ParseBool(attrs[kTagDisableP2PForSharing]);
907 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800908
David Zeuthene8ed8632014-07-24 13:38:10 -0400909 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800910 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800911 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700912
David Zeuthene8ed8632014-07-24 13:38:10 -0400913 output_object->is_delta_payload = ParseBool(attrs[kTagIsDeltaPayload]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800914
915 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -0400916 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800917
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700918 return true;
919}
920
David Zeuthene8ed8632014-07-24 13:38:10 -0400921// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000922// and fill in the appropriate fields of the output object. Also, notifies
923// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700924void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
925 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000926 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800927 string current_response(response_buffer_.begin(), response_buffer_.end());
928 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700929
Gilad Arnold74b5f552014-10-07 08:17:16 -0700930 PayloadStateInterface* const payload_state = system_state_->payload_state();
931
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700932 // Events are best effort transactions -- assume they always succeed.
933 if (IsEvent()) {
934 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700935 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700936 return;
937 }
938
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700939 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700940 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700941 int code = GetHTTPResponseCode();
942 // Makes sure we send sane error values.
943 if (code < 0 || code >= 1000) {
944 code = 999;
945 }
David Zeuthena99981f2013-04-29 13:42:47 -0700946 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700947 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000948 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700949 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000950
David Zeuthene8ed8632014-07-24 13:38:10 -0400951 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400952 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400953 XML_SetUserData(parser, &parser_data);
954 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400955 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800956 XML_Status res = XML_Parse(
957 parser,
958 reinterpret_cast<const char*>(response_buffer_.data()),
959 response_buffer_.size(),
960 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400961 XML_ParserFree(parser);
962
963 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700964 LOG(ERROR) << "Omaha response not valid XML: "
965 << XML_ErrorString(XML_GetErrorCode(parser))
966 << " at line " << XML_GetCurrentLineNumber(parser)
967 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400968 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
969 if (response_buffer_.empty()) {
970 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
971 } else if (parser_data.entity_decl) {
972 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
973 }
974 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000975 return;
976 }
977
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700978 // Update the last ping day preferences based on the server daystart response
979 // even if we didn't send a ping. Omaha always includes the daystart in the
980 // response, but log the error if it didn't.
981 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
982 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700983
Thieu Le116fda32011-04-19 11:01:54 -0700984 if (!HasOutputPipe()) {
985 // Just set success to whether or not the http transfer succeeded,
986 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700987 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700988 return;
989 }
990
Darin Petkov6a5b3222010-07-13 14:55:28 -0700991 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400992 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000993 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700994 output_object.update_exists = true;
995 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000996
Chris Sosa77f79e82014-06-02 18:16:24 -0700997 if (ShouldIgnoreUpdate(output_object)) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700998 output_object.update_exists = false;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700999 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001000 return;
1001 }
1002
David Zeuthen8f191b22013-08-06 12:27:50 -07001003 // If Omaha says to disable p2p, respect that
1004 if (output_object.disable_p2p_for_downloading) {
1005 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1006 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001007 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001008 }
1009 if (output_object.disable_p2p_for_sharing) {
1010 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1011 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001012 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001013 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001014
1015 // Update the payload state with the current response. The payload state
1016 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001017 // from what's stored already. We are updating the payload state as late
1018 // as possible in this method so that if a new release gets pushed and then
1019 // got pulled back due to some issues, we don't want to clear our internal
1020 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001021 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001022
David Zeuthen8f191b22013-08-06 12:27:50 -07001023 // It could be we've already exceeded the deadline for when p2p is
1024 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001025 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001026 payload_state->P2PNewAttempt();
1027 if (!payload_state->P2PAttemptAllowed()) {
1028 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1029 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001030 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001031 }
1032 }
1033
1034 // From here on, we'll complete stuff in CompleteProcessing() so
1035 // disable |completer| since we'll create a new one in that
1036 // function.
1037 completer.set_should_complete(false);
1038
1039 // If we're allowed to use p2p for downloading we do not pay
1040 // attention to wall-clock-based waiting if the URL is indeed
1041 // available via p2p. Therefore, check if the file is available via
1042 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001043 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001044 LookupPayloadViaP2P(output_object);
1045 } else {
1046 CompleteProcessing();
1047 }
1048}
1049
1050void OmahaRequestAction::CompleteProcessing() {
1051 ScopedActionCompleter completer(processor_, this);
1052 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1053 PayloadStateInterface* payload_state = system_state_->payload_state();
1054
Alex Deymo46a9aae2016-05-04 20:20:11 -07001055 if (system_state_->hardware()->IsOOBEEnabled() &&
1056 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
Kevin Cernekeec5081a82016-04-08 12:29:52 -07001057 output_object.deadline.empty() &&
1058 params_->app_version() != "ForcedUpdate") {
Kevin Cernekee2494e282016-03-29 18:03:53 -07001059 output_object.update_exists = false;
1060 LOG(INFO) << "Ignoring non-critical Omaha updates until OOBE is done.";
1061 completer.set_code(ErrorCode::kNonCriticalUpdateInOOBE);
1062 return;
1063 }
1064
David Zeuthen8f191b22013-08-06 12:27:50 -07001065 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001066 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001067 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001068 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001069 return;
1070 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001071
Chris Sosa20f005c2013-09-05 13:53:08 -07001072 if (payload_state->ShouldBackoffDownload()) {
1073 output_object.update_exists = false;
1074 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1075 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001076 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001077 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001078 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001079 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001080}
1081
1082void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1083 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1084 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001085 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001086 } else {
1087 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1088 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001089 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001090 }
1091 CompleteProcessing();
1092}
1093
1094void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001095 // If the device is in the middle of an update, the state variables
1096 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1097 // tracks the offset and length of the operation currently in
1098 // progress. The offset is based from the end of the manifest which
1099 // is kPrefsManifestMetadataSize bytes long.
1100 //
1101 // To make forward progress and avoid deadlocks, we need to find a
1102 // peer that has at least the entire operation we're currently
1103 // working on. Otherwise we may end up in a situation where two
1104 // devices bounce back and forth downloading from each other,
1105 // neither making any forward progress until one of them decides to
1106 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1107 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001108 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001109 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001110 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001111 int64_t next_data_offset = 0;
1112 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001113 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001114 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1115 &manifest_metadata_size) &&
1116 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001117 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1118 &manifest_signature_size) &&
1119 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001120 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001121 &next_data_offset) &&
1122 next_data_offset != -1 &&
1123 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1124 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001125 minimum_size = manifest_metadata_size + manifest_signature_size +
1126 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001127 }
1128
1129 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001130 if (system_state_->p2p_manager()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001131 LOG(INFO) << "Checking if payload is available via p2p, file_id="
1132 << file_id << " minimum_size=" << minimum_size;
1133 system_state_->p2p_manager()->LookupUrlForFile(
1134 file_id,
1135 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001136 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001137 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1138 base::Unretained(this)));
1139 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001140}
1141
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001142bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001143 if (params_->interactive()) {
1144 LOG(INFO) << "Not deferring download because update is interactive.";
1145 return false;
1146 }
1147
David Zeuthen8f191b22013-08-06 12:27:50 -07001148 // If we're using p2p to download _and_ we have a p2p URL, we never
1149 // defer the download. This is because the download will always
1150 // happen from a peer on the LAN and we've been waiting in line for
1151 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001152 const PayloadStateInterface* payload_state = system_state_->payload_state();
1153 if (payload_state->GetUsingP2PForDownloading() &&
1154 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001155 LOG(INFO) << "Download not deferred because download "
1156 << "will happen from a local peer (via p2p).";
1157 return false;
1158 }
1159
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001160 // We should defer the downloads only if we've first satisfied the
1161 // wall-clock-based-waiting period and then the update-check-based waiting
1162 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001163 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001164 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1165 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001166 return false;
1167 }
1168
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001169 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001170 case kWallClockWaitNotSatisfied:
1171 // We haven't even satisfied the first condition, passing the
1172 // wall-clock-based waiting period, so we should defer the downloads
1173 // until that happens.
1174 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1175 return true;
1176
1177 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1178 LOG(INFO) << "wall-clock-based-wait satisfied and "
1179 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001180 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001181
1182 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1183 // Wall-clock-based waiting period is satisfied, and it's determined
1184 // that we do not need the update-check-based wait. so no need to
1185 // defer downloads.
1186 LOG(INFO) << "wall-clock-based-wait satisfied and "
1187 << "update-check-based-wait is not required.";
1188 return false;
1189
1190 default:
1191 // Returning false for this default case so we err on the
1192 // side of downloading updates than deferring in case of any bugs.
1193 NOTREACHED();
1194 return false;
1195 }
1196}
1197
1198OmahaRequestAction::WallClockWaitResult
1199OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001200 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001201 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001202 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001203
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001204 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1205 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1206 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001207 // Note: This timestamp could be that of ANY update we saw in the past
1208 // (not necessarily this particular update we're considering to apply)
1209 // but never got to apply because of some reason (e.g. stop AU policy,
1210 // updates being pulled out from Omaha, changes in target version prefix,
1211 // new update being rolled out, etc.). But for the purposes of scattering
1212 // it doesn't matter which update the timestamp corresponds to. i.e.
1213 // the clock starts ticking the first time we see an update and we're
1214 // ready to apply when the random wait period is satisfied relative to
1215 // that first seen timestamp.
1216 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1217 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1218 << utils::ToString(update_first_seen_at);
1219 } else {
1220 // This seems like an unexpected error where the persisted value exists
1221 // but it's not readable for some reason. Just skip scattering in this
1222 // case to be safe.
1223 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1224 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1225 }
1226 } else {
Sen Jiang7c1171e2016-06-23 11:35:40 -07001227 update_first_seen_at = system_state_->clock()->GetWallclockTime();
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001228 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001229 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1230 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001231 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1232 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001233 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001234 // This seems like an unexpected error where the value cannot be
1235 // persisted for some reason. Just skip scattering in this
1236 // case to be safe.
1237 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1238 << utils::ToString(update_first_seen_at)
1239 << " cannot be persisted";
1240 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1241 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001242 }
1243
Sen Jiang7c1171e2016-06-23 11:35:40 -07001244 TimeDelta elapsed_time =
1245 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1246 TimeDelta max_scatter_period =
1247 TimeDelta::FromDays(output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001248
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001249 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001250 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001251 << ", Time Elapsed = "
1252 << utils::FormatSecs(elapsed_time.InSeconds())
1253 << ", MaxDaysToScatter = "
1254 << max_scatter_period.InDays();
1255
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001256 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001257 // The deadline is set for all rules which serve a delta update from a
1258 // previous FSI, which means this update will be applied mostly in OOBE
1259 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1260 // quickly.
1261 LOG(INFO) << "Not scattering as deadline flag is set";
1262 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1263 }
1264
1265 if (max_scatter_period.InDays() == 0) {
1266 // This means the Omaha rule creator decides that this rule
1267 // should not be scattered irrespective of the policy.
1268 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1269 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1270 }
1271
1272 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001273 // This means we've waited more than the upperbound wait in the rule
1274 // from the time we first saw a valid update available to us.
1275 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001276 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1277 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1278 }
1279
1280 // This means we are required to participate in scattering.
1281 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001282 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001283 if (remaining_wait_time.InSeconds() <= 0) {
1284 // Yes, it's our turn now.
1285 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1286
1287 // But we can't download until the update-check-count-based wait is also
1288 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001289 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001290 kWallClockWaitDoneButUpdateCheckWaitRequired :
1291 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1292 }
1293
1294 // Not our turn yet, so we have to wait until our turn to
1295 // help scatter the downloads across all clients of the enterprise.
1296 LOG(INFO) << "Update deferred for another "
1297 << utils::FormatSecs(remaining_wait_time.InSeconds())
1298 << " per policy.";
1299 return kWallClockWaitNotSatisfied;
1300}
1301
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001302bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001303 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001304
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001305 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1306 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1307 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001308 // We are unable to read the update check count from file for some reason.
1309 // So let's proceed anyway so as to not stall the update.
1310 LOG(ERROR) << "Unable to read update check count. "
1311 << "Skipping update-check-count-based-wait.";
1312 return true;
1313 }
1314 } else {
1315 // This file does not exist. This means we haven't started our update
1316 // check count down yet, so this is the right time to start the count down.
1317 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001318 params_->min_update_checks_needed(),
1319 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001320
1321 LOG(INFO) << "Randomly picked update check count value = "
1322 << update_check_count_value;
1323
1324 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001325 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1326 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001327 // We weren't able to write the update check count file for some reason.
1328 // So let's proceed anyway so as to not stall the update.
1329 LOG(ERROR) << "Unable to write update check count. "
1330 << "Skipping update-check-count-based-wait.";
1331 return true;
1332 }
1333 }
1334
1335 if (update_check_count_value == 0) {
1336 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1337 return true;
1338 }
1339
1340 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001341 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001342 // We err on the side of skipping scattering logic instead of stalling
1343 // a machine from receiving any updates in case of any unexpected state.
1344 LOG(ERROR) << "Invalid value for update check count detected. "
1345 << "Skipping update-check-count-based-wait.";
1346 return true;
1347 }
1348
1349 // Legal value, we need to wait for more update checks to happen
1350 // until this becomes 0.
1351 LOG(INFO) << "Deferring Omaha updates for another "
1352 << update_check_count_value
1353 << " update checks per policy";
1354 return false;
1355}
1356
David Zeuthen639aa362014-02-03 16:23:44 -08001357// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001358bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001359 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001360 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001361 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001362 &elapsed_days))
1363 return false;
1364
1365 if (elapsed_days < 0)
1366 return false;
1367
1368 output_object->install_date_days = elapsed_days;
1369 return true;
1370}
1371
1372// static
1373bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1374 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001375 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001376 return false;
1377
1378 return prefs->Exists(kPrefsInstallDateDays);
1379}
1380
1381// static
1382bool OmahaRequestAction::PersistInstallDate(
1383 SystemState *system_state,
1384 int install_date_days,
1385 InstallDateProvisioningSource source) {
1386 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1387
1388 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001389 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001390 return false;
1391
1392 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1393 return false;
1394
Alex Deymoaf9a8632015-09-23 18:51:48 -07001395 string metric_name = metrics::kMetricInstallDateProvisioningSource;
David Zeuthen33bae492014-02-25 16:16:18 -08001396 system_state->metrics_lib()->SendEnumToUMA(
1397 metric_name,
1398 static_cast<int>(source), // Sample.
1399 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001400
1401 return true;
1402}
1403
Alex Deymo8e18f932015-03-27 16:16:59 -07001404bool OmahaRequestAction::PersistCohortData(
1405 const string& prefs_key,
1406 const string& new_value) {
1407 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1408 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1409 return system_state_->prefs()->Delete(prefs_key);
1410 } else if (!new_value.empty()) {
1411 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1412 return system_state_->prefs()->SetString(prefs_key, new_value);
1413 }
1414 return true;
1415}
1416
Alex Deymob3fa53b2016-04-18 19:57:58 -07001417bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
1418 auto eol_attr = attrs.find(kEolAttr);
1419 if (eol_attr != attrs.end()) {
1420 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1421 eol_attr->second);
1422 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1423 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1424 }
1425 return true;
1426}
1427
David Zeuthen33bae492014-02-25 16:16:18 -08001428void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1429 // We only want to report this on "update check".
1430 if (ping_only_ || event_ != nullptr)
1431 return;
1432
1433 metrics::CheckResult result = metrics::CheckResult::kUnset;
1434 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1435 metrics::DownloadErrorCode download_error_code =
1436 metrics::DownloadErrorCode::kUnset;
1437
1438 // Regular update attempt.
1439 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001440 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001441 // OK, we parsed the response successfully but that does
1442 // necessarily mean that an update is available.
1443 if (HasOutputPipe()) {
1444 const OmahaResponse& response = GetOutputObject();
1445 if (response.update_exists) {
1446 result = metrics::CheckResult::kUpdateAvailable;
1447 reaction = metrics::CheckReaction::kUpdating;
1448 } else {
1449 result = metrics::CheckResult::kNoUpdateAvailable;
1450 }
1451 } else {
1452 result = metrics::CheckResult::kNoUpdateAvailable;
1453 }
1454 break;
1455
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001456 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001457 result = metrics::CheckResult::kUpdateAvailable;
1458 reaction = metrics::CheckReaction::kIgnored;
1459 break;
1460
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001461 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001462 result = metrics::CheckResult::kUpdateAvailable;
1463 reaction = metrics::CheckReaction::kDeferring;
1464 break;
1465
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001466 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001467 result = metrics::CheckResult::kUpdateAvailable;
1468 reaction = metrics::CheckReaction::kBackingOff;
1469 break;
1470
1471 default:
1472 // We report two flavors of errors, "Download errors" and "Parsing
1473 // error". Try to convert to the former and if that doesn't work
1474 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001475 metrics::DownloadErrorCode tmp_error =
1476 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001477 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1478 result = metrics::CheckResult::kDownloadError;
1479 download_error_code = tmp_error;
1480 } else {
1481 result = metrics::CheckResult::kParsingError;
1482 }
1483 break;
1484 }
1485
1486 metrics::ReportUpdateCheckMetrics(system_state_,
1487 result, reaction, download_error_code);
1488}
1489
Chris Sosa77f79e82014-06-02 18:16:24 -07001490bool OmahaRequestAction::ShouldIgnoreUpdate(
1491 const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001492 // Note: policy decision to not update to a version we rolled back from.
1493 string rollback_version =
1494 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001495 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001496 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001497 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001498 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1499 return true;
1500 }
1501 }
1502
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001503 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001504 LOG(INFO) << "Update is not allowed over current connection.";
1505 return true;
1506 }
1507
1508 // Note: We could technically delete the UpdateFirstSeenAt state when we
1509 // return true. If we do, it'll mean a device has to restart the
1510 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1511 // turned on again. On the other hand, it also increases the chance of update
1512 // starvation if an admin turns AU on/off more frequently. We choose to err on
1513 // the side of preventing starvation at the cost of not applying scattering in
1514 // those cases.
1515 return false;
1516}
1517
1518bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001519 ConnectionType type;
1520 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001521 ConnectionManagerInterface* connection_manager =
1522 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001523 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001524 LOG(INFO) << "We could not determine our connection type. "
1525 << "Defaulting to allow updates.";
1526 return true;
1527 }
1528 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1529 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001530 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001531 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1532 return is_allowed;
1533}
1534
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001535} // namespace chromeos_update_engine