blob: a8b8a94b95f8243dde16e1170c76e42316719c28 [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>
Sen Jiang8cd42342018-01-31 12:06:59 -080024#include <utility>
David Zeuthene8ed8632014-07-24 13:38:10 -040025#include <vector>
rspangler@google.com49fdf182009-10-10 00:57:34 +000026
David Zeuthen8f191b22013-08-06 12:27:50 -070027#include <base/bind.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070028#include <base/logging.h>
29#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070030#include <base/strings/string_number_conversions.h>
Sen Jiang0affc2c2017-02-10 15:55:05 -080031#include <base/strings/string_split.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070032#include <base/strings/string_util.h>
33#include <base/strings/stringprintf.h>
34#include <base/time/time.h>
Sen Jiang684c9cd2017-10-17 16:26:45 -070035#include <brillo/key_value_store.h>
David Zeuthene8ed8632014-07-24 13:38:10 -040036#include <expat.h>
Alex Deymoa2591792015-11-17 00:39:40 -030037#include <metrics/metrics_library.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000038
Alex Deymo39910dc2015-11-09 17:04:30 -080039#include "update_engine/common/action_pipe.h"
40#include "update_engine/common/constants.h"
41#include "update_engine/common/hardware_interface.h"
42#include "update_engine/common/hash_calculator.h"
43#include "update_engine/common/platform_constants.h"
44#include "update_engine/common/prefs_interface.h"
45#include "update_engine/common/utils.h"
Sen Jiang255e22b2016-05-20 16:15:29 -070046#include "update_engine/connection_manager_interface.h"
Tianjie Xu282aa1f2017-09-05 13:42:45 -070047#include "update_engine/metrics_reporter_interface.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080048#include "update_engine/metrics_utils.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070049#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070050#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080051#include "update_engine/payload_state_interface.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000052
Darin Petkov1cbd78f2010-07-29 12:38:34 -070053using base::Time;
54using base::TimeDelta;
David Zeuthene8ed8632014-07-24 13:38:10 -040055using std::map;
rspangler@google.com49fdf182009-10-10 00:57:34 +000056using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040057using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000058
59namespace chromeos_update_engine {
60
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080061// List of custom pair tags that we interpret in the Omaha Response:
62static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080063static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070064static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080065// Deprecated: "IsDelta"
66static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080067static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
68static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
69// Deprecated: "ManifestSignatureRsa"
70// Deprecated: "ManifestSize"
71static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
72static const char* kTagMetadataSize = "MetadataSize";
73static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070074// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080075static const char* kTagPrompt = "Prompt";
David Zeuthen8f191b22013-08-06 12:27:50 -070076static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
77static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
David Zeuthene7f89172013-10-31 10:21:04 -070078static const char* kTagPublicKeyRsa = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080079
Alex Deymoac41a822015-09-15 20:52:53 -070080static const char* kOmahaUpdaterVersion = "0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +000081
Alex Deymo14ad88e2016-06-29 12:30:14 -070082// X-GoogleUpdate headers.
83static const char* kXGoogleUpdateInteractivity = "X-GoogleUpdate-Interactivity";
84static const char* kXGoogleUpdateAppId = "X-GoogleUpdate-AppId";
85static const char* kXGoogleUpdateUpdater = "X-GoogleUpdate-Updater";
86
Alex Deymob3fa53b2016-04-18 19:57:58 -070087// updatecheck attributes (without the underscore prefix).
88static const char* kEolAttr = "eol";
89
Alex Deymoac41a822015-09-15 20:52:53 -070090namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +000091
Darin Petkov1cbd78f2010-07-29 12:38:34 -070092// Returns an XML ping element attribute assignment with attribute
93// |name| and value |ping_days| if |ping_days| has a value that needs
94// to be sent, or an empty string otherwise.
95string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -070096 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -070097 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -070098 return "";
99}
100
101// Returns an XML ping element if any of the elapsed days need to be
102// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700103string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700104 string ping_active = GetPingAttribute("a", ping_active_days);
105 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
106 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700107 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700108 ping_active.c_str(),
109 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700110 }
111 return "";
112}
113
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700114// Returns an XML that goes into the body of the <app> element of the Omaha
115// request based on the given parameters.
116string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700117 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700118 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700119 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700120 int ping_active_days,
121 int ping_roll_call_days,
122 PrefsInterface* prefs) {
123 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700124 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700125 if (include_ping)
126 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700127 if (!ping_only) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700128 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700129 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700130 "></updatecheck>\n",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700131 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700132
Darin Petkov265f2902011-05-09 15:17:40 -0700133 // If this is the first update check after a reboot following a previous
134 // update, generate an event containing the previous version number. If
135 // the previous version preference file doesn't exist the event is still
136 // generated with a previous version of 0.0.0.0 -- this is relevant for
137 // older clients or new installs. The previous version event is not sent
138 // for ping-only requests because they come before the client has
Alex Deymo87c08862015-10-30 21:56:55 -0700139 // rebooted. The previous version event is also not sent if it was already
140 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700141 string prev_version;
142 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
143 prev_version = "0.0.0.0";
144 }
Alex Deymo87c08862015-10-30 21:56:55 -0700145 // We only store a non-empty previous version value after a successful
146 // update in the previous boot. After reporting it back to the server,
147 // we clear the previous version value so it doesn't get reported again.
148 if (!prev_version.empty()) {
149 app_body += base::StringPrintf(
150 " <event eventtype=\"%d\" eventresult=\"%d\" "
151 "previousversion=\"%s\"></event>\n",
Alex Deymo9fded1e2015-11-05 12:31:19 -0800152 OmahaEvent::kTypeRebootedAfterUpdate,
153 OmahaEvent::kResultSuccess,
Alex Deymo87c08862015-10-30 21:56:55 -0700154 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
155 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
156 << "Unable to reset the previous version.";
157 }
Darin Petkov95508da2011-01-05 12:42:29 -0800158 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700159 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800160 // The error code is an optional attribute so append it only if the result
161 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700162 string error_code;
163 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700164 error_code = base::StringPrintf(" errorcode=\"%d\"",
165 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700166 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700167 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700168 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700169 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700170 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700171
172 return app_body;
173}
174
Alex Deymo8e18f932015-03-27 16:16:59 -0700175// Returns the cohort* argument to include in the <app> tag for the passed
176// |arg_name| and |prefs_key|, if any. The return value is suitable to
177// concatenate to the list of arguments and includes a space at the end.
178string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700179 const string arg_name,
180 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700181 // There's nothing wrong with not having a given cohort setting, so we check
182 // existance first to avoid the warning log message.
183 if (!prefs->Exists(prefs_key))
184 return "";
185 string cohort_value;
186 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
187 return "";
188 // This is a sanity check to avoid sending a huge XML file back to Ohama due
189 // to a compromised stateful partition making the update check fail in low
190 // network environments envent after a reboot.
191 if (cohort_value.size() > 1024) {
192 LOG(WARNING) << "The omaha cohort setting " << arg_name
193 << " has a too big value, which must be an error or an "
194 "attacker trying to inhibit updates.";
195 return "";
196 }
197
Alex Deymob0d74eb2015-03-30 17:59:17 -0700198 string escaped_xml_value;
199 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
200 LOG(WARNING) << "The omaha cohort setting " << arg_name
201 << " is ASCII-7 invalid, ignoring it.";
202 return "";
203 }
204
Alex Deymo8e18f932015-03-27 16:16:59 -0700205 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700206 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700207}
208
Sen Jiang94a4dec2017-03-28 18:23:35 -0700209struct OmahaAppData {
210 string id;
211 string version;
Sen Jiang684c9cd2017-10-17 16:26:45 -0700212 string product_components;
Sen Jiang94a4dec2017-03-28 18:23:35 -0700213};
214
Sen Jiang684c9cd2017-10-17 16:26:45 -0700215bool IsValidComponentID(const string& id) {
216 for (char c : id) {
217 if (!isalnum(c) && c != '-' && c != '_' && c != '.')
218 return false;
219 }
220 return true;
221}
222
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700223// Returns an XML that corresponds to the entire <app> node of the Omaha
224// request based on the given parameters.
225string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700226 OmahaRequestParams* params,
Sen Jiang94a4dec2017-03-28 18:23:35 -0700227 const OmahaAppData& app_data,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700228 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700229 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700230 int ping_active_days,
231 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800232 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700233 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700234 string app_body = GetAppBody(event, params, ping_only, include_ping,
235 ping_active_days, ping_roll_call_days,
236 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700237 string app_versions;
238
Sen Jiang8cd42342018-01-31 12:06:59 -0800239 // If we are downgrading to a more stable channel and we are allowed to do
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700240 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
241 // highest-versioned payload on the destination channel.
Sen Jiang8cd42342018-01-31 12:06:59 -0800242 bool is_potential_downgrade =
243 params->to_more_stable_channel() && params->is_powerwash_allowed();
244 if (is_potential_downgrade) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700245 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
246 << "on downgrading to the version in the more stable channel";
247 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700248 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700249 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700250 app_versions = "version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700251 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700252 }
253
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700254 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700255 string app_channels =
256 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
257 if (params->current_channel() != download_channel) {
258 app_channels += "from_track=\"" + XmlEncodeWithDefault(
259 params->current_channel(), "") + "\" ";
260 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700261
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700262 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700263
David Zeuthen639aa362014-02-03 16:23:44 -0800264 // If install_date_days is not set (e.g. its value is -1 ), don't
265 // include the attribute.
266 string install_date_in_days_str = "";
267 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700268 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
269 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800270 }
271
Alex Deymo8e18f932015-03-27 16:16:59 -0700272 string app_cohort_args;
273 app_cohort_args += GetCohortArgXml(system_state->prefs(),
274 "cohort", kPrefsOmahaCohort);
275 app_cohort_args += GetCohortArgXml(system_state->prefs(),
276 "cohorthint", kPrefsOmahaCohortHint);
277 app_cohort_args += GetCohortArgXml(system_state->prefs(),
278 "cohortname", kPrefsOmahaCohortName);
279
Alex Deymoebf6e122017-03-10 16:12:01 -0800280 string fingerprint_arg;
281 if (!params->os_build_fingerprint().empty()) {
Sen Jiang8cd42342018-01-31 12:06:59 -0800282 fingerprint_arg = "fingerprint=\"" +
283 XmlEncodeWithDefault(params->os_build_fingerprint(), "") +
284 "\" ";
Alex Deymoebf6e122017-03-10 16:12:01 -0800285 }
286
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700287 string buildtype_arg;
288 if (!params->os_build_type().empty()) {
289 buildtype_arg = "os_build_type=\"" +
290 XmlEncodeWithDefault(params->os_build_type(), "") + "\" ";
291 }
292
Sen Jiang684c9cd2017-10-17 16:26:45 -0700293 string product_components_args;
Sen Jiang8cd42342018-01-31 12:06:59 -0800294 if (!is_potential_downgrade && !app_data.product_components.empty()) {
Sen Jiang684c9cd2017-10-17 16:26:45 -0700295 brillo::KeyValueStore store;
296 if (store.LoadFromString(app_data.product_components)) {
297 for (const string& key : store.GetKeys()) {
298 if (!IsValidComponentID(key)) {
299 LOG(ERROR) << "Invalid component id: " << key;
300 continue;
301 }
302 string version;
303 if (!store.GetString(key, &version)) {
304 LOG(ERROR) << "Failed to get version for " << key
305 << " in product_components.";
306 continue;
307 }
308 product_components_args +=
309 base::StringPrintf("_%s.version=\"%s\" ",
310 key.c_str(),
311 XmlEncodeWithDefault(version, "").c_str());
312 }
313 } else {
314 LOG(ERROR) << "Failed to parse product_components:\n"
315 << app_data.product_components;
316 }
317 }
318
319 // clang-format off
Alex Deymob0d74eb2015-03-30 17:59:17 -0700320 string app_xml = " <app "
Sen Jiang94a4dec2017-03-28 18:23:35 -0700321 "appid=\"" + XmlEncodeWithDefault(app_data.id, "") + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700322 app_cohort_args +
323 app_versions +
324 app_channels +
Sen Jiang684c9cd2017-10-17 16:26:45 -0700325 product_components_args +
Alex Deymoebf6e122017-03-10 16:12:01 -0800326 fingerprint_arg +
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700327 buildtype_arg +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700328 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
329 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
330 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
331 "delta_okay=\"" + delta_okay_str + "\" "
332 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
333 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
334 install_date_in_days_str +
335 ">\n" +
336 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700337 " </app>\n";
Sen Jiang684c9cd2017-10-17 16:26:45 -0700338 // clang-format on
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700339 return app_xml;
340}
341
342// Returns an XML that corresponds to the entire <os> node of the Omaha
343// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700344string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700345 string os_xml =" <os "
346 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
347 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
348 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
349 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700350 return os_xml;
351}
352
353// Returns an XML that corresponds to the entire Omaha request based on the
354// given parameters.
355string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700356 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700357 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700358 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700359 int ping_active_days,
360 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800361 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700362 SystemState* system_state) {
363 string os_xml = GetOsXml(params);
Sen Jiang684c9cd2017-10-17 16:26:45 -0700364 OmahaAppData product_app = {
365 .id = params->GetAppId(),
366 .version = params->app_version(),
367 .product_components = params->product_components()};
Sen Jiang94a4dec2017-03-28 18:23:35 -0700368 string app_xml = GetAppXml(event,
369 params,
370 product_app,
371 ping_only,
372 include_ping,
373 ping_active_days,
374 ping_roll_call_days,
375 install_date_in_days,
376 system_state);
377 if (!params->system_app_id().empty()) {
378 OmahaAppData system_app = {.id = params->system_app_id(),
379 .version = params->system_version()};
380 app_xml += GetAppXml(event,
381 params,
382 system_app,
383 ping_only,
384 include_ping,
385 ping_active_days,
386 ping_roll_call_days,
387 install_date_in_days,
388 system_state);
389 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700390
Alex Vakulenko75039d72014-03-25 12:36:28 -0700391 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700392 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700393
Alex Deymoac41a822015-09-15 20:52:53 -0700394 string updater_version = XmlEncodeWithDefault(
395 base::StringPrintf("%s-%s",
396 constants::kOmahaUpdaterID,
397 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700398 string request_xml =
399 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700400 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700401 "version=\"" + updater_version + "\" "
402 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700403 install_source +
404 "ismachine=\"1\">\n") +
405 os_xml +
406 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700407 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700408
409 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000410}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700411
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700412} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000413
David Zeuthene8ed8632014-07-24 13:38:10 -0400414// Struct used for holding data obtained when parsing the XML.
415struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400416 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
417
418 // Pointer to the expat XML_Parser object.
419 XML_Parser xml_parser;
420
David Zeuthene8ed8632014-07-24 13:38:10 -0400421 // This is the state of the parser as it's processing the XML.
422 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400423 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400424 string current_path;
425
426 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400427 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700428 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400429 string daystart_elapsed_days;
430 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800431
Sen Jiang81259682017-03-30 15:11:30 -0700432 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700433 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700434 vector<string> url_codebase;
435 string manifest_version;
436 map<string, string> action_postinstall_attrs;
437 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700438 string cohort;
439 string cohorthint;
440 string cohortname;
441 bool cohort_set = false;
442 bool cohorthint_set = false;
443 bool cohortname_set = false;
Sen Jiang81259682017-03-30 15:11:30 -0700444
445 struct Package {
446 string name;
447 string size;
448 string hash;
449 };
450 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800451 };
Sen Jiang81259682017-03-30 15:11:30 -0700452 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400453};
454
455namespace {
456
457// Callback function invoked by expat.
458void ParserHandlerStart(void* user_data, const XML_Char* element,
459 const XML_Char** attr) {
460 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
461
462 if (data->failed)
463 return;
464
465 data->current_path += string("/") + element;
466
467 map<string, string> attrs;
468 if (attr != nullptr) {
469 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
470 string key = attr[n];
471 string value = attr[n + 1];
472 attrs[key] = value;
473 }
474 }
475
Alex Deymo8e18f932015-03-27 16:16:59 -0700476 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700477 OmahaParserData::App app;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700478 if (attrs.find("appid") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700479 app.id = attrs["appid"];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700480 }
Alex Deymo8e18f932015-03-27 16:16:59 -0700481 if (attrs.find("cohort") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700482 app.cohort_set = true;
483 app.cohort = attrs["cohort"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700484 }
485 if (attrs.find("cohorthint") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700486 app.cohorthint_set = true;
487 app.cohorthint = attrs["cohorthint"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700488 }
489 if (attrs.find("cohortname") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700490 app.cohortname_set = true;
491 app.cohortname = attrs["cohortname"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700492 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700493 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700494 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700495 if (!data->apps.empty())
496 data->apps.back().updatecheck_status = attrs["status"];
497 if (data->updatecheck_poll_interval.empty())
498 data->updatecheck_poll_interval = attrs["PollInterval"];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700499 // Omaha sends arbitrary key-value pairs as extra attributes starting with
500 // an underscore.
501 for (const auto& attr : attrs) {
502 if (!attr.first.empty() && attr.first[0] == '_')
503 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
504 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400505 } else if (data->current_path == "/response/daystart") {
506 // Get the install-date.
507 data->daystart_elapsed_days = attrs["elapsed_days"];
508 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
509 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
510 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700511 if (!data->apps.empty())
512 data->apps.back().url_codebase.push_back(attrs["codebase"]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800513 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400514 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800515 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700516 if (!data->apps.empty())
517 data->apps.back().packages.push_back({.name = attrs["name"],
518 .size = attrs["size"],
519 .hash = attrs["hash_sha256"]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400520 } else if (data->current_path == "/response/app/updatecheck/manifest") {
521 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700522 if (!data->apps.empty())
523 data->apps.back().manifest_version = attrs[kTagVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400524 } else if (data->current_path ==
525 "/response/app/updatecheck/manifest/actions/action") {
526 // We only care about the postinstall action.
Sen Jiang81259682017-03-30 15:11:30 -0700527 if (attrs["event"] == "postinstall" && !data->apps.empty()) {
528 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400529 }
530 }
531}
532
533// Callback function invoked by expat.
534void ParserHandlerEnd(void* user_data, const XML_Char* element) {
535 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
536 if (data->failed)
537 return;
538
539 const string path_suffix = string("/") + element;
540
Alex Vakulenko0103c362016-01-20 07:56:15 -0800541 if (!base::EndsWith(data->current_path, path_suffix,
542 base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400543 LOG(ERROR) << "Unexpected end element '" << element
544 << "' with current_path='" << data->current_path << "'";
545 data->failed = true;
546 return;
547 }
548 data->current_path.resize(data->current_path.size() - path_suffix.size());
549}
550
David Zeuthenf3e28012014-08-26 18:23:52 -0400551// Callback function invoked by expat.
552//
553// This is called for entity declarations. Since Omaha is guaranteed
554// to never return any XML with entities our course of action is to
555// just stop parsing. This avoids potential resource exhaustion
556// problems AKA the "billion laughs". CVE-2013-0340.
557void ParserHandlerEntityDecl(void *user_data,
558 const XML_Char *entity_name,
559 int is_parameter_entity,
560 const XML_Char *value,
561 int value_length,
562 const XML_Char *base,
563 const XML_Char *system_id,
564 const XML_Char *public_id,
565 const XML_Char *notation_name) {
566 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
567
568 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
569 data->failed = true;
570 data->entity_decl = true;
571 XML_StopParser(data->xml_parser, false);
572}
573
David Zeuthene8ed8632014-07-24 13:38:10 -0400574} // namespace
575
Alex Deymob0d74eb2015-03-30 17:59:17 -0700576bool XmlEncode(const string& input, string* output) {
577 if (std::find_if(input.begin(), input.end(),
578 [](const char c){return c & 0x80;}) != input.end()) {
579 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
580 utils::HexDumpString(input);
581 return false;
582 }
Alex Deymocc457852015-06-18 18:35:50 -0700583 output->clear();
584 // We need at least input.size() space in the output, but the code below will
585 // handle it if we need more.
586 output->reserve(input.size());
587 for (char c : input) {
588 switch (c) {
589 case '\"':
590 output->append("&quot;");
591 break;
592 case '\'':
593 output->append("&apos;");
594 break;
595 case '&':
596 output->append("&amp;");
597 break;
598 case '<':
599 output->append("&lt;");
600 break;
601 case '>':
602 output->append("&gt;");
603 break;
604 default:
605 output->push_back(c);
606 }
607 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700608 return true;
609}
610
611string XmlEncodeWithDefault(const string& input, const string& default_value) {
612 string output;
613 if (XmlEncode(input, &output))
614 return output;
615 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000616}
617
Alex Deymoc1c17b42015-11-23 03:53:15 -0300618OmahaRequestAction::OmahaRequestAction(
619 SystemState* system_state,
620 OmahaEvent* event,
621 std::unique_ptr<HttpFetcher> http_fetcher,
622 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800623 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700624 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300625 http_fetcher_(std::move(http_fetcher)),
Thieu Le116fda32011-04-19 11:01:54 -0700626 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700627 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700628 ping_roll_call_days_(0) {
629 params_ = system_state->request_params();
630}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000631
Darin Petkov6a5b3222010-07-13 14:55:28 -0700632OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000633
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700634// Calculates the value to use for the ping days parameter.
635int OmahaRequestAction::CalculatePingDays(const string& key) {
636 int days = kNeverPinged;
637 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800638 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700639 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
640 if (days < 0) {
641 // If |days| is negative, then the system clock must have jumped
642 // back in time since the ping was sent. Mark the value so that
643 // it doesn't get sent to the server but we still update the
644 // last ping daystart preference. This way the next ping time
645 // will be correct, hopefully.
646 days = kPingTimeJump;
647 LOG(WARNING) <<
648 "System clock jumped back in time. Resetting ping daystarts.";
649 }
650 }
651 return days;
652}
653
654void OmahaRequestAction::InitPingDays() {
655 // We send pings only along with update checks, not with events.
656 if (IsEvent()) {
657 return;
658 }
659 // TODO(petkov): Figure a way to distinguish active use pings
660 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700661 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700662 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
663 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
664}
665
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700666bool OmahaRequestAction::ShouldPing() const {
667 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
668 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
669 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
670 if (powerwash_count > 0) {
671 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
672 << "powerwash_count is " << powerwash_count;
673 return false;
674 }
Amin Hassani1677e812017-06-21 13:36:36 -0700675 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
676 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
677 << "the first_active_omaha_ping_sent is true";
678 return false;
679 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700680 return true;
681 }
682 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
683}
684
David Zeuthen639aa362014-02-03 16:23:44 -0800685// static
686int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
687 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700688 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800689 return -1;
690
691 // If we have the value stored on disk, just return it.
692 int64_t stored_value;
693 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
694 // Convert and sanity-check.
695 int install_date_days = static_cast<int>(stored_value);
696 if (install_date_days >= 0)
697 return install_date_days;
698 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
699 << install_date_days << " looks suspicious.";
700 prefs->Delete(kPrefsInstallDateDays);
701 }
702
703 // Otherwise, if OOBE is not complete then do nothing and wait for
704 // ParseResponse() to call ParseInstallDate() and then
705 // PersistInstallDate() to set the kPrefsInstallDateDays state
706 // variable. Once that is done, we'll then report back in future
707 // Omaha requests. This works exactly because OOBE triggers an
708 // update check.
709 //
710 // However, if OOBE is complete and the kPrefsInstallDateDays state
711 // variable is not set, there are two possibilities
712 //
713 // 1. The update check in OOBE failed so we never got a response
714 // from Omaha (no network etc.); or
715 //
716 // 2. OOBE was done on an older version that didn't write to the
717 // kPrefsInstallDateDays state variable.
718 //
719 // In both cases, we approximate the install date by simply
720 // inspecting the timestamp of when OOBE happened.
721
722 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700723 if (!system_state->hardware()->IsOOBEEnabled() ||
724 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800725 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700726 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800727 return -1;
728 }
729
730 int num_days;
731 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
732 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
733 << "as its value '" << utils::ToString(time_of_oobe)
734 << "' looks suspicious.";
735 return -1;
736 }
737
738 // Persist this to disk, for future use.
739 if (!OmahaRequestAction::PersistInstallDate(system_state,
740 num_days,
741 kProvisionedFromOOBEMarker))
742 return -1;
743
744 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
745 << num_days << " days";
746
747 return num_days;
748}
749
Darin Petkov6a5b3222010-07-13 14:55:28 -0700750void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000751 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700752 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700753 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700754 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700755 return;
756 }
David Zeuthen639aa362014-02-03 16:23:44 -0800757
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700758 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700759 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700760 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700761 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700762 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800763 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800764 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700765 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700766
Alex Deymo14ad88e2016-06-29 12:30:14 -0700767 // Set X-GoogleUpdate headers.
768 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
769 params_->interactive() ? "fg" : "bg");
770 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
771 http_fetcher_->SetHeader(
772 kXGoogleUpdateUpdater,
773 base::StringPrintf(
774 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
775
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800776 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
777 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700778 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700779 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700780 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000781}
782
Darin Petkov6a5b3222010-07-13 14:55:28 -0700783void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000784 http_fetcher_->TerminateTransfer();
785}
786
787// We just store the response in the buffer. Once we've received all bytes,
788// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700789void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800790 const void* bytes,
791 size_t length) {
792 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
793 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000794}
795
796namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000797
798// Parses a 64 bit base-10 int from a string and returns it. Returns 0
799// on error. If the string contains "0", that's indistinguishable from
800// error.
801off_t ParseInt(const string& str) {
802 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700803 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000804 if (rc < 1) {
805 // failure
806 return 0;
807 }
808 return ret;
809}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700810
David Zeuthene8ed8632014-07-24 13:38:10 -0400811// Parses |str| and returns |true| if, and only if, its value is "true".
812bool ParseBool(const string& str) {
813 return str == "true";
814}
815
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700816// Update the last ping day preferences based on the server daystart
817// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400818bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700819 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400820 TEST_AND_RETURN_FALSE(
821 base::StringToInt64(parser_data->daystart_elapsed_seconds,
822 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700823 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
824
825 // Remember the local time that matches the server's last midnight
826 // time.
827 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
828 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
829 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
830 return true;
831}
Sen Jiang81259682017-03-30 15:11:30 -0700832
833// Parses the package node in the given XML document and populates
834// |output_object| if valid. Returns true if we should continue the parsing.
835// False otherwise, in which case it sets any error code using |completer|.
836bool ParsePackage(OmahaParserData::App* app,
837 OmahaResponse* output_object,
838 ScopedActionCompleter* completer) {
839 if (app->updatecheck_status == "noupdate") {
840 if (!app->packages.empty()) {
841 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
842 completer->set_code(ErrorCode::kOmahaResponseInvalid);
843 return false;
844 }
845 return true;
846 }
847 if (app->packages.empty()) {
848 LOG(ERROR) << "Omaha Response has no packages";
849 completer->set_code(ErrorCode::kOmahaResponseInvalid);
850 return false;
851 }
852 if (app->url_codebase.empty()) {
853 LOG(ERROR) << "No Omaha Response URLs";
854 completer->set_code(ErrorCode::kOmahaResponseInvalid);
855 return false;
856 }
857 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
858 vector<string> metadata_sizes =
859 base::SplitString(app->action_postinstall_attrs[kTagMetadataSize],
860 ":",
861 base::TRIM_WHITESPACE,
862 base::SPLIT_WANT_ALL);
863 vector<string> metadata_signatures =
864 base::SplitString(app->action_postinstall_attrs[kTagMetadataSignatureRsa],
865 ":",
866 base::TRIM_WHITESPACE,
867 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700868 vector<string> is_delta_payloads =
869 base::SplitString(app->action_postinstall_attrs[kTagIsDeltaPayload],
870 ":",
871 base::TRIM_WHITESPACE,
872 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700873 for (size_t i = 0; i < app->packages.size(); i++) {
874 const auto& package = app->packages[i];
875 if (package.name.empty()) {
876 LOG(ERROR) << "Omaha Response has empty package name";
877 completer->set_code(ErrorCode::kOmahaResponseInvalid);
878 return false;
879 }
880 LOG(INFO) << "Found package " << package.name;
881
882 OmahaResponse::Package out_package;
883 for (const string& codebase : app->url_codebase) {
884 if (codebase.empty()) {
885 LOG(ERROR) << "Omaha Response URL has empty codebase";
886 completer->set_code(ErrorCode::kOmahaResponseInvalid);
887 return false;
888 }
889 out_package.payload_urls.push_back(codebase + package.name);
890 }
891 // Parse the payload size.
892 base::StringToUint64(package.size, &out_package.size);
893 if (out_package.size <= 0) {
894 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
895 completer->set_code(ErrorCode::kOmahaResponseInvalid);
896 return false;
897 }
898 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
899
900 if (i < metadata_sizes.size())
901 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
902 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
903 << " bytes";
904
905 if (i < metadata_signatures.size())
906 out_package.metadata_signature = metadata_signatures[i];
907 LOG(INFO) << "Payload metadata signature = "
908 << out_package.metadata_signature;
909
910 out_package.hash = package.hash;
911 if (out_package.hash.empty()) {
912 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
913 completer->set_code(ErrorCode::kOmahaResponseInvalid);
914 return false;
915 }
916 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700917
918 if (i < is_delta_payloads.size())
919 out_package.is_delta = ParseBool(is_delta_payloads[i]);
920 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
921
Sen Jiang81259682017-03-30 15:11:30 -0700922 output_object->packages.push_back(std::move(out_package));
923 }
924
925 return true;
926}
927
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700928} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000929
David Zeuthene8ed8632014-07-24 13:38:10 -0400930bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700931 OmahaResponse* output_object,
932 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700933 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700934 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700935 return false;
936 }
Sen Jiang81259682017-03-30 15:11:30 -0700937 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700938
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800939 // chromium-os:37289: The PollInterval is not supported by Omaha server
940 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700941 // slow down the request rate from the server-side. Note that the PollInterval
942 // is not persisted, so it has to be sent by the server on every response to
943 // guarantee that the scheduler uses this value (otherwise, if the device got
944 // rebooted after the last server-indicated value, it'll revert to the default
945 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
946 // based on the assumption that we perform an update check every hour so that
947 // the max value of 8 will roughly be equivalent to one work day. If we decide
948 // to use PollInterval permanently, we should update the
949 // max_update_checks_allowed to take PollInterval into account. Note: The
950 // parsing for PollInterval happens even before parsing of the status because
951 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400952 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700953 &output_object->poll_interval);
954
David Zeuthen639aa362014-02-03 16:23:44 -0800955 // Check for the "elapsed_days" attribute in the "daystart"
956 // element. This is the number of days since Jan 1 2007, 0:00
957 // PST. If we don't have a persisted value of the Omaha InstallDate,
958 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400959 if (ParseInstallDate(parser_data, output_object) &&
960 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800961 // Since output_object->install_date_days is never negative, the
962 // elapsed_days -> install-date calculation is reduced to simply
963 // rounding down to the nearest number divisible by 7.
964 int remainder = output_object->install_date_days % 7;
965 int install_date_days_rounded =
966 output_object->install_date_days - remainder;
967 if (PersistInstallDate(system_state_,
968 install_date_days_rounded,
969 kProvisionedFromOmahaResponse)) {
970 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
971 << install_date_days_rounded << " days";
972 }
973 }
974
Alex Deymo00d79ac2015-06-29 15:41:49 -0700975 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -0700976 for (const auto& app : parser_data->apps) {
977 if (app.id == params_->GetAppId()) {
978 if (app.cohort_set)
979 PersistCohortData(kPrefsOmahaCohort, app.cohort);
980 if (app.cohorthint_set)
981 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
982 if (app.cohortname_set)
983 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
984 break;
985 }
986 }
Alex Deymo00d79ac2015-06-29 15:41:49 -0700987
Alex Deymob3fa53b2016-04-18 19:57:58 -0700988 // Parse the updatecheck attributes.
989 PersistEolStatus(parser_data->updatecheck_attrs);
990
David Zeuthene8ed8632014-07-24 13:38:10 -0400991 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700992 return false;
993
David Zeuthene8ed8632014-07-24 13:38:10 -0400994 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700995 return false;
996
Sen Jiang0affc2c2017-02-10 15:55:05 -0800997 // Package has to be parsed after Params now because ParseParams need to make
998 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -0700999 for (auto& app : parser_data->apps)
1000 if (!ParsePackage(&app, output_object, completer))
1001 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001002
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001003 return true;
1004}
1005
David Zeuthene8ed8632014-07-24 13:38:10 -04001006bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001007 OmahaResponse* output_object,
1008 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001009 output_object->update_exists = false;
1010 for (size_t i = 0; i < parser_data->apps.size(); i++) {
1011 const string& status = parser_data->apps[i].updatecheck_status;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001012 if (status == "noupdate") {
1013 // Don't update if any app has status="noupdate".
Sen Jiang81259682017-03-30 15:11:30 -07001014 LOG(INFO) << "No update for <app> " << i;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001015 output_object->update_exists = false;
1016 break;
Sen Jiang81259682017-03-30 15:11:30 -07001017 } else if (status == "ok") {
Sen Jiang00adf7b2017-06-26 15:57:29 -07001018 if (parser_data->apps[i].action_postinstall_attrs["noupdate"] == "true") {
1019 // noupdate="true" in postinstall attributes means it's an update to
1020 // self, only update if there's at least one app really have update.
1021 LOG(INFO) << "Update to self for <app> " << i;
1022 } else {
1023 LOG(INFO) << "Update for <app> " << i;
1024 output_object->update_exists = true;
1025 }
Sen Jiang81259682017-03-30 15:11:30 -07001026 } else {
1027 LOG(ERROR) << "Unknown Omaha response status: " << status;
1028 completer->set_code(ErrorCode::kOmahaResponseInvalid);
1029 return false;
1030 }
1031 }
1032 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001033 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001034 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001035 }
1036
Sen Jiang81259682017-03-30 15:11:30 -07001037 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001038}
1039
David Zeuthene8ed8632014-07-24 13:38:10 -04001040bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001041 OmahaResponse* output_object,
1042 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001043 map<string, string> attrs;
1044 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001045 if (app.id == params_->GetAppId()) {
1046 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -07001047 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001048 } else if (!params_->system_app_id().empty() &&
1049 app.id == params_->system_app_id()) {
1050 // this is the system app (this check is intentionally skipped if there is
1051 // no system_app_id set)
1052 output_object->system_version = app.manifest_version;
1053 }
1054 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -07001055 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001056 }
Sen Jiang81259682017-03-30 15:11:30 -07001057 }
Chris Sosa3b748432013-06-20 16:42:59 -07001058 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -07001059 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001060 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -07001061 return false;
1062 }
1063
1064 LOG(INFO) << "Received omaha response to update to version "
1065 << output_object->version;
1066
David Zeuthene8ed8632014-07-24 13:38:10 -04001067 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001068 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001069 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001070 return false;
1071 }
1072
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001073 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -04001074 output_object->more_info_url = attrs[kTagMoreInfo];
David Zeuthene8ed8632014-07-24 13:38:10 -04001075 output_object->prompt = ParseBool(attrs[kTagPrompt]);
1076 output_object->deadline = attrs[kTagDeadline];
1077 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001078 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -04001079 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001080 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -04001081 ParseBool(attrs[kTagDisableP2PForSharing]);
1082 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001083
David Zeuthene8ed8632014-07-24 13:38:10 -04001084 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -08001085 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001086 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001087
Jay Srinivasan08262882012-12-28 19:29:43 -08001088 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -04001089 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -08001090
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001091 return true;
1092}
1093
David Zeuthene8ed8632014-07-24 13:38:10 -04001094// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +00001095// and fill in the appropriate fields of the output object. Also, notifies
1096// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -07001097void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
1098 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +00001099 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001100 string current_response(response_buffer_.begin(), response_buffer_.end());
1101 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001102
Gilad Arnold74b5f552014-10-07 08:17:16 -07001103 PayloadStateInterface* const payload_state = system_state_->payload_state();
1104
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001105 // Events are best effort transactions -- assume they always succeed.
1106 if (IsEvent()) {
1107 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001108 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001109 return;
1110 }
1111
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001112 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001113 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -07001114 int code = GetHTTPResponseCode();
1115 // Makes sure we send sane error values.
1116 if (code < 0 || code >= 1000) {
1117 code = 999;
1118 }
David Zeuthena99981f2013-04-29 13:42:47 -07001119 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001120 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +00001121 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001122 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001123
David Zeuthene8ed8632014-07-24 13:38:10 -04001124 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -04001125 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -04001126 XML_SetUserData(parser, &parser_data);
1127 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -04001128 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001129 XML_Status res = XML_Parse(
1130 parser,
1131 reinterpret_cast<const char*>(response_buffer_.data()),
1132 response_buffer_.size(),
1133 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -04001134 XML_ParserFree(parser);
1135
1136 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -07001137 LOG(ERROR) << "Omaha response not valid XML: "
1138 << XML_ErrorString(XML_GetErrorCode(parser))
1139 << " at line " << XML_GetCurrentLineNumber(parser)
1140 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -04001141 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
1142 if (response_buffer_.empty()) {
1143 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
1144 } else if (parser_data.entity_decl) {
1145 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
1146 }
1147 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001148 return;
1149 }
1150
Alex Deymoebbe7ef2014-10-30 13:02:49 -07001151 // Update the last ping day preferences based on the server daystart response
1152 // even if we didn't send a ping. Omaha always includes the daystart in the
1153 // response, but log the error if it didn't.
1154 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
1155 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -07001156
Amin Hassani1677e812017-06-21 13:36:36 -07001157 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
1158 // we have got a response from omaha and if its value has never been set to
1159 // true before. Failure of this function should be ignored. There should be no
1160 // need to check if a=-1 has been sent because older devices have already sent
1161 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
1162 // future checks.
1163 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
1164 system_state_->hardware()->SetFirstActiveOmahaPingSent();
1165 }
1166
Thieu Le116fda32011-04-19 11:01:54 -07001167 if (!HasOutputPipe()) {
1168 // Just set success to whether or not the http transfer succeeded,
1169 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001170 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001171 return;
1172 }
1173
Darin Petkov6a5b3222010-07-13 14:55:28 -07001174 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001175 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001176 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001177 output_object.update_exists = true;
1178 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001179
Tao Bao5688d162017-06-06 13:09:06 -07001180 if (ShouldIgnoreUpdate(output_object)) {
1181 output_object.update_exists = false;
1182 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001183 return;
1184 }
1185
David Zeuthen8f191b22013-08-06 12:27:50 -07001186 // If Omaha says to disable p2p, respect that
1187 if (output_object.disable_p2p_for_downloading) {
1188 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1189 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001190 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001191 }
1192 if (output_object.disable_p2p_for_sharing) {
1193 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1194 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001195 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001196 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001197
1198 // Update the payload state with the current response. The payload state
1199 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001200 // from what's stored already. We are updating the payload state as late
1201 // as possible in this method so that if a new release gets pushed and then
1202 // got pulled back due to some issues, we don't want to clear our internal
1203 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001204 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001205
David Zeuthen8f191b22013-08-06 12:27:50 -07001206 // It could be we've already exceeded the deadline for when p2p is
1207 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001208 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001209 payload_state->P2PNewAttempt();
1210 if (!payload_state->P2PAttemptAllowed()) {
1211 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1212 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001213 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001214 }
1215 }
1216
1217 // From here on, we'll complete stuff in CompleteProcessing() so
1218 // disable |completer| since we'll create a new one in that
1219 // function.
1220 completer.set_should_complete(false);
1221
1222 // If we're allowed to use p2p for downloading we do not pay
1223 // attention to wall-clock-based waiting if the URL is indeed
1224 // available via p2p. Therefore, check if the file is available via
1225 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001226 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001227 LookupPayloadViaP2P(output_object);
1228 } else {
1229 CompleteProcessing();
1230 }
1231}
1232
1233void OmahaRequestAction::CompleteProcessing() {
1234 ScopedActionCompleter completer(processor_, this);
1235 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1236 PayloadStateInterface* payload_state = system_state_->payload_state();
1237
Alex Deymo46a9aae2016-05-04 20:20:11 -07001238 if (system_state_->hardware()->IsOOBEEnabled() &&
1239 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
Kevin Cernekeec5081a82016-04-08 12:29:52 -07001240 output_object.deadline.empty() &&
1241 params_->app_version() != "ForcedUpdate") {
Kevin Cernekee2494e282016-03-29 18:03:53 -07001242 output_object.update_exists = false;
1243 LOG(INFO) << "Ignoring non-critical Omaha updates until OOBE is done.";
1244 completer.set_code(ErrorCode::kNonCriticalUpdateInOOBE);
1245 return;
1246 }
1247
David Zeuthen8f191b22013-08-06 12:27:50 -07001248 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001249 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001250 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001251 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001252 return;
1253 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001254
Chris Sosa20f005c2013-09-05 13:53:08 -07001255 if (payload_state->ShouldBackoffDownload()) {
1256 output_object.update_exists = false;
1257 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1258 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001259 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001260 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001261 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001262 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001263}
1264
1265void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1266 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1267 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001268 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001269 } else {
1270 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1271 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001272 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001273 }
1274 CompleteProcessing();
1275}
1276
1277void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001278 // If the device is in the middle of an update, the state variables
1279 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1280 // tracks the offset and length of the operation currently in
1281 // progress. The offset is based from the end of the manifest which
1282 // is kPrefsManifestMetadataSize bytes long.
1283 //
1284 // To make forward progress and avoid deadlocks, we need to find a
1285 // peer that has at least the entire operation we're currently
1286 // working on. Otherwise we may end up in a situation where two
1287 // devices bounce back and forth downloading from each other,
1288 // neither making any forward progress until one of them decides to
1289 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1290 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001291 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001292 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001293 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001294 int64_t next_data_offset = 0;
1295 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001296 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001297 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1298 &manifest_metadata_size) &&
1299 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001300 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1301 &manifest_signature_size) &&
1302 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001303 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001304 &next_data_offset) &&
1305 next_data_offset != -1 &&
1306 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1307 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001308 minimum_size = manifest_metadata_size + manifest_signature_size +
1309 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001310 }
1311
Sen Jiang0affc2c2017-02-10 15:55:05 -08001312 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001313 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001314 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001315 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001316 string file_id =
1317 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001318 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001319 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1320 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001321 system_state_->p2p_manager()->LookupUrlForFile(
1322 file_id,
1323 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001324 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001325 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1326 base::Unretained(this)));
1327 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001328}
1329
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001330bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001331 if (params_->interactive()) {
1332 LOG(INFO) << "Not deferring download because update is interactive.";
1333 return false;
1334 }
1335
David Zeuthen8f191b22013-08-06 12:27:50 -07001336 // If we're using p2p to download _and_ we have a p2p URL, we never
1337 // defer the download. This is because the download will always
1338 // happen from a peer on the LAN and we've been waiting in line for
1339 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001340 const PayloadStateInterface* payload_state = system_state_->payload_state();
1341 if (payload_state->GetUsingP2PForDownloading() &&
1342 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001343 LOG(INFO) << "Download not deferred because download "
1344 << "will happen from a local peer (via p2p).";
1345 return false;
1346 }
1347
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001348 // We should defer the downloads only if we've first satisfied the
1349 // wall-clock-based-waiting period and then the update-check-based waiting
1350 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001351 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001352 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1353 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001354 return false;
1355 }
1356
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001357 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001358 case kWallClockWaitNotSatisfied:
1359 // We haven't even satisfied the first condition, passing the
1360 // wall-clock-based waiting period, so we should defer the downloads
1361 // until that happens.
1362 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1363 return true;
1364
1365 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1366 LOG(INFO) << "wall-clock-based-wait satisfied and "
1367 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001368 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001369
1370 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1371 // Wall-clock-based waiting period is satisfied, and it's determined
1372 // that we do not need the update-check-based wait. so no need to
1373 // defer downloads.
1374 LOG(INFO) << "wall-clock-based-wait satisfied and "
1375 << "update-check-based-wait is not required.";
1376 return false;
1377
1378 default:
1379 // Returning false for this default case so we err on the
1380 // side of downloading updates than deferring in case of any bugs.
1381 NOTREACHED();
1382 return false;
1383 }
1384}
1385
1386OmahaRequestAction::WallClockWaitResult
1387OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001388 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001389 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001390 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001391
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001392 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1393 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1394 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001395 // Note: This timestamp could be that of ANY update we saw in the past
1396 // (not necessarily this particular update we're considering to apply)
1397 // but never got to apply because of some reason (e.g. stop AU policy,
1398 // updates being pulled out from Omaha, changes in target version prefix,
1399 // new update being rolled out, etc.). But for the purposes of scattering
1400 // it doesn't matter which update the timestamp corresponds to. i.e.
1401 // the clock starts ticking the first time we see an update and we're
1402 // ready to apply when the random wait period is satisfied relative to
1403 // that first seen timestamp.
1404 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1405 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1406 << utils::ToString(update_first_seen_at);
1407 } else {
1408 // This seems like an unexpected error where the persisted value exists
1409 // but it's not readable for some reason. Just skip scattering in this
1410 // case to be safe.
1411 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1412 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1413 }
1414 } else {
Sen Jiang7c1171e2016-06-23 11:35:40 -07001415 update_first_seen_at = system_state_->clock()->GetWallclockTime();
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001416 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001417 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1418 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001419 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1420 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001421 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001422 // This seems like an unexpected error where the value cannot be
1423 // persisted for some reason. Just skip scattering in this
1424 // case to be safe.
1425 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1426 << utils::ToString(update_first_seen_at)
1427 << " cannot be persisted";
1428 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1429 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001430 }
1431
Sen Jiang7c1171e2016-06-23 11:35:40 -07001432 TimeDelta elapsed_time =
1433 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1434 TimeDelta max_scatter_period =
1435 TimeDelta::FromDays(output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001436
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001437 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001438 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001439 << ", Time Elapsed = "
1440 << utils::FormatSecs(elapsed_time.InSeconds())
1441 << ", MaxDaysToScatter = "
1442 << max_scatter_period.InDays();
1443
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001444 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001445 // The deadline is set for all rules which serve a delta update from a
1446 // previous FSI, which means this update will be applied mostly in OOBE
1447 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1448 // quickly.
1449 LOG(INFO) << "Not scattering as deadline flag is set";
1450 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1451 }
1452
1453 if (max_scatter_period.InDays() == 0) {
1454 // This means the Omaha rule creator decides that this rule
1455 // should not be scattered irrespective of the policy.
1456 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1457 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1458 }
1459
1460 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001461 // This means we've waited more than the upperbound wait in the rule
1462 // from the time we first saw a valid update available to us.
1463 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001464 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1465 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1466 }
1467
1468 // This means we are required to participate in scattering.
1469 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001470 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001471 if (remaining_wait_time.InSeconds() <= 0) {
1472 // Yes, it's our turn now.
1473 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1474
1475 // But we can't download until the update-check-count-based wait is also
1476 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001477 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001478 kWallClockWaitDoneButUpdateCheckWaitRequired :
1479 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1480 }
1481
1482 // Not our turn yet, so we have to wait until our turn to
1483 // help scatter the downloads across all clients of the enterprise.
1484 LOG(INFO) << "Update deferred for another "
1485 << utils::FormatSecs(remaining_wait_time.InSeconds())
1486 << " per policy.";
1487 return kWallClockWaitNotSatisfied;
1488}
1489
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001490bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001491 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001492
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001493 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1494 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1495 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001496 // We are unable to read the update check count from file for some reason.
1497 // So let's proceed anyway so as to not stall the update.
1498 LOG(ERROR) << "Unable to read update check count. "
1499 << "Skipping update-check-count-based-wait.";
1500 return true;
1501 }
1502 } else {
1503 // This file does not exist. This means we haven't started our update
1504 // check count down yet, so this is the right time to start the count down.
1505 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001506 params_->min_update_checks_needed(),
1507 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001508
1509 LOG(INFO) << "Randomly picked update check count value = "
1510 << update_check_count_value;
1511
1512 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001513 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1514 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001515 // We weren't able to write the update check count file for some reason.
1516 // So let's proceed anyway so as to not stall the update.
1517 LOG(ERROR) << "Unable to write update check count. "
1518 << "Skipping update-check-count-based-wait.";
1519 return true;
1520 }
1521 }
1522
1523 if (update_check_count_value == 0) {
1524 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1525 return true;
1526 }
1527
1528 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001529 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001530 // We err on the side of skipping scattering logic instead of stalling
1531 // a machine from receiving any updates in case of any unexpected state.
1532 LOG(ERROR) << "Invalid value for update check count detected. "
1533 << "Skipping update-check-count-based-wait.";
1534 return true;
1535 }
1536
1537 // Legal value, we need to wait for more update checks to happen
1538 // until this becomes 0.
1539 LOG(INFO) << "Deferring Omaha updates for another "
1540 << update_check_count_value
1541 << " update checks per policy";
1542 return false;
1543}
1544
David Zeuthen639aa362014-02-03 16:23:44 -08001545// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001546bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001547 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001548 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001549 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001550 &elapsed_days))
1551 return false;
1552
1553 if (elapsed_days < 0)
1554 return false;
1555
1556 output_object->install_date_days = elapsed_days;
1557 return true;
1558}
1559
1560// static
1561bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1562 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001563 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001564 return false;
1565
1566 return prefs->Exists(kPrefsInstallDateDays);
1567}
1568
1569// static
1570bool OmahaRequestAction::PersistInstallDate(
1571 SystemState *system_state,
1572 int install_date_days,
1573 InstallDateProvisioningSource source) {
1574 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1575
1576 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001577 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001578 return false;
1579
1580 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1581 return false;
1582
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001583 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001584 static_cast<int>(source), // Sample.
1585 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001586 return true;
1587}
1588
Alex Deymo8e18f932015-03-27 16:16:59 -07001589bool OmahaRequestAction::PersistCohortData(
1590 const string& prefs_key,
1591 const string& new_value) {
1592 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1593 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1594 return system_state_->prefs()->Delete(prefs_key);
1595 } else if (!new_value.empty()) {
1596 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1597 return system_state_->prefs()->SetString(prefs_key, new_value);
1598 }
1599 return true;
1600}
1601
Alex Deymob3fa53b2016-04-18 19:57:58 -07001602bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
1603 auto eol_attr = attrs.find(kEolAttr);
1604 if (eol_attr != attrs.end()) {
1605 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1606 eol_attr->second);
1607 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1608 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1609 }
1610 return true;
1611}
1612
David Zeuthen33bae492014-02-25 16:16:18 -08001613void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1614 // We only want to report this on "update check".
1615 if (ping_only_ || event_ != nullptr)
1616 return;
1617
1618 metrics::CheckResult result = metrics::CheckResult::kUnset;
1619 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1620 metrics::DownloadErrorCode download_error_code =
1621 metrics::DownloadErrorCode::kUnset;
1622
1623 // Regular update attempt.
1624 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001625 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001626 // OK, we parsed the response successfully but that does
1627 // necessarily mean that an update is available.
1628 if (HasOutputPipe()) {
1629 const OmahaResponse& response = GetOutputObject();
1630 if (response.update_exists) {
1631 result = metrics::CheckResult::kUpdateAvailable;
1632 reaction = metrics::CheckReaction::kUpdating;
1633 } else {
1634 result = metrics::CheckResult::kNoUpdateAvailable;
1635 }
1636 } else {
1637 result = metrics::CheckResult::kNoUpdateAvailable;
1638 }
1639 break;
1640
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001641 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001642 result = metrics::CheckResult::kUpdateAvailable;
1643 reaction = metrics::CheckReaction::kIgnored;
1644 break;
1645
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001646 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001647 result = metrics::CheckResult::kUpdateAvailable;
1648 reaction = metrics::CheckReaction::kDeferring;
1649 break;
1650
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001651 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001652 result = metrics::CheckResult::kUpdateAvailable;
1653 reaction = metrics::CheckReaction::kBackingOff;
1654 break;
1655
1656 default:
1657 // We report two flavors of errors, "Download errors" and "Parsing
1658 // error". Try to convert to the former and if that doesn't work
1659 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001660 metrics::DownloadErrorCode tmp_error =
1661 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001662 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1663 result = metrics::CheckResult::kDownloadError;
1664 download_error_code = tmp_error;
1665 } else {
1666 result = metrics::CheckResult::kParsingError;
1667 }
1668 break;
1669 }
1670
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001671 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1672 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001673}
1674
Chris Sosa77f79e82014-06-02 18:16:24 -07001675bool OmahaRequestAction::ShouldIgnoreUpdate(
Tao Bao5688d162017-06-06 13:09:06 -07001676 const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001677 // Note: policy decision to not update to a version we rolled back from.
1678 string rollback_version =
1679 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001680 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001681 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001682 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001683 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1684 return true;
1685 }
1686 }
1687
Tao Bao5688d162017-06-06 13:09:06 -07001688 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001689 LOG(INFO) << "Update is not allowed over current connection.";
1690 return true;
1691 }
1692
1693 // Note: We could technically delete the UpdateFirstSeenAt state when we
1694 // return true. If we do, it'll mean a device has to restart the
1695 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1696 // turned on again. On the other hand, it also increases the chance of update
1697 // starvation if an admin turns AU on/off more frequently. We choose to err on
1698 // the side of preventing starvation at the cost of not applying scattering in
1699 // those cases.
1700 return false;
1701}
1702
Tao Bao5688d162017-06-06 13:09:06 -07001703bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001704 ConnectionType type;
1705 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001706 ConnectionManagerInterface* connection_manager =
1707 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001708 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001709 LOG(INFO) << "We could not determine our connection type. "
1710 << "Defaulting to allow updates.";
1711 return true;
1712 }
1713 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1714 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001715 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001716 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1717 return is_allowed;
1718}
1719
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001720} // namespace chromeos_update_engine