blob: 47f3e37de171eac1f6be58de04ea1d52f36cf4c5 [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 Deymoebf6e122017-03-10 16:12:01 -0800261 string fingerprint_arg;
262 if (!params->os_build_fingerprint().empty()) {
263 fingerprint_arg =
264 "fingerprint=\"" + XmlEncodeWithDefault(params->os_build_fingerprint(), "") + "\" ";
265 }
266
Alex Deymob0d74eb2015-03-30 17:59:17 -0700267 string app_xml = " <app "
268 "appid=\"" + XmlEncodeWithDefault(params->GetAppId(), "") + "\" " +
269 app_cohort_args +
270 app_versions +
271 app_channels +
Alex Deymoebf6e122017-03-10 16:12:01 -0800272 fingerprint_arg +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700273 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
274 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
275 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
276 "delta_okay=\"" + delta_okay_str + "\" "
277 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
278 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
279 install_date_in_days_str +
280 ">\n" +
281 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700282 " </app>\n";
283
284 return app_xml;
285}
286
287// Returns an XML that corresponds to the entire <os> node of the Omaha
288// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700289string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700290 string os_xml =" <os "
291 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
292 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
293 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
294 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700295 return os_xml;
296}
297
298// Returns an XML that corresponds to the entire Omaha request based on the
299// given parameters.
300string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700301 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700302 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700303 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700304 int ping_active_days,
305 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800306 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700307 SystemState* system_state) {
308 string os_xml = GetOsXml(params);
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700309 string app_xml = GetAppXml(event, params, ping_only, include_ping,
310 ping_active_days, ping_roll_call_days,
311 install_date_in_days, system_state);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700312
Alex Vakulenko75039d72014-03-25 12:36:28 -0700313 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700314 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700315
Alex Deymoac41a822015-09-15 20:52:53 -0700316 string updater_version = XmlEncodeWithDefault(
317 base::StringPrintf("%s-%s",
318 constants::kOmahaUpdaterID,
319 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700320 string request_xml =
321 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700322 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700323 "version=\"" + updater_version + "\" "
324 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700325 install_source +
326 "ismachine=\"1\">\n") +
327 os_xml +
328 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700329 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700330
331 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000332}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700333
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700334} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000335
David Zeuthene8ed8632014-07-24 13:38:10 -0400336// Struct used for holding data obtained when parsing the XML.
337struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400338 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
339
340 // Pointer to the expat XML_Parser object.
341 XML_Parser xml_parser;
342
David Zeuthene8ed8632014-07-24 13:38:10 -0400343 // This is the state of the parser as it's processing the XML.
344 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400345 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400346 string current_path;
347
348 // These are the values extracted from the XML.
Alex Deymo8e18f932015-03-27 16:16:59 -0700349 string app_cohort;
350 string app_cohorthint;
351 string app_cohortname;
352 bool app_cohort_set = false;
353 bool app_cohorthint_set = false;
354 bool app_cohortname_set = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400355 string updatecheck_status;
356 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700357 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400358 string daystart_elapsed_days;
359 string daystart_elapsed_seconds;
360 vector<string> url_codebase;
361 string package_name;
362 string package_size;
363 string manifest_version;
364 map<string, string> action_postinstall_attrs;
365};
366
367namespace {
368
369// Callback function invoked by expat.
370void ParserHandlerStart(void* user_data, const XML_Char* element,
371 const XML_Char** attr) {
372 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
373
374 if (data->failed)
375 return;
376
377 data->current_path += string("/") + element;
378
379 map<string, string> attrs;
380 if (attr != nullptr) {
381 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
382 string key = attr[n];
383 string value = attr[n + 1];
384 attrs[key] = value;
385 }
386 }
387
Alex Deymo8e18f932015-03-27 16:16:59 -0700388 if (data->current_path == "/response/app") {
389 if (attrs.find("cohort") != attrs.end()) {
390 data->app_cohort_set = true;
391 data->app_cohort = attrs["cohort"];
392 }
393 if (attrs.find("cohorthint") != attrs.end()) {
394 data->app_cohorthint_set = true;
395 data->app_cohorthint = attrs["cohorthint"];
396 }
397 if (attrs.find("cohortname") != attrs.end()) {
398 data->app_cohortname_set = true;
399 data->app_cohortname = attrs["cohortname"];
400 }
401 } else if (data->current_path == "/response/app/updatecheck") {
David Zeuthene8ed8632014-07-24 13:38:10 -0400402 // There is only supposed to be a single <updatecheck> element.
403 data->updatecheck_status = attrs["status"];
404 data->updatecheck_poll_interval = attrs["PollInterval"];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700405 // Omaha sends arbitrary key-value pairs as extra attributes starting with
406 // an underscore.
407 for (const auto& attr : attrs) {
408 if (!attr.first.empty() && attr.first[0] == '_')
409 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
410 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400411 } else if (data->current_path == "/response/daystart") {
412 // Get the install-date.
413 data->daystart_elapsed_days = attrs["elapsed_days"];
414 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
415 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
416 // Look at all <url> elements.
417 data->url_codebase.push_back(attrs["codebase"]);
418 } else if (data->package_name.empty() && data->current_path ==
419 "/response/app/updatecheck/manifest/packages/package") {
420 // Only look at the first <package>.
421 data->package_name = attrs["name"];
422 data->package_size = attrs["size"];
423 } else if (data->current_path == "/response/app/updatecheck/manifest") {
424 // Get the version.
425 data->manifest_version = attrs[kTagVersion];
426 } else if (data->current_path ==
427 "/response/app/updatecheck/manifest/actions/action") {
428 // We only care about the postinstall action.
429 if (attrs["event"] == "postinstall") {
430 data->action_postinstall_attrs = attrs;
431 }
432 }
433}
434
435// Callback function invoked by expat.
436void ParserHandlerEnd(void* user_data, const XML_Char* element) {
437 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
438 if (data->failed)
439 return;
440
441 const string path_suffix = string("/") + element;
442
Alex Vakulenko0103c362016-01-20 07:56:15 -0800443 if (!base::EndsWith(data->current_path, path_suffix,
444 base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400445 LOG(ERROR) << "Unexpected end element '" << element
446 << "' with current_path='" << data->current_path << "'";
447 data->failed = true;
448 return;
449 }
450 data->current_path.resize(data->current_path.size() - path_suffix.size());
451}
452
David Zeuthenf3e28012014-08-26 18:23:52 -0400453// Callback function invoked by expat.
454//
455// This is called for entity declarations. Since Omaha is guaranteed
456// to never return any XML with entities our course of action is to
457// just stop parsing. This avoids potential resource exhaustion
458// problems AKA the "billion laughs". CVE-2013-0340.
459void ParserHandlerEntityDecl(void *user_data,
460 const XML_Char *entity_name,
461 int is_parameter_entity,
462 const XML_Char *value,
463 int value_length,
464 const XML_Char *base,
465 const XML_Char *system_id,
466 const XML_Char *public_id,
467 const XML_Char *notation_name) {
468 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
469
470 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
471 data->failed = true;
472 data->entity_decl = true;
473 XML_StopParser(data->xml_parser, false);
474}
475
David Zeuthene8ed8632014-07-24 13:38:10 -0400476} // namespace
477
Alex Deymob0d74eb2015-03-30 17:59:17 -0700478bool XmlEncode(const string& input, string* output) {
479 if (std::find_if(input.begin(), input.end(),
480 [](const char c){return c & 0x80;}) != input.end()) {
481 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
482 utils::HexDumpString(input);
483 return false;
484 }
Alex Deymocc457852015-06-18 18:35:50 -0700485 output->clear();
486 // We need at least input.size() space in the output, but the code below will
487 // handle it if we need more.
488 output->reserve(input.size());
489 for (char c : input) {
490 switch (c) {
491 case '\"':
492 output->append("&quot;");
493 break;
494 case '\'':
495 output->append("&apos;");
496 break;
497 case '&':
498 output->append("&amp;");
499 break;
500 case '<':
501 output->append("&lt;");
502 break;
503 case '>':
504 output->append("&gt;");
505 break;
506 default:
507 output->push_back(c);
508 }
509 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700510 return true;
511}
512
513string XmlEncodeWithDefault(const string& input, const string& default_value) {
514 string output;
515 if (XmlEncode(input, &output))
516 return output;
517 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000518}
519
Alex Deymoc1c17b42015-11-23 03:53:15 -0300520OmahaRequestAction::OmahaRequestAction(
521 SystemState* system_state,
522 OmahaEvent* event,
523 std::unique_ptr<HttpFetcher> http_fetcher,
524 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800525 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700526 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300527 http_fetcher_(std::move(http_fetcher)),
Thieu Le116fda32011-04-19 11:01:54 -0700528 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700529 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700530 ping_roll_call_days_(0) {
531 params_ = system_state->request_params();
532}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000533
Darin Petkov6a5b3222010-07-13 14:55:28 -0700534OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000535
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700536// Calculates the value to use for the ping days parameter.
537int OmahaRequestAction::CalculatePingDays(const string& key) {
538 int days = kNeverPinged;
539 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800540 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700541 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
542 if (days < 0) {
543 // If |days| is negative, then the system clock must have jumped
544 // back in time since the ping was sent. Mark the value so that
545 // it doesn't get sent to the server but we still update the
546 // last ping daystart preference. This way the next ping time
547 // will be correct, hopefully.
548 days = kPingTimeJump;
549 LOG(WARNING) <<
550 "System clock jumped back in time. Resetting ping daystarts.";
551 }
552 }
553 return days;
554}
555
556void OmahaRequestAction::InitPingDays() {
557 // We send pings only along with update checks, not with events.
558 if (IsEvent()) {
559 return;
560 }
561 // TODO(petkov): Figure a way to distinguish active use pings
562 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700563 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700564 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
565 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
566}
567
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700568bool OmahaRequestAction::ShouldPing() const {
569 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
570 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
571 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
572 if (powerwash_count > 0) {
573 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
574 << "powerwash_count is " << powerwash_count;
575 return false;
576 }
Amin Hassani1677e812017-06-21 13:36:36 -0700577 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
578 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
579 << "the first_active_omaha_ping_sent is true";
580 return false;
581 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700582 return true;
583 }
584 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
585}
586
David Zeuthen639aa362014-02-03 16:23:44 -0800587// static
588int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
589 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700590 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800591 return -1;
592
593 // If we have the value stored on disk, just return it.
594 int64_t stored_value;
595 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
596 // Convert and sanity-check.
597 int install_date_days = static_cast<int>(stored_value);
598 if (install_date_days >= 0)
599 return install_date_days;
600 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
601 << install_date_days << " looks suspicious.";
602 prefs->Delete(kPrefsInstallDateDays);
603 }
604
605 // Otherwise, if OOBE is not complete then do nothing and wait for
606 // ParseResponse() to call ParseInstallDate() and then
607 // PersistInstallDate() to set the kPrefsInstallDateDays state
608 // variable. Once that is done, we'll then report back in future
609 // Omaha requests. This works exactly because OOBE triggers an
610 // update check.
611 //
612 // However, if OOBE is complete and the kPrefsInstallDateDays state
613 // variable is not set, there are two possibilities
614 //
615 // 1. The update check in OOBE failed so we never got a response
616 // from Omaha (no network etc.); or
617 //
618 // 2. OOBE was done on an older version that didn't write to the
619 // kPrefsInstallDateDays state variable.
620 //
621 // In both cases, we approximate the install date by simply
622 // inspecting the timestamp of when OOBE happened.
623
624 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700625 if (!system_state->hardware()->IsOOBEEnabled() ||
626 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800627 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700628 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800629 return -1;
630 }
631
632 int num_days;
633 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
634 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
635 << "as its value '" << utils::ToString(time_of_oobe)
636 << "' looks suspicious.";
637 return -1;
638 }
639
640 // Persist this to disk, for future use.
641 if (!OmahaRequestAction::PersistInstallDate(system_state,
642 num_days,
643 kProvisionedFromOOBEMarker))
644 return -1;
645
646 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
647 << num_days << " days";
648
649 return num_days;
650}
651
Darin Petkov6a5b3222010-07-13 14:55:28 -0700652void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000653 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700654 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700655 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700656 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700657 return;
658 }
David Zeuthen639aa362014-02-03 16:23:44 -0800659
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700660 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700661 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700662 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700663 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700664 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800665 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800666 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700667 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700668
Alex Deymo14ad88e2016-06-29 12:30:14 -0700669 // Set X-GoogleUpdate headers.
670 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
671 params_->interactive() ? "fg" : "bg");
672 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
673 http_fetcher_->SetHeader(
674 kXGoogleUpdateUpdater,
675 base::StringPrintf(
676 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
677
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800678 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
679 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700680 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700681 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700682 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000683}
684
Darin Petkov6a5b3222010-07-13 14:55:28 -0700685void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000686 http_fetcher_->TerminateTransfer();
687}
688
689// We just store the response in the buffer. Once we've received all bytes,
690// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700691void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800692 const void* bytes,
693 size_t length) {
694 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
695 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000696}
697
698namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000699
700// Parses a 64 bit base-10 int from a string and returns it. Returns 0
701// on error. If the string contains "0", that's indistinguishable from
702// error.
703off_t ParseInt(const string& str) {
704 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700705 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000706 if (rc < 1) {
707 // failure
708 return 0;
709 }
710 return ret;
711}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700712
David Zeuthene8ed8632014-07-24 13:38:10 -0400713// Parses |str| and returns |true| if, and only if, its value is "true".
714bool ParseBool(const string& str) {
715 return str == "true";
716}
717
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700718// Update the last ping day preferences based on the server daystart
719// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400720bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700721 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400722 TEST_AND_RETURN_FALSE(
723 base::StringToInt64(parser_data->daystart_elapsed_seconds,
724 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700725 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
726
727 // Remember the local time that matches the server's last midnight
728 // time.
729 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
730 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
731 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
732 return true;
733}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700734} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000735
David Zeuthene8ed8632014-07-24 13:38:10 -0400736bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700737 OmahaResponse* output_object,
738 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400739 if (parser_data->updatecheck_status.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700740 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700741 return false;
742 }
743
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800744 // chromium-os:37289: The PollInterval is not supported by Omaha server
745 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700746 // slow down the request rate from the server-side. Note that the PollInterval
747 // is not persisted, so it has to be sent by the server on every response to
748 // guarantee that the scheduler uses this value (otherwise, if the device got
749 // rebooted after the last server-indicated value, it'll revert to the default
750 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
751 // based on the assumption that we perform an update check every hour so that
752 // the max value of 8 will roughly be equivalent to one work day. If we decide
753 // to use PollInterval permanently, we should update the
754 // max_update_checks_allowed to take PollInterval into account. Note: The
755 // parsing for PollInterval happens even before parsing of the status because
756 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400757 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700758 &output_object->poll_interval);
759
David Zeuthen639aa362014-02-03 16:23:44 -0800760 // Check for the "elapsed_days" attribute in the "daystart"
761 // element. This is the number of days since Jan 1 2007, 0:00
762 // PST. If we don't have a persisted value of the Omaha InstallDate,
763 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400764 if (ParseInstallDate(parser_data, output_object) &&
765 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800766 // Since output_object->install_date_days is never negative, the
767 // elapsed_days -> install-date calculation is reduced to simply
768 // rounding down to the nearest number divisible by 7.
769 int remainder = output_object->install_date_days % 7;
770 int install_date_days_rounded =
771 output_object->install_date_days - remainder;
772 if (PersistInstallDate(system_state_,
773 install_date_days_rounded,
774 kProvisionedFromOmahaResponse)) {
775 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
776 << install_date_days_rounded << " days";
777 }
778 }
779
Alex Deymo00d79ac2015-06-29 15:41:49 -0700780 // We persist the cohorts sent by omaha even if the status is "noupdate".
781 if (parser_data->app_cohort_set)
782 PersistCohortData(kPrefsOmahaCohort, parser_data->app_cohort);
783 if (parser_data->app_cohorthint_set)
784 PersistCohortData(kPrefsOmahaCohortHint, parser_data->app_cohorthint);
785 if (parser_data->app_cohortname_set)
786 PersistCohortData(kPrefsOmahaCohortName, parser_data->app_cohortname);
787
Alex Deymob3fa53b2016-04-18 19:57:58 -0700788 // Parse the updatecheck attributes.
789 PersistEolStatus(parser_data->updatecheck_attrs);
790
David Zeuthene8ed8632014-07-24 13:38:10 -0400791 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700792 return false;
793
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800794 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
795 // appends the package name to the URLs populated in this method.
David Zeuthene8ed8632014-07-24 13:38:10 -0400796 if (!ParseUrls(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700797 return false;
798
David Zeuthene8ed8632014-07-24 13:38:10 -0400799 if (!ParsePackage(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700800 return false;
801
David Zeuthene8ed8632014-07-24 13:38:10 -0400802 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700803 return false;
804
805 return true;
806}
807
David Zeuthene8ed8632014-07-24 13:38:10 -0400808bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700809 OmahaResponse* output_object,
810 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400811 const string& status = parser_data->updatecheck_status;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700812 if (status == "noupdate") {
813 LOG(INFO) << "No update.";
814 output_object->update_exists = false;
815 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700816 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700817 return false;
818 }
819
820 if (status != "ok") {
821 LOG(ERROR) << "Unknown Omaha response status: " << status;
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
826 return true;
827}
828
David Zeuthene8ed8632014-07-24 13:38:10 -0400829bool OmahaRequestAction::ParseUrls(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700830 OmahaResponse* output_object,
831 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400832 if (parser_data->url_codebase.empty()) {
833 LOG(ERROR) << "No Omaha Response URLs";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700834 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700835 return false;
836 }
837
David Zeuthene8ed8632014-07-24 13:38:10 -0400838 LOG(INFO) << "Found " << parser_data->url_codebase.size() << " url(s)";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800839 output_object->payload_urls.clear();
David Zeuthene8ed8632014-07-24 13:38:10 -0400840 for (const auto& codebase : parser_data->url_codebase) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800841 if (codebase.empty()) {
842 LOG(ERROR) << "Omaha Response URL has empty codebase";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700843 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800844 return false;
845 }
846 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700847 }
848
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700849 return true;
850}
851
David Zeuthene8ed8632014-07-24 13:38:10 -0400852bool OmahaRequestAction::ParsePackage(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700853 OmahaResponse* output_object,
854 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400855 if (parser_data->package_name.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700856 LOG(ERROR) << "Omaha Response has empty package name";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700857 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700858 return false;
859 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800860
861 // Append the package name to each URL in our list so that we don't
862 // propagate the urlBase vs packageName distinctions beyond this point.
863 // From now on, we only need to use payload_urls.
David Zeuthene8ed8632014-07-24 13:38:10 -0400864 for (auto& payload_url : output_object->payload_urls)
865 payload_url += parser_data->package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700866
867 // Parse the payload size.
David Zeuthene8ed8632014-07-24 13:38:10 -0400868 off_t size = ParseInt(parser_data->package_size);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700869 if (size <= 0) {
870 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700871 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700872 return false;
873 }
874 output_object->size = size;
875
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800876 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700877
878 return true;
879}
880
David Zeuthene8ed8632014-07-24 13:38:10 -0400881bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700882 OmahaResponse* output_object,
883 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400884 output_object->version = parser_data->manifest_version;
Chris Sosa3b748432013-06-20 16:42:59 -0700885 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700886 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700887 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700888 return false;
889 }
890
891 LOG(INFO) << "Received omaha response to update to version "
892 << output_object->version;
893
David Zeuthene8ed8632014-07-24 13:38:10 -0400894 map<string, string> attrs = parser_data->action_postinstall_attrs;
895 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700896 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700897 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700898 return false;
899 }
900
David Zeuthene8ed8632014-07-24 13:38:10 -0400901 output_object->hash = attrs[kTagSha256];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700902 if (output_object->hash.empty()) {
903 LOG(ERROR) << "Omaha Response has empty sha256 value";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700904 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700905 return false;
906 }
907
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800908 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -0400909 output_object->more_info_url = attrs[kTagMoreInfo];
910 output_object->metadata_size = ParseInt(attrs[kTagMetadataSize]);
911 output_object->metadata_signature = attrs[kTagMetadataSignatureRsa];
912 output_object->prompt = ParseBool(attrs[kTagPrompt]);
913 output_object->deadline = attrs[kTagDeadline];
914 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700915 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -0400916 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700917 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -0400918 ParseBool(attrs[kTagDisableP2PForSharing]);
919 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800920
David Zeuthene8ed8632014-07-24 13:38:10 -0400921 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800922 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800923 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700924
David Zeuthene8ed8632014-07-24 13:38:10 -0400925 output_object->is_delta_payload = ParseBool(attrs[kTagIsDeltaPayload]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800926
927 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -0400928 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800929
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700930 return true;
931}
932
David Zeuthene8ed8632014-07-24 13:38:10 -0400933// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000934// and fill in the appropriate fields of the output object. Also, notifies
935// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700936void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
937 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000938 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800939 string current_response(response_buffer_.begin(), response_buffer_.end());
940 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700941
Gilad Arnold74b5f552014-10-07 08:17:16 -0700942 PayloadStateInterface* const payload_state = system_state_->payload_state();
943
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700944 // Events are best effort transactions -- assume they always succeed.
945 if (IsEvent()) {
946 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700947 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700948 return;
949 }
950
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700951 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700952 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700953 int code = GetHTTPResponseCode();
954 // Makes sure we send sane error values.
955 if (code < 0 || code >= 1000) {
956 code = 999;
957 }
David Zeuthena99981f2013-04-29 13:42:47 -0700958 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700959 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000960 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700961 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000962
David Zeuthene8ed8632014-07-24 13:38:10 -0400963 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400964 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400965 XML_SetUserData(parser, &parser_data);
966 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400967 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800968 XML_Status res = XML_Parse(
969 parser,
970 reinterpret_cast<const char*>(response_buffer_.data()),
971 response_buffer_.size(),
972 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400973 XML_ParserFree(parser);
974
975 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700976 LOG(ERROR) << "Omaha response not valid XML: "
977 << XML_ErrorString(XML_GetErrorCode(parser))
978 << " at line " << XML_GetCurrentLineNumber(parser)
979 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400980 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
981 if (response_buffer_.empty()) {
982 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
983 } else if (parser_data.entity_decl) {
984 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
985 }
986 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000987 return;
988 }
989
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700990 // Update the last ping day preferences based on the server daystart response
991 // even if we didn't send a ping. Omaha always includes the daystart in the
992 // response, but log the error if it didn't.
993 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
994 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700995
Amin Hassani1677e812017-06-21 13:36:36 -0700996 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
997 // we have got a response from omaha and if its value has never been set to
998 // true before. Failure of this function should be ignored. There should be no
999 // need to check if a=-1 has been sent because older devices have already sent
1000 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
1001 // future checks.
1002 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
1003 system_state_->hardware()->SetFirstActiveOmahaPingSent();
1004 }
1005
Thieu Le116fda32011-04-19 11:01:54 -07001006 if (!HasOutputPipe()) {
1007 // Just set success to whether or not the http transfer succeeded,
1008 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001009 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001010 return;
1011 }
1012
Darin Petkov6a5b3222010-07-13 14:55:28 -07001013 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001014 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001015 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001016 output_object.update_exists = true;
1017 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001018
Weidong Guo4b0d6032017-04-17 10:08:38 -07001019 ErrorCode error = ErrorCode::kSuccess;
1020 if (ShouldIgnoreUpdate(&error, output_object)) {
1021 // No need to change output_object.update_exists here, since the value
1022 // has been output to the pipe.
1023 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001024 return;
1025 }
1026
David Zeuthen8f191b22013-08-06 12:27:50 -07001027 // If Omaha says to disable p2p, respect that
1028 if (output_object.disable_p2p_for_downloading) {
1029 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1030 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001031 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001032 }
1033 if (output_object.disable_p2p_for_sharing) {
1034 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1035 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001036 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001037 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001038
1039 // Update the payload state with the current response. The payload state
1040 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001041 // from what's stored already. We are updating the payload state as late
1042 // as possible in this method so that if a new release gets pushed and then
1043 // got pulled back due to some issues, we don't want to clear our internal
1044 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001045 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001046
David Zeuthen8f191b22013-08-06 12:27:50 -07001047 // It could be we've already exceeded the deadline for when p2p is
1048 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001049 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001050 payload_state->P2PNewAttempt();
1051 if (!payload_state->P2PAttemptAllowed()) {
1052 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1053 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001054 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001055 }
1056 }
1057
1058 // From here on, we'll complete stuff in CompleteProcessing() so
1059 // disable |completer| since we'll create a new one in that
1060 // function.
1061 completer.set_should_complete(false);
1062
1063 // If we're allowed to use p2p for downloading we do not pay
1064 // attention to wall-clock-based waiting if the URL is indeed
1065 // available via p2p. Therefore, check if the file is available via
1066 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001067 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001068 LookupPayloadViaP2P(output_object);
1069 } else {
1070 CompleteProcessing();
1071 }
1072}
1073
1074void OmahaRequestAction::CompleteProcessing() {
1075 ScopedActionCompleter completer(processor_, this);
1076 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1077 PayloadStateInterface* payload_state = system_state_->payload_state();
1078
Alex Deymo46a9aae2016-05-04 20:20:11 -07001079 if (system_state_->hardware()->IsOOBEEnabled() &&
1080 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
Kevin Cernekeec5081a82016-04-08 12:29:52 -07001081 output_object.deadline.empty() &&
1082 params_->app_version() != "ForcedUpdate") {
Kevin Cernekee2494e282016-03-29 18:03:53 -07001083 output_object.update_exists = false;
1084 LOG(INFO) << "Ignoring non-critical Omaha updates until OOBE is done.";
1085 completer.set_code(ErrorCode::kNonCriticalUpdateInOOBE);
1086 return;
1087 }
1088
David Zeuthen8f191b22013-08-06 12:27:50 -07001089 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001090 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001091 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001092 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001093 return;
1094 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001095
Chris Sosa20f005c2013-09-05 13:53:08 -07001096 if (payload_state->ShouldBackoffDownload()) {
1097 output_object.update_exists = false;
1098 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1099 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001100 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001101 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001102 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001103 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001104}
1105
1106void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1107 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1108 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001109 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001110 } else {
1111 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1112 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001113 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001114 }
1115 CompleteProcessing();
1116}
1117
1118void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001119 // If the device is in the middle of an update, the state variables
1120 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1121 // tracks the offset and length of the operation currently in
1122 // progress. The offset is based from the end of the manifest which
1123 // is kPrefsManifestMetadataSize bytes long.
1124 //
1125 // To make forward progress and avoid deadlocks, we need to find a
1126 // peer that has at least the entire operation we're currently
1127 // working on. Otherwise we may end up in a situation where two
1128 // devices bounce back and forth downloading from each other,
1129 // neither making any forward progress until one of them decides to
1130 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1131 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001132 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001133 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001134 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001135 int64_t next_data_offset = 0;
1136 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001137 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001138 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1139 &manifest_metadata_size) &&
1140 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001141 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1142 &manifest_signature_size) &&
1143 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001144 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001145 &next_data_offset) &&
1146 next_data_offset != -1 &&
1147 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1148 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001149 minimum_size = manifest_metadata_size + manifest_signature_size +
1150 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001151 }
1152
1153 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001154 if (system_state_->p2p_manager()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001155 LOG(INFO) << "Checking if payload is available via p2p, file_id="
1156 << file_id << " minimum_size=" << minimum_size;
1157 system_state_->p2p_manager()->LookupUrlForFile(
1158 file_id,
1159 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001160 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001161 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1162 base::Unretained(this)));
1163 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001164}
1165
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001166bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001167 if (params_->interactive()) {
1168 LOG(INFO) << "Not deferring download because update is interactive.";
1169 return false;
1170 }
1171
David Zeuthen8f191b22013-08-06 12:27:50 -07001172 // If we're using p2p to download _and_ we have a p2p URL, we never
1173 // defer the download. This is because the download will always
1174 // happen from a peer on the LAN and we've been waiting in line for
1175 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001176 const PayloadStateInterface* payload_state = system_state_->payload_state();
1177 if (payload_state->GetUsingP2PForDownloading() &&
1178 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001179 LOG(INFO) << "Download not deferred because download "
1180 << "will happen from a local peer (via p2p).";
1181 return false;
1182 }
1183
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001184 // We should defer the downloads only if we've first satisfied the
1185 // wall-clock-based-waiting period and then the update-check-based waiting
1186 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001187 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001188 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1189 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001190 return false;
1191 }
1192
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001193 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001194 case kWallClockWaitNotSatisfied:
1195 // We haven't even satisfied the first condition, passing the
1196 // wall-clock-based waiting period, so we should defer the downloads
1197 // until that happens.
1198 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1199 return true;
1200
1201 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1202 LOG(INFO) << "wall-clock-based-wait satisfied and "
1203 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001204 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001205
1206 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1207 // Wall-clock-based waiting period is satisfied, and it's determined
1208 // that we do not need the update-check-based wait. so no need to
1209 // defer downloads.
1210 LOG(INFO) << "wall-clock-based-wait satisfied and "
1211 << "update-check-based-wait is not required.";
1212 return false;
1213
1214 default:
1215 // Returning false for this default case so we err on the
1216 // side of downloading updates than deferring in case of any bugs.
1217 NOTREACHED();
1218 return false;
1219 }
1220}
1221
1222OmahaRequestAction::WallClockWaitResult
1223OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001224 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001225 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001226 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001227
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001228 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1229 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1230 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001231 // Note: This timestamp could be that of ANY update we saw in the past
1232 // (not necessarily this particular update we're considering to apply)
1233 // but never got to apply because of some reason (e.g. stop AU policy,
1234 // updates being pulled out from Omaha, changes in target version prefix,
1235 // new update being rolled out, etc.). But for the purposes of scattering
1236 // it doesn't matter which update the timestamp corresponds to. i.e.
1237 // the clock starts ticking the first time we see an update and we're
1238 // ready to apply when the random wait period is satisfied relative to
1239 // that first seen timestamp.
1240 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1241 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1242 << utils::ToString(update_first_seen_at);
1243 } else {
1244 // This seems like an unexpected error where the persisted value exists
1245 // but it's not readable for some reason. Just skip scattering in this
1246 // case to be safe.
1247 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1248 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1249 }
1250 } else {
Sen Jiang7c1171e2016-06-23 11:35:40 -07001251 update_first_seen_at = system_state_->clock()->GetWallclockTime();
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001252 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001253 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1254 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001255 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1256 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001257 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001258 // This seems like an unexpected error where the value cannot be
1259 // persisted for some reason. Just skip scattering in this
1260 // case to be safe.
1261 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1262 << utils::ToString(update_first_seen_at)
1263 << " cannot be persisted";
1264 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1265 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001266 }
1267
Sen Jiang7c1171e2016-06-23 11:35:40 -07001268 TimeDelta elapsed_time =
1269 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1270 TimeDelta max_scatter_period =
1271 TimeDelta::FromDays(output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001272
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001273 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001274 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001275 << ", Time Elapsed = "
1276 << utils::FormatSecs(elapsed_time.InSeconds())
1277 << ", MaxDaysToScatter = "
1278 << max_scatter_period.InDays();
1279
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001280 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001281 // The deadline is set for all rules which serve a delta update from a
1282 // previous FSI, which means this update will be applied mostly in OOBE
1283 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1284 // quickly.
1285 LOG(INFO) << "Not scattering as deadline flag is set";
1286 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1287 }
1288
1289 if (max_scatter_period.InDays() == 0) {
1290 // This means the Omaha rule creator decides that this rule
1291 // should not be scattered irrespective of the policy.
1292 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1293 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1294 }
1295
1296 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001297 // This means we've waited more than the upperbound wait in the rule
1298 // from the time we first saw a valid update available to us.
1299 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001300 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1301 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1302 }
1303
1304 // This means we are required to participate in scattering.
1305 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001306 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001307 if (remaining_wait_time.InSeconds() <= 0) {
1308 // Yes, it's our turn now.
1309 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1310
1311 // But we can't download until the update-check-count-based wait is also
1312 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001313 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001314 kWallClockWaitDoneButUpdateCheckWaitRequired :
1315 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1316 }
1317
1318 // Not our turn yet, so we have to wait until our turn to
1319 // help scatter the downloads across all clients of the enterprise.
1320 LOG(INFO) << "Update deferred for another "
1321 << utils::FormatSecs(remaining_wait_time.InSeconds())
1322 << " per policy.";
1323 return kWallClockWaitNotSatisfied;
1324}
1325
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001326bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001327 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001328
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001329 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1330 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1331 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001332 // We are unable to read the update check count from file for some reason.
1333 // So let's proceed anyway so as to not stall the update.
1334 LOG(ERROR) << "Unable to read update check count. "
1335 << "Skipping update-check-count-based-wait.";
1336 return true;
1337 }
1338 } else {
1339 // This file does not exist. This means we haven't started our update
1340 // check count down yet, so this is the right time to start the count down.
1341 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001342 params_->min_update_checks_needed(),
1343 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001344
1345 LOG(INFO) << "Randomly picked update check count value = "
1346 << update_check_count_value;
1347
1348 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001349 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1350 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001351 // We weren't able to write the update check count file for some reason.
1352 // So let's proceed anyway so as to not stall the update.
1353 LOG(ERROR) << "Unable to write update check count. "
1354 << "Skipping update-check-count-based-wait.";
1355 return true;
1356 }
1357 }
1358
1359 if (update_check_count_value == 0) {
1360 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1361 return true;
1362 }
1363
1364 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001365 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001366 // We err on the side of skipping scattering logic instead of stalling
1367 // a machine from receiving any updates in case of any unexpected state.
1368 LOG(ERROR) << "Invalid value for update check count detected. "
1369 << "Skipping update-check-count-based-wait.";
1370 return true;
1371 }
1372
1373 // Legal value, we need to wait for more update checks to happen
1374 // until this becomes 0.
1375 LOG(INFO) << "Deferring Omaha updates for another "
1376 << update_check_count_value
1377 << " update checks per policy";
1378 return false;
1379}
1380
David Zeuthen639aa362014-02-03 16:23:44 -08001381// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001382bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001383 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001384 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001385 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001386 &elapsed_days))
1387 return false;
1388
1389 if (elapsed_days < 0)
1390 return false;
1391
1392 output_object->install_date_days = elapsed_days;
1393 return true;
1394}
1395
1396// static
1397bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1398 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001399 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001400 return false;
1401
1402 return prefs->Exists(kPrefsInstallDateDays);
1403}
1404
1405// static
1406bool OmahaRequestAction::PersistInstallDate(
1407 SystemState *system_state,
1408 int install_date_days,
1409 InstallDateProvisioningSource source) {
1410 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1411
1412 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001413 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001414 return false;
1415
1416 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1417 return false;
1418
Alex Deymoaf9a8632015-09-23 18:51:48 -07001419 string metric_name = metrics::kMetricInstallDateProvisioningSource;
David Zeuthen33bae492014-02-25 16:16:18 -08001420 system_state->metrics_lib()->SendEnumToUMA(
1421 metric_name,
1422 static_cast<int>(source), // Sample.
1423 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001424
1425 return true;
1426}
1427
Alex Deymo8e18f932015-03-27 16:16:59 -07001428bool OmahaRequestAction::PersistCohortData(
1429 const string& prefs_key,
1430 const string& new_value) {
1431 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1432 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1433 return system_state_->prefs()->Delete(prefs_key);
1434 } else if (!new_value.empty()) {
1435 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1436 return system_state_->prefs()->SetString(prefs_key, new_value);
1437 }
1438 return true;
1439}
1440
Alex Deymob3fa53b2016-04-18 19:57:58 -07001441bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
1442 auto eol_attr = attrs.find(kEolAttr);
1443 if (eol_attr != attrs.end()) {
1444 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1445 eol_attr->second);
1446 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1447 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1448 }
1449 return true;
1450}
1451
David Zeuthen33bae492014-02-25 16:16:18 -08001452void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1453 // We only want to report this on "update check".
1454 if (ping_only_ || event_ != nullptr)
1455 return;
1456
1457 metrics::CheckResult result = metrics::CheckResult::kUnset;
1458 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1459 metrics::DownloadErrorCode download_error_code =
1460 metrics::DownloadErrorCode::kUnset;
1461
1462 // Regular update attempt.
1463 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001464 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001465 // OK, we parsed the response successfully but that does
1466 // necessarily mean that an update is available.
1467 if (HasOutputPipe()) {
1468 const OmahaResponse& response = GetOutputObject();
1469 if (response.update_exists) {
1470 result = metrics::CheckResult::kUpdateAvailable;
1471 reaction = metrics::CheckReaction::kUpdating;
1472 } else {
1473 result = metrics::CheckResult::kNoUpdateAvailable;
1474 }
1475 } else {
1476 result = metrics::CheckResult::kNoUpdateAvailable;
1477 }
1478 break;
1479
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001480 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
Weidong Guo4b0d6032017-04-17 10:08:38 -07001481 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
David Zeuthen33bae492014-02-25 16:16:18 -08001482 result = metrics::CheckResult::kUpdateAvailable;
1483 reaction = metrics::CheckReaction::kIgnored;
1484 break;
1485
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001486 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001487 result = metrics::CheckResult::kUpdateAvailable;
1488 reaction = metrics::CheckReaction::kDeferring;
1489 break;
1490
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001491 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001492 result = metrics::CheckResult::kUpdateAvailable;
1493 reaction = metrics::CheckReaction::kBackingOff;
1494 break;
1495
1496 default:
1497 // We report two flavors of errors, "Download errors" and "Parsing
1498 // error". Try to convert to the former and if that doesn't work
1499 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001500 metrics::DownloadErrorCode tmp_error =
1501 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001502 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1503 result = metrics::CheckResult::kDownloadError;
1504 download_error_code = tmp_error;
1505 } else {
1506 result = metrics::CheckResult::kParsingError;
1507 }
1508 break;
1509 }
1510
1511 metrics::ReportUpdateCheckMetrics(system_state_,
1512 result, reaction, download_error_code);
1513}
1514
Chris Sosa77f79e82014-06-02 18:16:24 -07001515bool OmahaRequestAction::ShouldIgnoreUpdate(
Weidong Guo4b0d6032017-04-17 10:08:38 -07001516 ErrorCode* error, const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001517 // Note: policy decision to not update to a version we rolled back from.
1518 string rollback_version =
1519 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001520 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001521 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001522 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001523 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo4b0d6032017-04-17 10:08:38 -07001524 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001525 return true;
1526 }
1527 }
1528
Weidong Guo4b0d6032017-04-17 10:08:38 -07001529 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001530 LOG(INFO) << "Update is not allowed over current connection.";
1531 return true;
1532 }
1533
1534 // Note: We could technically delete the UpdateFirstSeenAt state when we
1535 // return true. If we do, it'll mean a device has to restart the
1536 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1537 // turned on again. On the other hand, it also increases the chance of update
1538 // starvation if an admin turns AU on/off more frequently. We choose to err on
1539 // the side of preventing starvation at the cost of not applying scattering in
1540 // those cases.
1541 return false;
1542}
1543
Weidong Guo4b0d6032017-04-17 10:08:38 -07001544bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1545 const OmahaResponse& response) const {
1546 PrefsInterface* prefs = system_state_->prefs();
1547
1548 if (!prefs) {
1549 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1550 "not available.";
1551 return false;
1552 }
1553
1554 bool is_allowed;
1555
1556 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1557 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1558 is_allowed) {
1559 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1560 "set to true.";
1561 return true;
1562 }
1563
1564 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1565 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1566 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1567 "set to false or does not exist while target does not exist.";
1568 return false;
1569 }
1570
1571 std::string target_version;
1572 int64_t target_size;
1573
1574 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1575 &target_version) ||
1576 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize,
1577 &target_size)) {
1578 LOG(INFO) << "Disabling updates over cellular as the target version or "
1579 "size is not accessible.";
1580 return false;
1581 }
1582
1583 if (target_version == response.version && target_size == response.size) {
1584 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1585 "omaha response.";
1586 return true;
1587 } else {
1588 LOG(INFO) << "Disabling updates over cellular as the target does not"
1589 "match the omaha response.";
1590 return false;
1591 }
1592}
1593
1594bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1595 ErrorCode* error,
1596 const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001597 ConnectionType type;
1598 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001599 ConnectionManagerInterface* connection_manager =
1600 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001601 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001602 LOG(INFO) << "We could not determine our connection type. "
1603 << "Defaulting to allow updates.";
1604 return true;
1605 }
Weidong Guo4b0d6032017-04-17 10:08:38 -07001606
Chris Sosa77f79e82014-06-02 18:16:24 -07001607 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo4b0d6032017-04-17 10:08:38 -07001608 bool is_device_policy_set = connection_manager->
1609 IsAllowedConnectionTypesForUpdateSet();
1610 // Treats tethered connection as if it is cellular connection.
1611 bool is_over_cellular = type == ConnectionType::kCellular ||
1612 tethering == ConnectionTethering::kConfirmed;
1613
1614 if (!is_over_cellular) {
1615 // There's no need to further check user preferences as we are not over
1616 // cellular connection.
1617 if (!is_allowed)
1618 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1619 } else if (is_device_policy_set) {
1620 // There's no need to further check user preferences as the device policy
1621 // is set regarding updates over cellular.
1622 if (!is_allowed)
1623 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1624 } else if (!IsUpdateAllowedOverCellularByPrefs(response)) {
1625 // The user prefereces does not allow updates over cellular.
1626 is_allowed = false;
1627 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1628 }
1629
Chris Sosa77f79e82014-06-02 18:16:24 -07001630 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001631 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001632 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1633 return is_allowed;
1634}
1635
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001636} // namespace chromeos_update_engine