blob: c4db0c7b952b34f7872f0d687810ed372664677e [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>
Sen Jiang0affc2c2017-02-10 15:55:05 -080030#include <base/strings/string_split.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070031#include <base/strings/string_util.h>
32#include <base/strings/stringprintf.h>
33#include <base/time/time.h>
Sen Jiang684c9cd2017-10-17 16:26:45 -070034#include <brillo/key_value_store.h>
David Zeuthene8ed8632014-07-24 13:38:10 -040035#include <expat.h>
Alex Deymoa2591792015-11-17 00:39:40 -030036#include <metrics/metrics_library.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000037
Alex Deymo39910dc2015-11-09 17:04:30 -080038#include "update_engine/common/action_pipe.h"
39#include "update_engine/common/constants.h"
40#include "update_engine/common/hardware_interface.h"
41#include "update_engine/common/hash_calculator.h"
42#include "update_engine/common/platform_constants.h"
43#include "update_engine/common/prefs_interface.h"
44#include "update_engine/common/utils.h"
Sen Jiang255e22b2016-05-20 16:15:29 -070045#include "update_engine/connection_manager_interface.h"
Tianjie Xu282aa1f2017-09-05 13:42:45 -070046#include "update_engine/metrics_reporter_interface.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080047#include "update_engine/metrics_utils.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070048#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070049#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080050#include "update_engine/payload_state_interface.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000051
Darin Petkov1cbd78f2010-07-29 12:38:34 -070052using base::Time;
53using base::TimeDelta;
David Zeuthene8ed8632014-07-24 13:38:10 -040054using std::map;
rspangler@google.com49fdf182009-10-10 00:57:34 +000055using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040056using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000057
58namespace chromeos_update_engine {
59
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080060// List of custom pair tags that we interpret in the Omaha Response:
61static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080062static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070063static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080064// Deprecated: "IsDelta"
65static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080066static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
67static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
68// Deprecated: "ManifestSignatureRsa"
69// Deprecated: "ManifestSize"
70static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
71static const char* kTagMetadataSize = "MetadataSize";
72static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070073// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080074static const char* kTagPrompt = "Prompt";
David Zeuthen8f191b22013-08-06 12:27:50 -070075static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
76static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
David Zeuthene7f89172013-10-31 10:21:04 -070077static const char* kTagPublicKeyRsa = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080078
Alex Deymoac41a822015-09-15 20:52:53 -070079static const char* kOmahaUpdaterVersion = "0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +000080
Alex Deymo14ad88e2016-06-29 12:30:14 -070081// X-GoogleUpdate headers.
82static const char* kXGoogleUpdateInteractivity = "X-GoogleUpdate-Interactivity";
83static const char* kXGoogleUpdateAppId = "X-GoogleUpdate-AppId";
84static const char* kXGoogleUpdateUpdater = "X-GoogleUpdate-Updater";
85
Alex Deymob3fa53b2016-04-18 19:57:58 -070086// updatecheck attributes (without the underscore prefix).
87static const char* kEolAttr = "eol";
88
Alex Deymoac41a822015-09-15 20:52:53 -070089namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +000090
Darin Petkov1cbd78f2010-07-29 12:38:34 -070091// Returns an XML ping element attribute assignment with attribute
92// |name| and value |ping_days| if |ping_days| has a value that needs
93// to be sent, or an empty string otherwise.
94string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -070095 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -070096 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -070097 return "";
98}
99
100// Returns an XML ping element if any of the elapsed days need to be
101// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700102string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700103 string ping_active = GetPingAttribute("a", ping_active_days);
104 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
105 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700106 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700107 ping_active.c_str(),
108 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700109 }
110 return "";
111}
112
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700113// Returns an XML that goes into the body of the <app> element of the Omaha
114// request based on the given parameters.
115string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700116 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700117 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700118 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700119 int ping_active_days,
120 int ping_roll_call_days,
121 PrefsInterface* prefs) {
122 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700123 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700124 if (include_ping)
125 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700126 if (!ping_only) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700127 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700128 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700129 "></updatecheck>\n",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700130 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700131
Darin Petkov265f2902011-05-09 15:17:40 -0700132 // If this is the first update check after a reboot following a previous
133 // update, generate an event containing the previous version number. If
134 // the previous version preference file doesn't exist the event is still
135 // generated with a previous version of 0.0.0.0 -- this is relevant for
136 // older clients or new installs. The previous version event is not sent
137 // for ping-only requests because they come before the client has
Alex Deymo87c08862015-10-30 21:56:55 -0700138 // rebooted. The previous version event is also not sent if it was already
139 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700140 string prev_version;
141 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
142 prev_version = "0.0.0.0";
143 }
Alex Deymo87c08862015-10-30 21:56:55 -0700144 // We only store a non-empty previous version value after a successful
145 // update in the previous boot. After reporting it back to the server,
146 // we clear the previous version value so it doesn't get reported again.
147 if (!prev_version.empty()) {
148 app_body += base::StringPrintf(
149 " <event eventtype=\"%d\" eventresult=\"%d\" "
150 "previousversion=\"%s\"></event>\n",
Alex Deymo9fded1e2015-11-05 12:31:19 -0800151 OmahaEvent::kTypeRebootedAfterUpdate,
152 OmahaEvent::kResultSuccess,
Alex Deymo87c08862015-10-30 21:56:55 -0700153 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
154 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
155 << "Unable to reset the previous version.";
156 }
Darin Petkov95508da2011-01-05 12:42:29 -0800157 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700158 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800159 // The error code is an optional attribute so append it only if the result
160 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700161 string error_code;
162 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700163 error_code = base::StringPrintf(" errorcode=\"%d\"",
164 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700165 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700166 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700167 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700168 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700169 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700170
171 return app_body;
172}
173
Alex Deymo8e18f932015-03-27 16:16:59 -0700174// Returns the cohort* argument to include in the <app> tag for the passed
175// |arg_name| and |prefs_key|, if any. The return value is suitable to
176// concatenate to the list of arguments and includes a space at the end.
177string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700178 const string arg_name,
179 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700180 // There's nothing wrong with not having a given cohort setting, so we check
181 // existance first to avoid the warning log message.
182 if (!prefs->Exists(prefs_key))
183 return "";
184 string cohort_value;
185 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
186 return "";
187 // This is a sanity check to avoid sending a huge XML file back to Ohama due
188 // to a compromised stateful partition making the update check fail in low
189 // network environments envent after a reboot.
190 if (cohort_value.size() > 1024) {
191 LOG(WARNING) << "The omaha cohort setting " << arg_name
192 << " has a too big value, which must be an error or an "
193 "attacker trying to inhibit updates.";
194 return "";
195 }
196
Alex Deymob0d74eb2015-03-30 17:59:17 -0700197 string escaped_xml_value;
198 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
199 LOG(WARNING) << "The omaha cohort setting " << arg_name
200 << " is ASCII-7 invalid, ignoring it.";
201 return "";
202 }
203
Alex Deymo8e18f932015-03-27 16:16:59 -0700204 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700205 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700206}
207
Sen Jiang94a4dec2017-03-28 18:23:35 -0700208struct OmahaAppData {
209 string id;
210 string version;
Sen Jiang684c9cd2017-10-17 16:26:45 -0700211 string product_components;
Sen Jiang94a4dec2017-03-28 18:23:35 -0700212};
213
Sen Jiang684c9cd2017-10-17 16:26:45 -0700214bool IsValidComponentID(const string& id) {
215 for (char c : id) {
216 if (!isalnum(c) && c != '-' && c != '_' && c != '.')
217 return false;
218 }
219 return true;
220}
221
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700222// Returns an XML that corresponds to the entire <app> node of the Omaha
223// request based on the given parameters.
224string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700225 OmahaRequestParams* params,
Sen Jiang94a4dec2017-03-28 18:23:35 -0700226 const OmahaAppData& app_data,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700227 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700228 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700229 int ping_active_days,
230 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800231 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700232 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700233 string app_body = GetAppBody(event, params, ping_only, include_ping,
234 ping_active_days, ping_roll_call_days,
235 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700236 string app_versions;
237
238 // If we are upgrading to a more stable channel and we are allowed to do
239 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
240 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700241 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700242 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
243 << "on downgrading to the version in the more stable channel";
244 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700245 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700246 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700247 app_versions = "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 }
250
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700251 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700252 string app_channels =
253 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
254 if (params->current_channel() != download_channel) {
255 app_channels += "from_track=\"" + XmlEncodeWithDefault(
256 params->current_channel(), "") + "\" ";
257 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700258
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700259 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700260
David Zeuthen639aa362014-02-03 16:23:44 -0800261 // If install_date_days is not set (e.g. its value is -1 ), don't
262 // include the attribute.
263 string install_date_in_days_str = "";
264 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700265 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
266 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800267 }
268
Alex Deymo8e18f932015-03-27 16:16:59 -0700269 string app_cohort_args;
270 app_cohort_args += GetCohortArgXml(system_state->prefs(),
271 "cohort", kPrefsOmahaCohort);
272 app_cohort_args += GetCohortArgXml(system_state->prefs(),
273 "cohorthint", kPrefsOmahaCohortHint);
274 app_cohort_args += GetCohortArgXml(system_state->prefs(),
275 "cohortname", kPrefsOmahaCohortName);
276
Alex Deymoebf6e122017-03-10 16:12:01 -0800277 string fingerprint_arg;
278 if (!params->os_build_fingerprint().empty()) {
279 fingerprint_arg =
280 "fingerprint=\"" + XmlEncodeWithDefault(params->os_build_fingerprint(), "") + "\" ";
281 }
282
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700283 string buildtype_arg;
284 if (!params->os_build_type().empty()) {
285 buildtype_arg = "os_build_type=\"" +
286 XmlEncodeWithDefault(params->os_build_type(), "") + "\" ";
287 }
288
Sen Jiang684c9cd2017-10-17 16:26:45 -0700289 string product_components_args;
290 if (!app_data.product_components.empty()) {
291 brillo::KeyValueStore store;
292 if (store.LoadFromString(app_data.product_components)) {
293 for (const string& key : store.GetKeys()) {
294 if (!IsValidComponentID(key)) {
295 LOG(ERROR) << "Invalid component id: " << key;
296 continue;
297 }
298 string version;
299 if (!store.GetString(key, &version)) {
300 LOG(ERROR) << "Failed to get version for " << key
301 << " in product_components.";
302 continue;
303 }
304 product_components_args +=
305 base::StringPrintf("_%s.version=\"%s\" ",
306 key.c_str(),
307 XmlEncodeWithDefault(version, "").c_str());
308 }
309 } else {
310 LOG(ERROR) << "Failed to parse product_components:\n"
311 << app_data.product_components;
312 }
313 }
314
315 // clang-format off
Alex Deymob0d74eb2015-03-30 17:59:17 -0700316 string app_xml = " <app "
Sen Jiang94a4dec2017-03-28 18:23:35 -0700317 "appid=\"" + XmlEncodeWithDefault(app_data.id, "") + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700318 app_cohort_args +
319 app_versions +
320 app_channels +
Sen Jiang684c9cd2017-10-17 16:26:45 -0700321 product_components_args +
Alex Deymoebf6e122017-03-10 16:12:01 -0800322 fingerprint_arg +
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700323 buildtype_arg +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700324 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
325 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
326 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
327 "delta_okay=\"" + delta_okay_str + "\" "
328 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
329 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
330 install_date_in_days_str +
331 ">\n" +
332 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700333 " </app>\n";
Sen Jiang684c9cd2017-10-17 16:26:45 -0700334 // clang-format on
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700335 return app_xml;
336}
337
338// Returns an XML that corresponds to the entire <os> node of the Omaha
339// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700340string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700341 string os_xml =" <os "
342 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
343 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
344 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
345 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700346 return os_xml;
347}
348
349// Returns an XML that corresponds to the entire Omaha request based on the
350// given parameters.
351string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700352 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700353 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700354 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700355 int ping_active_days,
356 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800357 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700358 SystemState* system_state) {
359 string os_xml = GetOsXml(params);
Sen Jiang684c9cd2017-10-17 16:26:45 -0700360 OmahaAppData product_app = {
361 .id = params->GetAppId(),
362 .version = params->app_version(),
363 .product_components = params->product_components()};
Sen Jiang94a4dec2017-03-28 18:23:35 -0700364 string app_xml = GetAppXml(event,
365 params,
366 product_app,
367 ping_only,
368 include_ping,
369 ping_active_days,
370 ping_roll_call_days,
371 install_date_in_days,
372 system_state);
373 if (!params->system_app_id().empty()) {
374 OmahaAppData system_app = {.id = params->system_app_id(),
375 .version = params->system_version()};
376 app_xml += GetAppXml(event,
377 params,
378 system_app,
379 ping_only,
380 include_ping,
381 ping_active_days,
382 ping_roll_call_days,
383 install_date_in_days,
384 system_state);
385 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700386
Alex Vakulenko75039d72014-03-25 12:36:28 -0700387 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700388 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700389
Alex Deymoac41a822015-09-15 20:52:53 -0700390 string updater_version = XmlEncodeWithDefault(
391 base::StringPrintf("%s-%s",
392 constants::kOmahaUpdaterID,
393 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700394 string request_xml =
395 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700396 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700397 "version=\"" + updater_version + "\" "
398 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700399 install_source +
400 "ismachine=\"1\">\n") +
401 os_xml +
402 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700403 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700404
405 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000406}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700407
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700408} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000409
David Zeuthene8ed8632014-07-24 13:38:10 -0400410// Struct used for holding data obtained when parsing the XML.
411struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400412 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
413
414 // Pointer to the expat XML_Parser object.
415 XML_Parser xml_parser;
416
David Zeuthene8ed8632014-07-24 13:38:10 -0400417 // This is the state of the parser as it's processing the XML.
418 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400419 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400420 string current_path;
421
422 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400423 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700424 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400425 string daystart_elapsed_days;
426 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800427
Sen Jiang81259682017-03-30 15:11:30 -0700428 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700429 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700430 vector<string> url_codebase;
431 string manifest_version;
432 map<string, string> action_postinstall_attrs;
433 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700434 string cohort;
435 string cohorthint;
436 string cohortname;
437 bool cohort_set = false;
438 bool cohorthint_set = false;
439 bool cohortname_set = false;
Sen Jiang81259682017-03-30 15:11:30 -0700440
441 struct Package {
442 string name;
443 string size;
444 string hash;
445 };
446 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800447 };
Sen Jiang81259682017-03-30 15:11:30 -0700448 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400449};
450
451namespace {
452
453// Callback function invoked by expat.
454void ParserHandlerStart(void* user_data, const XML_Char* element,
455 const XML_Char** attr) {
456 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
457
458 if (data->failed)
459 return;
460
461 data->current_path += string("/") + element;
462
463 map<string, string> attrs;
464 if (attr != nullptr) {
465 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
466 string key = attr[n];
467 string value = attr[n + 1];
468 attrs[key] = value;
469 }
470 }
471
Alex Deymo8e18f932015-03-27 16:16:59 -0700472 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700473 OmahaParserData::App app;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700474 if (attrs.find("appid") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700475 app.id = attrs["appid"];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700476 }
Alex Deymo8e18f932015-03-27 16:16:59 -0700477 if (attrs.find("cohort") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700478 app.cohort_set = true;
479 app.cohort = attrs["cohort"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700480 }
481 if (attrs.find("cohorthint") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700482 app.cohorthint_set = true;
483 app.cohorthint = attrs["cohorthint"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700484 }
485 if (attrs.find("cohortname") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700486 app.cohortname_set = true;
487 app.cohortname = attrs["cohortname"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700488 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700489 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700490 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700491 if (!data->apps.empty())
492 data->apps.back().updatecheck_status = attrs["status"];
493 if (data->updatecheck_poll_interval.empty())
494 data->updatecheck_poll_interval = attrs["PollInterval"];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700495 // Omaha sends arbitrary key-value pairs as extra attributes starting with
496 // an underscore.
497 for (const auto& attr : attrs) {
498 if (!attr.first.empty() && attr.first[0] == '_')
499 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
500 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400501 } else if (data->current_path == "/response/daystart") {
502 // Get the install-date.
503 data->daystart_elapsed_days = attrs["elapsed_days"];
504 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
505 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
506 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700507 if (!data->apps.empty())
508 data->apps.back().url_codebase.push_back(attrs["codebase"]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800509 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400510 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800511 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700512 if (!data->apps.empty())
513 data->apps.back().packages.push_back({.name = attrs["name"],
514 .size = attrs["size"],
515 .hash = attrs["hash_sha256"]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400516 } else if (data->current_path == "/response/app/updatecheck/manifest") {
517 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700518 if (!data->apps.empty())
519 data->apps.back().manifest_version = attrs[kTagVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400520 } else if (data->current_path ==
521 "/response/app/updatecheck/manifest/actions/action") {
522 // We only care about the postinstall action.
Sen Jiang81259682017-03-30 15:11:30 -0700523 if (attrs["event"] == "postinstall" && !data->apps.empty()) {
524 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400525 }
526 }
527}
528
529// Callback function invoked by expat.
530void ParserHandlerEnd(void* user_data, const XML_Char* element) {
531 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
532 if (data->failed)
533 return;
534
535 const string path_suffix = string("/") + element;
536
Alex Vakulenko0103c362016-01-20 07:56:15 -0800537 if (!base::EndsWith(data->current_path, path_suffix,
538 base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400539 LOG(ERROR) << "Unexpected end element '" << element
540 << "' with current_path='" << data->current_path << "'";
541 data->failed = true;
542 return;
543 }
544 data->current_path.resize(data->current_path.size() - path_suffix.size());
545}
546
David Zeuthenf3e28012014-08-26 18:23:52 -0400547// Callback function invoked by expat.
548//
549// This is called for entity declarations. Since Omaha is guaranteed
550// to never return any XML with entities our course of action is to
551// just stop parsing. This avoids potential resource exhaustion
552// problems AKA the "billion laughs". CVE-2013-0340.
553void ParserHandlerEntityDecl(void *user_data,
554 const XML_Char *entity_name,
555 int is_parameter_entity,
556 const XML_Char *value,
557 int value_length,
558 const XML_Char *base,
559 const XML_Char *system_id,
560 const XML_Char *public_id,
561 const XML_Char *notation_name) {
562 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
563
564 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
565 data->failed = true;
566 data->entity_decl = true;
567 XML_StopParser(data->xml_parser, false);
568}
569
David Zeuthene8ed8632014-07-24 13:38:10 -0400570} // namespace
571
Alex Deymob0d74eb2015-03-30 17:59:17 -0700572bool XmlEncode(const string& input, string* output) {
573 if (std::find_if(input.begin(), input.end(),
574 [](const char c){return c & 0x80;}) != input.end()) {
575 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
576 utils::HexDumpString(input);
577 return false;
578 }
Alex Deymocc457852015-06-18 18:35:50 -0700579 output->clear();
580 // We need at least input.size() space in the output, but the code below will
581 // handle it if we need more.
582 output->reserve(input.size());
583 for (char c : input) {
584 switch (c) {
585 case '\"':
586 output->append("&quot;");
587 break;
588 case '\'':
589 output->append("&apos;");
590 break;
591 case '&':
592 output->append("&amp;");
593 break;
594 case '<':
595 output->append("&lt;");
596 break;
597 case '>':
598 output->append("&gt;");
599 break;
600 default:
601 output->push_back(c);
602 }
603 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700604 return true;
605}
606
607string XmlEncodeWithDefault(const string& input, const string& default_value) {
608 string output;
609 if (XmlEncode(input, &output))
610 return output;
611 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000612}
613
Alex Deymoc1c17b42015-11-23 03:53:15 -0300614OmahaRequestAction::OmahaRequestAction(
615 SystemState* system_state,
616 OmahaEvent* event,
617 std::unique_ptr<HttpFetcher> http_fetcher,
618 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800619 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700620 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300621 http_fetcher_(std::move(http_fetcher)),
Thieu Le116fda32011-04-19 11:01:54 -0700622 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700623 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700624 ping_roll_call_days_(0) {
625 params_ = system_state->request_params();
626}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000627
Darin Petkov6a5b3222010-07-13 14:55:28 -0700628OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000629
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700630// Calculates the value to use for the ping days parameter.
631int OmahaRequestAction::CalculatePingDays(const string& key) {
632 int days = kNeverPinged;
633 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800634 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700635 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
636 if (days < 0) {
637 // If |days| is negative, then the system clock must have jumped
638 // back in time since the ping was sent. Mark the value so that
639 // it doesn't get sent to the server but we still update the
640 // last ping daystart preference. This way the next ping time
641 // will be correct, hopefully.
642 days = kPingTimeJump;
643 LOG(WARNING) <<
644 "System clock jumped back in time. Resetting ping daystarts.";
645 }
646 }
647 return days;
648}
649
650void OmahaRequestAction::InitPingDays() {
651 // We send pings only along with update checks, not with events.
652 if (IsEvent()) {
653 return;
654 }
655 // TODO(petkov): Figure a way to distinguish active use pings
656 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700657 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700658 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
659 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
660}
661
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700662bool OmahaRequestAction::ShouldPing() const {
663 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
664 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
665 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
666 if (powerwash_count > 0) {
667 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
668 << "powerwash_count is " << powerwash_count;
669 return false;
670 }
Amin Hassani1677e812017-06-21 13:36:36 -0700671 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
672 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
673 << "the first_active_omaha_ping_sent is true";
674 return false;
675 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700676 return true;
677 }
678 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
679}
680
David Zeuthen639aa362014-02-03 16:23:44 -0800681// static
682int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
683 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700684 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800685 return -1;
686
687 // If we have the value stored on disk, just return it.
688 int64_t stored_value;
689 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
690 // Convert and sanity-check.
691 int install_date_days = static_cast<int>(stored_value);
692 if (install_date_days >= 0)
693 return install_date_days;
694 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
695 << install_date_days << " looks suspicious.";
696 prefs->Delete(kPrefsInstallDateDays);
697 }
698
699 // Otherwise, if OOBE is not complete then do nothing and wait for
700 // ParseResponse() to call ParseInstallDate() and then
701 // PersistInstallDate() to set the kPrefsInstallDateDays state
702 // variable. Once that is done, we'll then report back in future
703 // Omaha requests. This works exactly because OOBE triggers an
704 // update check.
705 //
706 // However, if OOBE is complete and the kPrefsInstallDateDays state
707 // variable is not set, there are two possibilities
708 //
709 // 1. The update check in OOBE failed so we never got a response
710 // from Omaha (no network etc.); or
711 //
712 // 2. OOBE was done on an older version that didn't write to the
713 // kPrefsInstallDateDays state variable.
714 //
715 // In both cases, we approximate the install date by simply
716 // inspecting the timestamp of when OOBE happened.
717
718 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700719 if (!system_state->hardware()->IsOOBEEnabled() ||
720 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800721 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700722 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800723 return -1;
724 }
725
726 int num_days;
727 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
728 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
729 << "as its value '" << utils::ToString(time_of_oobe)
730 << "' looks suspicious.";
731 return -1;
732 }
733
734 // Persist this to disk, for future use.
735 if (!OmahaRequestAction::PersistInstallDate(system_state,
736 num_days,
737 kProvisionedFromOOBEMarker))
738 return -1;
739
740 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
741 << num_days << " days";
742
743 return num_days;
744}
745
Darin Petkov6a5b3222010-07-13 14:55:28 -0700746void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000747 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700748 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700749 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700750 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700751 return;
752 }
David Zeuthen639aa362014-02-03 16:23:44 -0800753
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700754 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700755 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700756 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700757 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700758 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800759 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800760 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700761 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700762
Alex Deymo14ad88e2016-06-29 12:30:14 -0700763 // Set X-GoogleUpdate headers.
764 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
765 params_->interactive() ? "fg" : "bg");
766 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
767 http_fetcher_->SetHeader(
768 kXGoogleUpdateUpdater,
769 base::StringPrintf(
770 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
771
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800772 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
773 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700774 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700775 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700776 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000777}
778
Darin Petkov6a5b3222010-07-13 14:55:28 -0700779void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000780 http_fetcher_->TerminateTransfer();
781}
782
783// We just store the response in the buffer. Once we've received all bytes,
784// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700785void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800786 const void* bytes,
787 size_t length) {
788 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
789 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000790}
791
792namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000793
794// Parses a 64 bit base-10 int from a string and returns it. Returns 0
795// on error. If the string contains "0", that's indistinguishable from
796// error.
797off_t ParseInt(const string& str) {
798 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700799 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000800 if (rc < 1) {
801 // failure
802 return 0;
803 }
804 return ret;
805}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700806
David Zeuthene8ed8632014-07-24 13:38:10 -0400807// Parses |str| and returns |true| if, and only if, its value is "true".
808bool ParseBool(const string& str) {
809 return str == "true";
810}
811
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700812// Update the last ping day preferences based on the server daystart
813// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400814bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700815 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400816 TEST_AND_RETURN_FALSE(
817 base::StringToInt64(parser_data->daystart_elapsed_seconds,
818 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700819 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
820
821 // Remember the local time that matches the server's last midnight
822 // time.
823 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
824 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
825 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
826 return true;
827}
Sen Jiang81259682017-03-30 15:11:30 -0700828
829// Parses the package node in the given XML document and populates
830// |output_object| if valid. Returns true if we should continue the parsing.
831// False otherwise, in which case it sets any error code using |completer|.
832bool ParsePackage(OmahaParserData::App* app,
833 OmahaResponse* output_object,
834 ScopedActionCompleter* completer) {
835 if (app->updatecheck_status == "noupdate") {
836 if (!app->packages.empty()) {
837 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
838 completer->set_code(ErrorCode::kOmahaResponseInvalid);
839 return false;
840 }
841 return true;
842 }
843 if (app->packages.empty()) {
844 LOG(ERROR) << "Omaha Response has no packages";
845 completer->set_code(ErrorCode::kOmahaResponseInvalid);
846 return false;
847 }
848 if (app->url_codebase.empty()) {
849 LOG(ERROR) << "No Omaha Response URLs";
850 completer->set_code(ErrorCode::kOmahaResponseInvalid);
851 return false;
852 }
853 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
854 vector<string> metadata_sizes =
855 base::SplitString(app->action_postinstall_attrs[kTagMetadataSize],
856 ":",
857 base::TRIM_WHITESPACE,
858 base::SPLIT_WANT_ALL);
859 vector<string> metadata_signatures =
860 base::SplitString(app->action_postinstall_attrs[kTagMetadataSignatureRsa],
861 ":",
862 base::TRIM_WHITESPACE,
863 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700864 vector<string> is_delta_payloads =
865 base::SplitString(app->action_postinstall_attrs[kTagIsDeltaPayload],
866 ":",
867 base::TRIM_WHITESPACE,
868 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700869 for (size_t i = 0; i < app->packages.size(); i++) {
870 const auto& package = app->packages[i];
871 if (package.name.empty()) {
872 LOG(ERROR) << "Omaha Response has empty package name";
873 completer->set_code(ErrorCode::kOmahaResponseInvalid);
874 return false;
875 }
876 LOG(INFO) << "Found package " << package.name;
877
878 OmahaResponse::Package out_package;
879 for (const string& codebase : app->url_codebase) {
880 if (codebase.empty()) {
881 LOG(ERROR) << "Omaha Response URL has empty codebase";
882 completer->set_code(ErrorCode::kOmahaResponseInvalid);
883 return false;
884 }
885 out_package.payload_urls.push_back(codebase + package.name);
886 }
887 // Parse the payload size.
888 base::StringToUint64(package.size, &out_package.size);
889 if (out_package.size <= 0) {
890 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
891 completer->set_code(ErrorCode::kOmahaResponseInvalid);
892 return false;
893 }
894 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
895
896 if (i < metadata_sizes.size())
897 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
898 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
899 << " bytes";
900
901 if (i < metadata_signatures.size())
902 out_package.metadata_signature = metadata_signatures[i];
903 LOG(INFO) << "Payload metadata signature = "
904 << out_package.metadata_signature;
905
906 out_package.hash = package.hash;
907 if (out_package.hash.empty()) {
908 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
909 completer->set_code(ErrorCode::kOmahaResponseInvalid);
910 return false;
911 }
912 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700913
914 if (i < is_delta_payloads.size())
915 out_package.is_delta = ParseBool(is_delta_payloads[i]);
916 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
917
Sen Jiang81259682017-03-30 15:11:30 -0700918 output_object->packages.push_back(std::move(out_package));
919 }
920
921 return true;
922}
923
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700924} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000925
David Zeuthene8ed8632014-07-24 13:38:10 -0400926bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700927 OmahaResponse* output_object,
928 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700929 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700930 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700931 return false;
932 }
Sen Jiang81259682017-03-30 15:11:30 -0700933 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700934
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800935 // chromium-os:37289: The PollInterval is not supported by Omaha server
936 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700937 // slow down the request rate from the server-side. Note that the PollInterval
938 // is not persisted, so it has to be sent by the server on every response to
939 // guarantee that the scheduler uses this value (otherwise, if the device got
940 // rebooted after the last server-indicated value, it'll revert to the default
941 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
942 // based on the assumption that we perform an update check every hour so that
943 // the max value of 8 will roughly be equivalent to one work day. If we decide
944 // to use PollInterval permanently, we should update the
945 // max_update_checks_allowed to take PollInterval into account. Note: The
946 // parsing for PollInterval happens even before parsing of the status because
947 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400948 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700949 &output_object->poll_interval);
950
David Zeuthen639aa362014-02-03 16:23:44 -0800951 // Check for the "elapsed_days" attribute in the "daystart"
952 // element. This is the number of days since Jan 1 2007, 0:00
953 // PST. If we don't have a persisted value of the Omaha InstallDate,
954 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400955 if (ParseInstallDate(parser_data, output_object) &&
956 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800957 // Since output_object->install_date_days is never negative, the
958 // elapsed_days -> install-date calculation is reduced to simply
959 // rounding down to the nearest number divisible by 7.
960 int remainder = output_object->install_date_days % 7;
961 int install_date_days_rounded =
962 output_object->install_date_days - remainder;
963 if (PersistInstallDate(system_state_,
964 install_date_days_rounded,
965 kProvisionedFromOmahaResponse)) {
966 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
967 << install_date_days_rounded << " days";
968 }
969 }
970
Alex Deymo00d79ac2015-06-29 15:41:49 -0700971 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -0700972 for (const auto& app : parser_data->apps) {
973 if (app.id == params_->GetAppId()) {
974 if (app.cohort_set)
975 PersistCohortData(kPrefsOmahaCohort, app.cohort);
976 if (app.cohorthint_set)
977 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
978 if (app.cohortname_set)
979 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
980 break;
981 }
982 }
Alex Deymo00d79ac2015-06-29 15:41:49 -0700983
Alex Deymob3fa53b2016-04-18 19:57:58 -0700984 // Parse the updatecheck attributes.
985 PersistEolStatus(parser_data->updatecheck_attrs);
986
David Zeuthene8ed8632014-07-24 13:38:10 -0400987 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700988 return false;
989
David Zeuthene8ed8632014-07-24 13:38:10 -0400990 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700991 return false;
992
Sen Jiang0affc2c2017-02-10 15:55:05 -0800993 // Package has to be parsed after Params now because ParseParams need to make
994 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -0700995 for (auto& app : parser_data->apps)
996 if (!ParsePackage(&app, output_object, completer))
997 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800998
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700999 return true;
1000}
1001
David Zeuthene8ed8632014-07-24 13:38:10 -04001002bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001003 OmahaResponse* output_object,
1004 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001005 output_object->update_exists = false;
1006 for (size_t i = 0; i < parser_data->apps.size(); i++) {
1007 const string& status = parser_data->apps[i].updatecheck_status;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001008 if (status == "noupdate") {
1009 // Don't update if any app has status="noupdate".
Sen Jiang81259682017-03-30 15:11:30 -07001010 LOG(INFO) << "No update for <app> " << i;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001011 output_object->update_exists = false;
1012 break;
Sen Jiang81259682017-03-30 15:11:30 -07001013 } else if (status == "ok") {
Sen Jiang00adf7b2017-06-26 15:57:29 -07001014 if (parser_data->apps[i].action_postinstall_attrs["noupdate"] == "true") {
1015 // noupdate="true" in postinstall attributes means it's an update to
1016 // self, only update if there's at least one app really have update.
1017 LOG(INFO) << "Update to self for <app> " << i;
1018 } else {
1019 LOG(INFO) << "Update for <app> " << i;
1020 output_object->update_exists = true;
1021 }
Sen Jiang81259682017-03-30 15:11:30 -07001022 } else {
1023 LOG(ERROR) << "Unknown Omaha response status: " << status;
1024 completer->set_code(ErrorCode::kOmahaResponseInvalid);
1025 return false;
1026 }
1027 }
1028 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001029 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001030 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001031 }
1032
Sen Jiang81259682017-03-30 15:11:30 -07001033 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001034}
1035
David Zeuthene8ed8632014-07-24 13:38:10 -04001036bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001037 OmahaResponse* output_object,
1038 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001039 map<string, string> attrs;
1040 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001041 if (app.id == params_->GetAppId()) {
1042 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -07001043 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001044 } else if (!params_->system_app_id().empty() &&
1045 app.id == params_->system_app_id()) {
1046 // this is the system app (this check is intentionally skipped if there is
1047 // no system_app_id set)
1048 output_object->system_version = app.manifest_version;
1049 }
1050 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -07001051 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001052 }
Sen Jiang81259682017-03-30 15:11:30 -07001053 }
Chris Sosa3b748432013-06-20 16:42:59 -07001054 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -07001055 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001056 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -07001057 return false;
1058 }
1059
1060 LOG(INFO) << "Received omaha response to update to version "
1061 << output_object->version;
1062
David Zeuthene8ed8632014-07-24 13:38:10 -04001063 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001064 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001065 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001066 return false;
1067 }
1068
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001069 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -04001070 output_object->more_info_url = attrs[kTagMoreInfo];
David Zeuthene8ed8632014-07-24 13:38:10 -04001071 output_object->prompt = ParseBool(attrs[kTagPrompt]);
1072 output_object->deadline = attrs[kTagDeadline];
1073 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001074 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -04001075 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001076 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -04001077 ParseBool(attrs[kTagDisableP2PForSharing]);
1078 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001079
David Zeuthene8ed8632014-07-24 13:38:10 -04001080 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -08001081 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001082 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001083
Jay Srinivasan08262882012-12-28 19:29:43 -08001084 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -04001085 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -08001086
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001087 return true;
1088}
1089
David Zeuthene8ed8632014-07-24 13:38:10 -04001090// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +00001091// and fill in the appropriate fields of the output object. Also, notifies
1092// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -07001093void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
1094 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +00001095 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001096 string current_response(response_buffer_.begin(), response_buffer_.end());
1097 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001098
Gilad Arnold74b5f552014-10-07 08:17:16 -07001099 PayloadStateInterface* const payload_state = system_state_->payload_state();
1100
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001101 // Events are best effort transactions -- assume they always succeed.
1102 if (IsEvent()) {
1103 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001104 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001105 return;
1106 }
1107
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001108 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001109 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -07001110 int code = GetHTTPResponseCode();
1111 // Makes sure we send sane error values.
1112 if (code < 0 || code >= 1000) {
1113 code = 999;
1114 }
David Zeuthena99981f2013-04-29 13:42:47 -07001115 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001116 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +00001117 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001118 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001119
David Zeuthene8ed8632014-07-24 13:38:10 -04001120 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -04001121 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -04001122 XML_SetUserData(parser, &parser_data);
1123 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -04001124 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001125 XML_Status res = XML_Parse(
1126 parser,
1127 reinterpret_cast<const char*>(response_buffer_.data()),
1128 response_buffer_.size(),
1129 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -04001130 XML_ParserFree(parser);
1131
1132 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -07001133 LOG(ERROR) << "Omaha response not valid XML: "
1134 << XML_ErrorString(XML_GetErrorCode(parser))
1135 << " at line " << XML_GetCurrentLineNumber(parser)
1136 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -04001137 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
1138 if (response_buffer_.empty()) {
1139 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
1140 } else if (parser_data.entity_decl) {
1141 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
1142 }
1143 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001144 return;
1145 }
1146
Alex Deymoebbe7ef2014-10-30 13:02:49 -07001147 // Update the last ping day preferences based on the server daystart response
1148 // even if we didn't send a ping. Omaha always includes the daystart in the
1149 // response, but log the error if it didn't.
1150 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
1151 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -07001152
Amin Hassani1677e812017-06-21 13:36:36 -07001153 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
1154 // we have got a response from omaha and if its value has never been set to
1155 // true before. Failure of this function should be ignored. There should be no
1156 // need to check if a=-1 has been sent because older devices have already sent
1157 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
1158 // future checks.
1159 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
1160 system_state_->hardware()->SetFirstActiveOmahaPingSent();
1161 }
1162
Thieu Le116fda32011-04-19 11:01:54 -07001163 if (!HasOutputPipe()) {
1164 // Just set success to whether or not the http transfer succeeded,
1165 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001166 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001167 return;
1168 }
1169
Darin Petkov6a5b3222010-07-13 14:55:28 -07001170 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001171 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001172 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001173 output_object.update_exists = true;
1174 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001175
Tao Bao5688d162017-06-06 13:09:06 -07001176 if (ShouldIgnoreUpdate(output_object)) {
1177 output_object.update_exists = false;
1178 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001179 return;
1180 }
1181
David Zeuthen8f191b22013-08-06 12:27:50 -07001182 // If Omaha says to disable p2p, respect that
1183 if (output_object.disable_p2p_for_downloading) {
1184 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1185 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001186 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001187 }
1188 if (output_object.disable_p2p_for_sharing) {
1189 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1190 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001191 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001192 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001193
1194 // Update the payload state with the current response. The payload state
1195 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001196 // from what's stored already. We are updating the payload state as late
1197 // as possible in this method so that if a new release gets pushed and then
1198 // got pulled back due to some issues, we don't want to clear our internal
1199 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001200 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001201
David Zeuthen8f191b22013-08-06 12:27:50 -07001202 // It could be we've already exceeded the deadline for when p2p is
1203 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001204 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001205 payload_state->P2PNewAttempt();
1206 if (!payload_state->P2PAttemptAllowed()) {
1207 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1208 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001209 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001210 }
1211 }
1212
1213 // From here on, we'll complete stuff in CompleteProcessing() so
1214 // disable |completer| since we'll create a new one in that
1215 // function.
1216 completer.set_should_complete(false);
1217
1218 // If we're allowed to use p2p for downloading we do not pay
1219 // attention to wall-clock-based waiting if the URL is indeed
1220 // available via p2p. Therefore, check if the file is available via
1221 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001222 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001223 LookupPayloadViaP2P(output_object);
1224 } else {
1225 CompleteProcessing();
1226 }
1227}
1228
1229void OmahaRequestAction::CompleteProcessing() {
1230 ScopedActionCompleter completer(processor_, this);
1231 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1232 PayloadStateInterface* payload_state = system_state_->payload_state();
1233
Alex Deymo46a9aae2016-05-04 20:20:11 -07001234 if (system_state_->hardware()->IsOOBEEnabled() &&
1235 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
Kevin Cernekeec5081a82016-04-08 12:29:52 -07001236 output_object.deadline.empty() &&
1237 params_->app_version() != "ForcedUpdate") {
Kevin Cernekee2494e282016-03-29 18:03:53 -07001238 output_object.update_exists = false;
1239 LOG(INFO) << "Ignoring non-critical Omaha updates until OOBE is done.";
1240 completer.set_code(ErrorCode::kNonCriticalUpdateInOOBE);
1241 return;
1242 }
1243
David Zeuthen8f191b22013-08-06 12:27:50 -07001244 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001245 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001246 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001247 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001248 return;
1249 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001250
Chris Sosa20f005c2013-09-05 13:53:08 -07001251 if (payload_state->ShouldBackoffDownload()) {
1252 output_object.update_exists = false;
1253 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1254 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001255 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001256 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001257 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001258 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001259}
1260
1261void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1262 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1263 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001264 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001265 } else {
1266 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1267 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001268 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001269 }
1270 CompleteProcessing();
1271}
1272
1273void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001274 // If the device is in the middle of an update, the state variables
1275 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1276 // tracks the offset and length of the operation currently in
1277 // progress. The offset is based from the end of the manifest which
1278 // is kPrefsManifestMetadataSize bytes long.
1279 //
1280 // To make forward progress and avoid deadlocks, we need to find a
1281 // peer that has at least the entire operation we're currently
1282 // working on. Otherwise we may end up in a situation where two
1283 // devices bounce back and forth downloading from each other,
1284 // neither making any forward progress until one of them decides to
1285 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1286 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001287 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001288 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001289 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001290 int64_t next_data_offset = 0;
1291 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001292 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001293 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1294 &manifest_metadata_size) &&
1295 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001296 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1297 &manifest_signature_size) &&
1298 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001299 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001300 &next_data_offset) &&
1301 next_data_offset != -1 &&
1302 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1303 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001304 minimum_size = manifest_metadata_size + manifest_signature_size +
1305 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001306 }
1307
Sen Jiang0affc2c2017-02-10 15:55:05 -08001308 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001309 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001310 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001311 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001312 string file_id =
1313 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001314 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001315 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1316 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001317 system_state_->p2p_manager()->LookupUrlForFile(
1318 file_id,
1319 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001320 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001321 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1322 base::Unretained(this)));
1323 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001324}
1325
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001326bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001327 if (params_->interactive()) {
1328 LOG(INFO) << "Not deferring download because update is interactive.";
1329 return false;
1330 }
1331
David Zeuthen8f191b22013-08-06 12:27:50 -07001332 // If we're using p2p to download _and_ we have a p2p URL, we never
1333 // defer the download. This is because the download will always
1334 // happen from a peer on the LAN and we've been waiting in line for
1335 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001336 const PayloadStateInterface* payload_state = system_state_->payload_state();
1337 if (payload_state->GetUsingP2PForDownloading() &&
1338 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001339 LOG(INFO) << "Download not deferred because download "
1340 << "will happen from a local peer (via p2p).";
1341 return false;
1342 }
1343
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001344 // We should defer the downloads only if we've first satisfied the
1345 // wall-clock-based-waiting period and then the update-check-based waiting
1346 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001347 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001348 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1349 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001350 return false;
1351 }
1352
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001353 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001354 case kWallClockWaitNotSatisfied:
1355 // We haven't even satisfied the first condition, passing the
1356 // wall-clock-based waiting period, so we should defer the downloads
1357 // until that happens.
1358 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1359 return true;
1360
1361 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1362 LOG(INFO) << "wall-clock-based-wait satisfied and "
1363 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001364 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001365
1366 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1367 // Wall-clock-based waiting period is satisfied, and it's determined
1368 // that we do not need the update-check-based wait. so no need to
1369 // defer downloads.
1370 LOG(INFO) << "wall-clock-based-wait satisfied and "
1371 << "update-check-based-wait is not required.";
1372 return false;
1373
1374 default:
1375 // Returning false for this default case so we err on the
1376 // side of downloading updates than deferring in case of any bugs.
1377 NOTREACHED();
1378 return false;
1379 }
1380}
1381
1382OmahaRequestAction::WallClockWaitResult
1383OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001384 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001385 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001386 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001387
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001388 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1389 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1390 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001391 // Note: This timestamp could be that of ANY update we saw in the past
1392 // (not necessarily this particular update we're considering to apply)
1393 // but never got to apply because of some reason (e.g. stop AU policy,
1394 // updates being pulled out from Omaha, changes in target version prefix,
1395 // new update being rolled out, etc.). But for the purposes of scattering
1396 // it doesn't matter which update the timestamp corresponds to. i.e.
1397 // the clock starts ticking the first time we see an update and we're
1398 // ready to apply when the random wait period is satisfied relative to
1399 // that first seen timestamp.
1400 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1401 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1402 << utils::ToString(update_first_seen_at);
1403 } else {
1404 // This seems like an unexpected error where the persisted value exists
1405 // but it's not readable for some reason. Just skip scattering in this
1406 // case to be safe.
1407 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1408 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1409 }
1410 } else {
Sen Jiang7c1171e2016-06-23 11:35:40 -07001411 update_first_seen_at = system_state_->clock()->GetWallclockTime();
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001412 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001413 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1414 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001415 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1416 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001417 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001418 // This seems like an unexpected error where the value cannot be
1419 // persisted for some reason. Just skip scattering in this
1420 // case to be safe.
1421 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1422 << utils::ToString(update_first_seen_at)
1423 << " cannot be persisted";
1424 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1425 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001426 }
1427
Sen Jiang7c1171e2016-06-23 11:35:40 -07001428 TimeDelta elapsed_time =
1429 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1430 TimeDelta max_scatter_period =
1431 TimeDelta::FromDays(output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001432
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001433 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001434 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001435 << ", Time Elapsed = "
1436 << utils::FormatSecs(elapsed_time.InSeconds())
1437 << ", MaxDaysToScatter = "
1438 << max_scatter_period.InDays();
1439
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001440 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001441 // The deadline is set for all rules which serve a delta update from a
1442 // previous FSI, which means this update will be applied mostly in OOBE
1443 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1444 // quickly.
1445 LOG(INFO) << "Not scattering as deadline flag is set";
1446 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1447 }
1448
1449 if (max_scatter_period.InDays() == 0) {
1450 // This means the Omaha rule creator decides that this rule
1451 // should not be scattered irrespective of the policy.
1452 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1453 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1454 }
1455
1456 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001457 // This means we've waited more than the upperbound wait in the rule
1458 // from the time we first saw a valid update available to us.
1459 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001460 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1461 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1462 }
1463
1464 // This means we are required to participate in scattering.
1465 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001466 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001467 if (remaining_wait_time.InSeconds() <= 0) {
1468 // Yes, it's our turn now.
1469 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1470
1471 // But we can't download until the update-check-count-based wait is also
1472 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001473 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001474 kWallClockWaitDoneButUpdateCheckWaitRequired :
1475 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1476 }
1477
1478 // Not our turn yet, so we have to wait until our turn to
1479 // help scatter the downloads across all clients of the enterprise.
1480 LOG(INFO) << "Update deferred for another "
1481 << utils::FormatSecs(remaining_wait_time.InSeconds())
1482 << " per policy.";
1483 return kWallClockWaitNotSatisfied;
1484}
1485
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001486bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001487 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001488
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001489 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1490 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1491 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001492 // We are unable to read the update check count from file for some reason.
1493 // So let's proceed anyway so as to not stall the update.
1494 LOG(ERROR) << "Unable to read update check count. "
1495 << "Skipping update-check-count-based-wait.";
1496 return true;
1497 }
1498 } else {
1499 // This file does not exist. This means we haven't started our update
1500 // check count down yet, so this is the right time to start the count down.
1501 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001502 params_->min_update_checks_needed(),
1503 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001504
1505 LOG(INFO) << "Randomly picked update check count value = "
1506 << update_check_count_value;
1507
1508 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001509 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1510 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001511 // We weren't able to write the update check count file for some reason.
1512 // So let's proceed anyway so as to not stall the update.
1513 LOG(ERROR) << "Unable to write update check count. "
1514 << "Skipping update-check-count-based-wait.";
1515 return true;
1516 }
1517 }
1518
1519 if (update_check_count_value == 0) {
1520 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1521 return true;
1522 }
1523
1524 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001525 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001526 // We err on the side of skipping scattering logic instead of stalling
1527 // a machine from receiving any updates in case of any unexpected state.
1528 LOG(ERROR) << "Invalid value for update check count detected. "
1529 << "Skipping update-check-count-based-wait.";
1530 return true;
1531 }
1532
1533 // Legal value, we need to wait for more update checks to happen
1534 // until this becomes 0.
1535 LOG(INFO) << "Deferring Omaha updates for another "
1536 << update_check_count_value
1537 << " update checks per policy";
1538 return false;
1539}
1540
David Zeuthen639aa362014-02-03 16:23:44 -08001541// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001542bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001543 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001544 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001545 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001546 &elapsed_days))
1547 return false;
1548
1549 if (elapsed_days < 0)
1550 return false;
1551
1552 output_object->install_date_days = elapsed_days;
1553 return true;
1554}
1555
1556// static
1557bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1558 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001559 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001560 return false;
1561
1562 return prefs->Exists(kPrefsInstallDateDays);
1563}
1564
1565// static
1566bool OmahaRequestAction::PersistInstallDate(
1567 SystemState *system_state,
1568 int install_date_days,
1569 InstallDateProvisioningSource source) {
1570 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1571
1572 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001573 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001574 return false;
1575
1576 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1577 return false;
1578
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001579 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001580 static_cast<int>(source), // Sample.
1581 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001582 return true;
1583}
1584
Alex Deymo8e18f932015-03-27 16:16:59 -07001585bool OmahaRequestAction::PersistCohortData(
1586 const string& prefs_key,
1587 const string& new_value) {
1588 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1589 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1590 return system_state_->prefs()->Delete(prefs_key);
1591 } else if (!new_value.empty()) {
1592 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1593 return system_state_->prefs()->SetString(prefs_key, new_value);
1594 }
1595 return true;
1596}
1597
Alex Deymob3fa53b2016-04-18 19:57:58 -07001598bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
1599 auto eol_attr = attrs.find(kEolAttr);
1600 if (eol_attr != attrs.end()) {
1601 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1602 eol_attr->second);
1603 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1604 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1605 }
1606 return true;
1607}
1608
David Zeuthen33bae492014-02-25 16:16:18 -08001609void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1610 // We only want to report this on "update check".
1611 if (ping_only_ || event_ != nullptr)
1612 return;
1613
1614 metrics::CheckResult result = metrics::CheckResult::kUnset;
1615 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1616 metrics::DownloadErrorCode download_error_code =
1617 metrics::DownloadErrorCode::kUnset;
1618
1619 // Regular update attempt.
1620 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001621 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001622 // OK, we parsed the response successfully but that does
1623 // necessarily mean that an update is available.
1624 if (HasOutputPipe()) {
1625 const OmahaResponse& response = GetOutputObject();
1626 if (response.update_exists) {
1627 result = metrics::CheckResult::kUpdateAvailable;
1628 reaction = metrics::CheckReaction::kUpdating;
1629 } else {
1630 result = metrics::CheckResult::kNoUpdateAvailable;
1631 }
1632 } else {
1633 result = metrics::CheckResult::kNoUpdateAvailable;
1634 }
1635 break;
1636
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001637 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001638 result = metrics::CheckResult::kUpdateAvailable;
1639 reaction = metrics::CheckReaction::kIgnored;
1640 break;
1641
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001642 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001643 result = metrics::CheckResult::kUpdateAvailable;
1644 reaction = metrics::CheckReaction::kDeferring;
1645 break;
1646
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001647 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001648 result = metrics::CheckResult::kUpdateAvailable;
1649 reaction = metrics::CheckReaction::kBackingOff;
1650 break;
1651
1652 default:
1653 // We report two flavors of errors, "Download errors" and "Parsing
1654 // error". Try to convert to the former and if that doesn't work
1655 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001656 metrics::DownloadErrorCode tmp_error =
1657 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001658 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1659 result = metrics::CheckResult::kDownloadError;
1660 download_error_code = tmp_error;
1661 } else {
1662 result = metrics::CheckResult::kParsingError;
1663 }
1664 break;
1665 }
1666
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001667 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1668 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001669}
1670
Chris Sosa77f79e82014-06-02 18:16:24 -07001671bool OmahaRequestAction::ShouldIgnoreUpdate(
Tao Bao5688d162017-06-06 13:09:06 -07001672 const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001673 // Note: policy decision to not update to a version we rolled back from.
1674 string rollback_version =
1675 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001676 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001677 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001678 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001679 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1680 return true;
1681 }
1682 }
1683
Tao Bao5688d162017-06-06 13:09:06 -07001684 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001685 LOG(INFO) << "Update is not allowed over current connection.";
1686 return true;
1687 }
1688
1689 // Note: We could technically delete the UpdateFirstSeenAt state when we
1690 // return true. If we do, it'll mean a device has to restart the
1691 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1692 // turned on again. On the other hand, it also increases the chance of update
1693 // starvation if an admin turns AU on/off more frequently. We choose to err on
1694 // the side of preventing starvation at the cost of not applying scattering in
1695 // those cases.
1696 return false;
1697}
1698
Tao Bao5688d162017-06-06 13:09:06 -07001699bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001700 ConnectionType type;
1701 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001702 ConnectionManagerInterface* connection_manager =
1703 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001704 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001705 LOG(INFO) << "We could not determine our connection type. "
1706 << "Defaulting to allow updates.";
1707 return true;
1708 }
1709 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1710 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001711 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001712 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1713 return is_allowed;
1714}
1715
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001716} // namespace chromeos_update_engine