blob: ca6e34856111667bd67b496c191f3f52eb5e75ec [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>
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -080038#include <policy/libpolicy.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000039
Alex Deymo39910dc2015-11-09 17:04:30 -080040#include "update_engine/common/action_pipe.h"
41#include "update_engine/common/constants.h"
42#include "update_engine/common/hardware_interface.h"
43#include "update_engine/common/hash_calculator.h"
44#include "update_engine/common/platform_constants.h"
45#include "update_engine/common/prefs_interface.h"
46#include "update_engine/common/utils.h"
Sen Jiang255e22b2016-05-20 16:15:29 -070047#include "update_engine/connection_manager_interface.h"
Tianjie Xu282aa1f2017-09-05 13:42:45 -070048#include "update_engine/metrics_reporter_interface.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080049#include "update_engine/metrics_utils.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070050#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070051#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080052#include "update_engine/payload_state_interface.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000053
Darin Petkov1cbd78f2010-07-29 12:38:34 -070054using base::Time;
55using base::TimeDelta;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -080056using chromeos_update_manager::kRollforwardInfinity;
David Zeuthene8ed8632014-07-24 13:38:10 -040057using std::map;
rspangler@google.com49fdf182009-10-10 00:57:34 +000058using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040059using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000060
61namespace chromeos_update_engine {
62
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080063// List of custom pair tags that we interpret in the Omaha Response:
64static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080065static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070066static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080067// Deprecated: "IsDelta"
68static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080069static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
70static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
71// Deprecated: "ManifestSignatureRsa"
72// Deprecated: "ManifestSize"
73static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
74static const char* kTagMetadataSize = "MetadataSize";
75static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070076// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080077static const char* kTagPrompt = "Prompt";
David Zeuthen8f191b22013-08-06 12:27:50 -070078static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
79static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
David Zeuthene7f89172013-10-31 10:21:04 -070080static const char* kTagPublicKeyRsa = "PublicKeyRsa";
Sen Jiangfe284402018-03-21 14:03:50 -070081static const char* kTagPowerwash = "Powerwash";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080082
Alex Deymoac41a822015-09-15 20:52:53 -070083static const char* kOmahaUpdaterVersion = "0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +000084
Sen Jiang42fa45e2018-03-12 11:02:14 -070085// X-Goog-Update headers.
86static const char* kXGoogleUpdateInteractivity = "X-Goog-Update-Interactivity";
87static const char* kXGoogleUpdateAppId = "X-Goog-Update-AppId";
88static const char* kXGoogleUpdateUpdater = "X-Goog-Update-Updater";
Alex Deymo14ad88e2016-06-29 12:30:14 -070089
Alex Deymob3fa53b2016-04-18 19:57:58 -070090// updatecheck attributes (without the underscore prefix).
91static const char* kEolAttr = "eol";
Marton Hunyady199152d2018-05-07 19:08:48 +020092static const char* kRollback = "rollback";
93static const char* kFirmwareVersion = "firmware_version";
94static const char* kKernelVersion = "kernel_version";
Alex Deymob3fa53b2016-04-18 19:57:58 -070095
Alex Deymoac41a822015-09-15 20:52:53 -070096namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +000097
Darin Petkov1cbd78f2010-07-29 12:38:34 -070098// Returns an XML ping element attribute assignment with attribute
99// |name| and value |ping_days| if |ping_days| has a value that needs
100// to be sent, or an empty string otherwise.
101string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700102 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700103 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700104 return "";
105}
106
107// Returns an XML ping element if any of the elapsed days need to be
108// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700109string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700110 string ping_active = GetPingAttribute("a", ping_active_days);
111 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
112 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700113 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700114 ping_active.c_str(),
115 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700116 }
117 return "";
118}
119
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700120// Returns an XML that goes into the body of the <app> element of the Omaha
121// request based on the given parameters.
122string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700123 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700124 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700125 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700126 int ping_active_days,
127 int ping_roll_call_days,
128 PrefsInterface* prefs) {
129 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700130 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700131 if (include_ping)
132 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700133 if (!ping_only) {
Marton Hunyadyba51c3f2018-04-25 15:18:10 +0200134 app_body += " <updatecheck";
135 if (!params->target_version_prefix().empty()) {
136 app_body += base::StringPrintf(
137 " targetversionprefix=\"%s\"",
138 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
139 // Rollback requires target_version_prefix set.
140 if (params->rollback_allowed()) {
141 app_body += " rollback_allowed=\"true\"";
142 }
143 }
144 app_body += "></updatecheck>\n";
Jay Srinivasan0a708742012-03-20 11:26:12 -0700145
Darin Petkov265f2902011-05-09 15:17:40 -0700146 // If this is the first update check after a reboot following a previous
147 // update, generate an event containing the previous version number. If
148 // the previous version preference file doesn't exist the event is still
149 // generated with a previous version of 0.0.0.0 -- this is relevant for
150 // older clients or new installs. The previous version event is not sent
151 // for ping-only requests because they come before the client has
Alex Deymo87c08862015-10-30 21:56:55 -0700152 // rebooted. The previous version event is also not sent if it was already
153 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700154 string prev_version;
155 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
156 prev_version = "0.0.0.0";
157 }
Alex Deymo87c08862015-10-30 21:56:55 -0700158 // We only store a non-empty previous version value after a successful
159 // update in the previous boot. After reporting it back to the server,
160 // we clear the previous version value so it doesn't get reported again.
161 if (!prev_version.empty()) {
162 app_body += base::StringPrintf(
163 " <event eventtype=\"%d\" eventresult=\"%d\" "
164 "previousversion=\"%s\"></event>\n",
Alex Deymo9fded1e2015-11-05 12:31:19 -0800165 OmahaEvent::kTypeRebootedAfterUpdate,
166 OmahaEvent::kResultSuccess,
Alex Deymo87c08862015-10-30 21:56:55 -0700167 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
168 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
169 << "Unable to reset the previous version.";
170 }
Darin Petkov95508da2011-01-05 12:42:29 -0800171 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700172 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800173 // The error code is an optional attribute so append it only if the result
174 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700175 string error_code;
176 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700177 error_code = base::StringPrintf(" errorcode=\"%d\"",
178 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700179 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700180 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700181 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700182 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700183 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700184
185 return app_body;
186}
187
Alex Deymo8e18f932015-03-27 16:16:59 -0700188// Returns the cohort* argument to include in the <app> tag for the passed
189// |arg_name| and |prefs_key|, if any. The return value is suitable to
190// concatenate to the list of arguments and includes a space at the end.
191string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700192 const string arg_name,
193 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700194 // There's nothing wrong with not having a given cohort setting, so we check
Sen Jiang771f6482018-04-04 17:59:10 -0700195 // existence first to avoid the warning log message.
Alex Deymo8e18f932015-03-27 16:16:59 -0700196 if (!prefs->Exists(prefs_key))
197 return "";
198 string cohort_value;
199 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
200 return "";
201 // This is a sanity check to avoid sending a huge XML file back to Ohama due
202 // to a compromised stateful partition making the update check fail in low
203 // network environments envent after a reboot.
204 if (cohort_value.size() > 1024) {
205 LOG(WARNING) << "The omaha cohort setting " << arg_name
206 << " has a too big value, which must be an error or an "
207 "attacker trying to inhibit updates.";
208 return "";
209 }
210
Alex Deymob0d74eb2015-03-30 17:59:17 -0700211 string escaped_xml_value;
212 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
213 LOG(WARNING) << "The omaha cohort setting " << arg_name
214 << " is ASCII-7 invalid, ignoring it.";
215 return "";
216 }
217
Alex Deymo8e18f932015-03-27 16:16:59 -0700218 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700219 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700220}
221
Sen Jiang94a4dec2017-03-28 18:23:35 -0700222struct OmahaAppData {
223 string id;
224 string version;
Sen Jiang684c9cd2017-10-17 16:26:45 -0700225 string product_components;
Sen Jiang94a4dec2017-03-28 18:23:35 -0700226};
227
Sen Jiang684c9cd2017-10-17 16:26:45 -0700228bool IsValidComponentID(const string& id) {
229 for (char c : id) {
230 if (!isalnum(c) && c != '-' && c != '_' && c != '.')
231 return false;
232 }
233 return true;
234}
235
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700236// Returns an XML that corresponds to the entire <app> node of the Omaha
237// request based on the given parameters.
238string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700239 OmahaRequestParams* params,
Sen Jiang94a4dec2017-03-28 18:23:35 -0700240 const OmahaAppData& app_data,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700241 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700242 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700243 int ping_active_days,
244 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800245 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700246 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700247 string app_body = GetAppBody(event, params, ping_only, include_ping,
248 ping_active_days, ping_roll_call_days,
249 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700250 string app_versions;
251
Sen Jiang8cd42342018-01-31 12:06:59 -0800252 // If we are downgrading to a more stable channel and we are allowed to do
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700253 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
254 // highest-versioned payload on the destination channel.
Sen Jiang8500d3a2018-02-08 12:04:05 -0800255 if (params->ShouldPowerwash()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700256 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
257 << "on downgrading to the version in the more stable channel";
258 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700259 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700260 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700261 app_versions = "version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700262 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700263 }
264
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700265 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700266 string app_channels =
267 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
268 if (params->current_channel() != download_channel) {
269 app_channels += "from_track=\"" + XmlEncodeWithDefault(
270 params->current_channel(), "") + "\" ";
271 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700272
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700273 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700274
David Zeuthen639aa362014-02-03 16:23:44 -0800275 // If install_date_days is not set (e.g. its value is -1 ), don't
276 // include the attribute.
277 string install_date_in_days_str = "";
278 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700279 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
280 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800281 }
282
Alex Deymo8e18f932015-03-27 16:16:59 -0700283 string app_cohort_args;
284 app_cohort_args += GetCohortArgXml(system_state->prefs(),
285 "cohort", kPrefsOmahaCohort);
286 app_cohort_args += GetCohortArgXml(system_state->prefs(),
287 "cohorthint", kPrefsOmahaCohortHint);
288 app_cohort_args += GetCohortArgXml(system_state->prefs(),
289 "cohortname", kPrefsOmahaCohortName);
290
Alex Deymoebf6e122017-03-10 16:12:01 -0800291 string fingerprint_arg;
292 if (!params->os_build_fingerprint().empty()) {
Sen Jiang8cd42342018-01-31 12:06:59 -0800293 fingerprint_arg = "fingerprint=\"" +
294 XmlEncodeWithDefault(params->os_build_fingerprint(), "") +
295 "\" ";
Alex Deymoebf6e122017-03-10 16:12:01 -0800296 }
297
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700298 string buildtype_arg;
299 if (!params->os_build_type().empty()) {
300 buildtype_arg = "os_build_type=\"" +
301 XmlEncodeWithDefault(params->os_build_type(), "") + "\" ";
302 }
303
Sen Jiang684c9cd2017-10-17 16:26:45 -0700304 string product_components_args;
Sen Jiang8500d3a2018-02-08 12:04:05 -0800305 if (!params->ShouldPowerwash() && !app_data.product_components.empty()) {
Sen Jiang684c9cd2017-10-17 16:26:45 -0700306 brillo::KeyValueStore store;
307 if (store.LoadFromString(app_data.product_components)) {
308 for (const string& key : store.GetKeys()) {
309 if (!IsValidComponentID(key)) {
310 LOG(ERROR) << "Invalid component id: " << key;
311 continue;
312 }
313 string version;
314 if (!store.GetString(key, &version)) {
315 LOG(ERROR) << "Failed to get version for " << key
316 << " in product_components.";
317 continue;
318 }
319 product_components_args +=
320 base::StringPrintf("_%s.version=\"%s\" ",
321 key.c_str(),
322 XmlEncodeWithDefault(version, "").c_str());
323 }
324 } else {
325 LOG(ERROR) << "Failed to parse product_components:\n"
326 << app_data.product_components;
327 }
328 }
329
330 // clang-format off
Alex Deymob0d74eb2015-03-30 17:59:17 -0700331 string app_xml = " <app "
Sen Jiang94a4dec2017-03-28 18:23:35 -0700332 "appid=\"" + XmlEncodeWithDefault(app_data.id, "") + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700333 app_cohort_args +
334 app_versions +
335 app_channels +
Sen Jiang684c9cd2017-10-17 16:26:45 -0700336 product_components_args +
Alex Deymoebf6e122017-03-10 16:12:01 -0800337 fingerprint_arg +
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700338 buildtype_arg +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700339 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
340 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
341 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
342 "delta_okay=\"" + delta_okay_str + "\" "
343 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
344 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
345 install_date_in_days_str +
346 ">\n" +
347 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700348 " </app>\n";
Sen Jiang684c9cd2017-10-17 16:26:45 -0700349 // clang-format on
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700350 return app_xml;
351}
352
353// Returns an XML that corresponds to the entire <os> node of the Omaha
354// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700355string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700356 string os_xml =" <os "
357 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
358 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
359 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
360 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700361 return os_xml;
362}
363
364// Returns an XML that corresponds to the entire Omaha request based on the
365// given parameters.
366string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700367 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700368 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700369 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700370 int ping_active_days,
371 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800372 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700373 SystemState* system_state) {
374 string os_xml = GetOsXml(params);
Sen Jiang684c9cd2017-10-17 16:26:45 -0700375 OmahaAppData product_app = {
376 .id = params->GetAppId(),
377 .version = params->app_version(),
378 .product_components = params->product_components()};
Sen Jiang94a4dec2017-03-28 18:23:35 -0700379 string app_xml = GetAppXml(event,
380 params,
381 product_app,
382 ping_only,
383 include_ping,
384 ping_active_days,
385 ping_roll_call_days,
386 install_date_in_days,
387 system_state);
388 if (!params->system_app_id().empty()) {
389 OmahaAppData system_app = {.id = params->system_app_id(),
390 .version = params->system_version()};
391 app_xml += GetAppXml(event,
392 params,
393 system_app,
394 ping_only,
395 include_ping,
396 ping_active_days,
397 ping_roll_call_days,
398 install_date_in_days,
399 system_state);
400 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700401
Alex Vakulenko75039d72014-03-25 12:36:28 -0700402 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700403 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700404
Alex Deymoac41a822015-09-15 20:52:53 -0700405 string updater_version = XmlEncodeWithDefault(
406 base::StringPrintf("%s-%s",
407 constants::kOmahaUpdaterID,
408 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700409 string request_xml =
410 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700411 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700412 "version=\"" + updater_version + "\" "
413 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700414 install_source +
415 "ismachine=\"1\">\n") +
416 os_xml +
417 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700418 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700419
420 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000421}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700422
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700423} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000424
David Zeuthene8ed8632014-07-24 13:38:10 -0400425// Struct used for holding data obtained when parsing the XML.
426struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400427 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
428
429 // Pointer to the expat XML_Parser object.
430 XML_Parser xml_parser;
431
David Zeuthene8ed8632014-07-24 13:38:10 -0400432 // This is the state of the parser as it's processing the XML.
433 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400434 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400435 string current_path;
436
437 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400438 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700439 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400440 string daystart_elapsed_days;
441 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800442
Sen Jiang81259682017-03-30 15:11:30 -0700443 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700444 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700445 vector<string> url_codebase;
446 string manifest_version;
447 map<string, string> action_postinstall_attrs;
448 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700449 string cohort;
450 string cohorthint;
451 string cohortname;
452 bool cohort_set = false;
453 bool cohorthint_set = false;
454 bool cohortname_set = false;
Sen Jiang81259682017-03-30 15:11:30 -0700455
456 struct Package {
457 string name;
458 string size;
459 string hash;
460 };
461 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800462 };
Sen Jiang81259682017-03-30 15:11:30 -0700463 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400464};
465
466namespace {
467
468// Callback function invoked by expat.
469void ParserHandlerStart(void* user_data, const XML_Char* element,
470 const XML_Char** attr) {
471 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
472
473 if (data->failed)
474 return;
475
476 data->current_path += string("/") + element;
477
478 map<string, string> attrs;
479 if (attr != nullptr) {
480 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
481 string key = attr[n];
482 string value = attr[n + 1];
483 attrs[key] = value;
484 }
485 }
486
Alex Deymo8e18f932015-03-27 16:16:59 -0700487 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700488 OmahaParserData::App app;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700489 if (attrs.find("appid") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700490 app.id = attrs["appid"];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700491 }
Alex Deymo8e18f932015-03-27 16:16:59 -0700492 if (attrs.find("cohort") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700493 app.cohort_set = true;
494 app.cohort = attrs["cohort"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700495 }
496 if (attrs.find("cohorthint") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700497 app.cohorthint_set = true;
498 app.cohorthint = attrs["cohorthint"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700499 }
500 if (attrs.find("cohortname") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700501 app.cohortname_set = true;
502 app.cohortname = attrs["cohortname"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700503 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700504 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700505 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700506 if (!data->apps.empty())
507 data->apps.back().updatecheck_status = attrs["status"];
508 if (data->updatecheck_poll_interval.empty())
509 data->updatecheck_poll_interval = attrs["PollInterval"];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700510 // Omaha sends arbitrary key-value pairs as extra attributes starting with
511 // an underscore.
512 for (const auto& attr : attrs) {
513 if (!attr.first.empty() && attr.first[0] == '_')
514 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
515 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400516 } else if (data->current_path == "/response/daystart") {
517 // Get the install-date.
518 data->daystart_elapsed_days = attrs["elapsed_days"];
519 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
520 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
521 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700522 if (!data->apps.empty())
523 data->apps.back().url_codebase.push_back(attrs["codebase"]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800524 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400525 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800526 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700527 if (!data->apps.empty())
528 data->apps.back().packages.push_back({.name = attrs["name"],
529 .size = attrs["size"],
530 .hash = attrs["hash_sha256"]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400531 } else if (data->current_path == "/response/app/updatecheck/manifest") {
532 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700533 if (!data->apps.empty())
534 data->apps.back().manifest_version = attrs[kTagVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400535 } else if (data->current_path ==
536 "/response/app/updatecheck/manifest/actions/action") {
537 // We only care about the postinstall action.
Sen Jiang81259682017-03-30 15:11:30 -0700538 if (attrs["event"] == "postinstall" && !data->apps.empty()) {
539 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400540 }
541 }
542}
543
544// Callback function invoked by expat.
545void ParserHandlerEnd(void* user_data, const XML_Char* element) {
546 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
547 if (data->failed)
548 return;
549
550 const string path_suffix = string("/") + element;
551
Alex Vakulenko0103c362016-01-20 07:56:15 -0800552 if (!base::EndsWith(data->current_path, path_suffix,
553 base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400554 LOG(ERROR) << "Unexpected end element '" << element
555 << "' with current_path='" << data->current_path << "'";
556 data->failed = true;
557 return;
558 }
559 data->current_path.resize(data->current_path.size() - path_suffix.size());
560}
561
David Zeuthenf3e28012014-08-26 18:23:52 -0400562// Callback function invoked by expat.
563//
564// This is called for entity declarations. Since Omaha is guaranteed
565// to never return any XML with entities our course of action is to
566// just stop parsing. This avoids potential resource exhaustion
567// problems AKA the "billion laughs". CVE-2013-0340.
568void ParserHandlerEntityDecl(void *user_data,
569 const XML_Char *entity_name,
570 int is_parameter_entity,
571 const XML_Char *value,
572 int value_length,
573 const XML_Char *base,
574 const XML_Char *system_id,
575 const XML_Char *public_id,
576 const XML_Char *notation_name) {
577 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
578
579 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
580 data->failed = true;
581 data->entity_decl = true;
582 XML_StopParser(data->xml_parser, false);
583}
584
David Zeuthene8ed8632014-07-24 13:38:10 -0400585} // namespace
586
Alex Deymob0d74eb2015-03-30 17:59:17 -0700587bool XmlEncode(const string& input, string* output) {
588 if (std::find_if(input.begin(), input.end(),
589 [](const char c){return c & 0x80;}) != input.end()) {
590 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
591 utils::HexDumpString(input);
592 return false;
593 }
Alex Deymocc457852015-06-18 18:35:50 -0700594 output->clear();
595 // We need at least input.size() space in the output, but the code below will
596 // handle it if we need more.
597 output->reserve(input.size());
598 for (char c : input) {
599 switch (c) {
600 case '\"':
601 output->append("&quot;");
602 break;
603 case '\'':
604 output->append("&apos;");
605 break;
606 case '&':
607 output->append("&amp;");
608 break;
609 case '<':
610 output->append("&lt;");
611 break;
612 case '>':
613 output->append("&gt;");
614 break;
615 default:
616 output->push_back(c);
617 }
618 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700619 return true;
620}
621
622string XmlEncodeWithDefault(const string& input, const string& default_value) {
623 string output;
624 if (XmlEncode(input, &output))
625 return output;
626 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000627}
628
Alex Deymoc1c17b42015-11-23 03:53:15 -0300629OmahaRequestAction::OmahaRequestAction(
630 SystemState* system_state,
631 OmahaEvent* event,
632 std::unique_ptr<HttpFetcher> http_fetcher,
633 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800634 : system_state_(system_state),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800635 params_(system_state->request_params()),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700636 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300637 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800638 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700639 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700640 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700641 ping_roll_call_days_(0) {
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800642 policy_provider_->Reload();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700643}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000644
Darin Petkov6a5b3222010-07-13 14:55:28 -0700645OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000646
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700647// Calculates the value to use for the ping days parameter.
648int OmahaRequestAction::CalculatePingDays(const string& key) {
649 int days = kNeverPinged;
650 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800651 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700652 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
653 if (days < 0) {
654 // If |days| is negative, then the system clock must have jumped
655 // back in time since the ping was sent. Mark the value so that
656 // it doesn't get sent to the server but we still update the
657 // last ping daystart preference. This way the next ping time
658 // will be correct, hopefully.
659 days = kPingTimeJump;
660 LOG(WARNING) <<
661 "System clock jumped back in time. Resetting ping daystarts.";
662 }
663 }
664 return days;
665}
666
667void OmahaRequestAction::InitPingDays() {
668 // We send pings only along with update checks, not with events.
669 if (IsEvent()) {
670 return;
671 }
672 // TODO(petkov): Figure a way to distinguish active use pings
673 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700674 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700675 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
676 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
677}
678
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700679bool OmahaRequestAction::ShouldPing() const {
680 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
681 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
682 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
683 if (powerwash_count > 0) {
684 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
685 << "powerwash_count is " << powerwash_count;
686 return false;
687 }
Amin Hassani1677e812017-06-21 13:36:36 -0700688 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
689 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
690 << "the first_active_omaha_ping_sent is true";
691 return false;
692 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700693 return true;
694 }
695 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
696}
697
David Zeuthen639aa362014-02-03 16:23:44 -0800698// static
699int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
700 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700701 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800702 return -1;
703
704 // If we have the value stored on disk, just return it.
705 int64_t stored_value;
706 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
707 // Convert and sanity-check.
708 int install_date_days = static_cast<int>(stored_value);
709 if (install_date_days >= 0)
710 return install_date_days;
711 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
712 << install_date_days << " looks suspicious.";
713 prefs->Delete(kPrefsInstallDateDays);
714 }
715
716 // Otherwise, if OOBE is not complete then do nothing and wait for
717 // ParseResponse() to call ParseInstallDate() and then
718 // PersistInstallDate() to set the kPrefsInstallDateDays state
719 // variable. Once that is done, we'll then report back in future
720 // Omaha requests. This works exactly because OOBE triggers an
721 // update check.
722 //
723 // However, if OOBE is complete and the kPrefsInstallDateDays state
724 // variable is not set, there are two possibilities
725 //
726 // 1. The update check in OOBE failed so we never got a response
727 // from Omaha (no network etc.); or
728 //
729 // 2. OOBE was done on an older version that didn't write to the
730 // kPrefsInstallDateDays state variable.
731 //
732 // In both cases, we approximate the install date by simply
733 // inspecting the timestamp of when OOBE happened.
734
735 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700736 if (!system_state->hardware()->IsOOBEEnabled() ||
737 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800738 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700739 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800740 return -1;
741 }
742
743 int num_days;
744 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
745 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
746 << "as its value '" << utils::ToString(time_of_oobe)
747 << "' looks suspicious.";
748 return -1;
749 }
750
751 // Persist this to disk, for future use.
752 if (!OmahaRequestAction::PersistInstallDate(system_state,
753 num_days,
754 kProvisionedFromOOBEMarker))
755 return -1;
756
757 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
758 << num_days << " days";
759
760 return num_days;
761}
762
Darin Petkov6a5b3222010-07-13 14:55:28 -0700763void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000764 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700765 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700766 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700767 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700768 return;
769 }
David Zeuthen639aa362014-02-03 16:23:44 -0800770
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700771 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700772 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700773 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700774 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700775 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800776 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800777 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700778 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700779
Sen Jiang42fa45e2018-03-12 11:02:14 -0700780 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700781 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
782 params_->interactive() ? "fg" : "bg");
783 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
784 http_fetcher_->SetHeader(
785 kXGoogleUpdateUpdater,
786 base::StringPrintf(
787 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
788
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800789 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
790 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700791 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700792 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700793 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000794}
795
Darin Petkov6a5b3222010-07-13 14:55:28 -0700796void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000797 http_fetcher_->TerminateTransfer();
798}
799
800// We just store the response in the buffer. Once we've received all bytes,
801// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700802void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800803 const void* bytes,
804 size_t length) {
805 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
806 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000807}
808
809namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000810
811// Parses a 64 bit base-10 int from a string and returns it. Returns 0
812// on error. If the string contains "0", that's indistinguishable from
813// error.
814off_t ParseInt(const string& str) {
815 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700816 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000817 if (rc < 1) {
818 // failure
819 return 0;
820 }
821 return ret;
822}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700823
David Zeuthene8ed8632014-07-24 13:38:10 -0400824// Parses |str| and returns |true| if, and only if, its value is "true".
825bool ParseBool(const string& str) {
826 return str == "true";
827}
828
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700829// Update the last ping day preferences based on the server daystart
830// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400831bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700832 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400833 TEST_AND_RETURN_FALSE(
834 base::StringToInt64(parser_data->daystart_elapsed_seconds,
835 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700836 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
837
838 // Remember the local time that matches the server's last midnight
839 // time.
840 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
841 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
842 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
843 return true;
844}
Sen Jiang81259682017-03-30 15:11:30 -0700845
846// Parses the package node in the given XML document and populates
847// |output_object| if valid. Returns true if we should continue the parsing.
848// False otherwise, in which case it sets any error code using |completer|.
849bool ParsePackage(OmahaParserData::App* app,
850 OmahaResponse* output_object,
851 ScopedActionCompleter* completer) {
852 if (app->updatecheck_status == "noupdate") {
853 if (!app->packages.empty()) {
854 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
855 completer->set_code(ErrorCode::kOmahaResponseInvalid);
856 return false;
857 }
858 return true;
859 }
860 if (app->packages.empty()) {
861 LOG(ERROR) << "Omaha Response has no packages";
862 completer->set_code(ErrorCode::kOmahaResponseInvalid);
863 return false;
864 }
865 if (app->url_codebase.empty()) {
866 LOG(ERROR) << "No Omaha Response URLs";
867 completer->set_code(ErrorCode::kOmahaResponseInvalid);
868 return false;
869 }
870 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
871 vector<string> metadata_sizes =
872 base::SplitString(app->action_postinstall_attrs[kTagMetadataSize],
873 ":",
874 base::TRIM_WHITESPACE,
875 base::SPLIT_WANT_ALL);
876 vector<string> metadata_signatures =
877 base::SplitString(app->action_postinstall_attrs[kTagMetadataSignatureRsa],
878 ":",
879 base::TRIM_WHITESPACE,
880 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700881 vector<string> is_delta_payloads =
882 base::SplitString(app->action_postinstall_attrs[kTagIsDeltaPayload],
883 ":",
884 base::TRIM_WHITESPACE,
885 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700886 for (size_t i = 0; i < app->packages.size(); i++) {
887 const auto& package = app->packages[i];
888 if (package.name.empty()) {
889 LOG(ERROR) << "Omaha Response has empty package name";
890 completer->set_code(ErrorCode::kOmahaResponseInvalid);
891 return false;
892 }
893 LOG(INFO) << "Found package " << package.name;
894
895 OmahaResponse::Package out_package;
896 for (const string& codebase : app->url_codebase) {
897 if (codebase.empty()) {
898 LOG(ERROR) << "Omaha Response URL has empty codebase";
899 completer->set_code(ErrorCode::kOmahaResponseInvalid);
900 return false;
901 }
902 out_package.payload_urls.push_back(codebase + package.name);
903 }
904 // Parse the payload size.
905 base::StringToUint64(package.size, &out_package.size);
906 if (out_package.size <= 0) {
907 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
908 completer->set_code(ErrorCode::kOmahaResponseInvalid);
909 return false;
910 }
911 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
912
913 if (i < metadata_sizes.size())
914 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
915 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
916 << " bytes";
917
918 if (i < metadata_signatures.size())
919 out_package.metadata_signature = metadata_signatures[i];
920 LOG(INFO) << "Payload metadata signature = "
921 << out_package.metadata_signature;
922
923 out_package.hash = package.hash;
924 if (out_package.hash.empty()) {
925 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
926 completer->set_code(ErrorCode::kOmahaResponseInvalid);
927 return false;
928 }
929 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700930
931 if (i < is_delta_payloads.size())
932 out_package.is_delta = ParseBool(is_delta_payloads[i]);
933 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
934
Sen Jiang81259682017-03-30 15:11:30 -0700935 output_object->packages.push_back(std::move(out_package));
936 }
937
938 return true;
939}
940
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700941} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000942
David Zeuthene8ed8632014-07-24 13:38:10 -0400943bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700944 OmahaResponse* output_object,
945 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700946 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700947 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700948 return false;
949 }
Sen Jiang81259682017-03-30 15:11:30 -0700950 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700951
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800952 // chromium-os:37289: The PollInterval is not supported by Omaha server
953 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700954 // slow down the request rate from the server-side. Note that the PollInterval
955 // is not persisted, so it has to be sent by the server on every response to
956 // guarantee that the scheduler uses this value (otherwise, if the device got
957 // rebooted after the last server-indicated value, it'll revert to the default
958 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
959 // based on the assumption that we perform an update check every hour so that
960 // the max value of 8 will roughly be equivalent to one work day. If we decide
961 // to use PollInterval permanently, we should update the
962 // max_update_checks_allowed to take PollInterval into account. Note: The
963 // parsing for PollInterval happens even before parsing of the status because
964 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400965 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700966 &output_object->poll_interval);
967
David Zeuthen639aa362014-02-03 16:23:44 -0800968 // Check for the "elapsed_days" attribute in the "daystart"
969 // element. This is the number of days since Jan 1 2007, 0:00
970 // PST. If we don't have a persisted value of the Omaha InstallDate,
971 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400972 if (ParseInstallDate(parser_data, output_object) &&
973 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800974 // Since output_object->install_date_days is never negative, the
975 // elapsed_days -> install-date calculation is reduced to simply
976 // rounding down to the nearest number divisible by 7.
977 int remainder = output_object->install_date_days % 7;
978 int install_date_days_rounded =
979 output_object->install_date_days - remainder;
980 if (PersistInstallDate(system_state_,
981 install_date_days_rounded,
982 kProvisionedFromOmahaResponse)) {
983 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
984 << install_date_days_rounded << " days";
985 }
986 }
987
Alex Deymo00d79ac2015-06-29 15:41:49 -0700988 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -0700989 for (const auto& app : parser_data->apps) {
990 if (app.id == params_->GetAppId()) {
991 if (app.cohort_set)
992 PersistCohortData(kPrefsOmahaCohort, app.cohort);
993 if (app.cohorthint_set)
994 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
995 if (app.cohortname_set)
996 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
997 break;
998 }
999 }
Alex Deymo00d79ac2015-06-29 15:41:49 -07001000
Alex Deymob3fa53b2016-04-18 19:57:58 -07001001 // Parse the updatecheck attributes.
1002 PersistEolStatus(parser_data->updatecheck_attrs);
Marton Hunyady199152d2018-05-07 19:08:48 +02001003 // Rollback-related updatecheck attributes.
1004 // Defaults to false if attribute is not present.
1005 output_object->is_rollback =
1006 ParseBool(parser_data->updatecheck_attrs[kRollback]);
1007 // Defaults to 0 if attribute is not present. This is fine for these values,
1008 // because it's the lowest possible value, and the rollback image won't be
1009 // installed, if the values in the TPM are larger than these, and in case the
1010 // values in the TPM are 0, all images will be able to boot up.
1011 output_object->firmware_version = static_cast<uint32_t>(
1012 ParseInt(parser_data->updatecheck_attrs[kFirmwareVersion]));
1013 output_object->kernel_version = static_cast<uint32_t>(
1014 ParseInt(parser_data->updatecheck_attrs[kKernelVersion]));
Alex Deymob3fa53b2016-04-18 19:57:58 -07001015
David Zeuthene8ed8632014-07-24 13:38:10 -04001016 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001017 return false;
1018
David Zeuthene8ed8632014-07-24 13:38:10 -04001019 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001020 return false;
1021
Sen Jiang0affc2c2017-02-10 15:55:05 -08001022 // Package has to be parsed after Params now because ParseParams need to make
1023 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -07001024 for (auto& app : parser_data->apps)
1025 if (!ParsePackage(&app, output_object, completer))
1026 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001027
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001028 return true;
1029}
1030
David Zeuthene8ed8632014-07-24 13:38:10 -04001031bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001032 OmahaResponse* output_object,
1033 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001034 output_object->update_exists = false;
1035 for (size_t i = 0; i < parser_data->apps.size(); i++) {
1036 const string& status = parser_data->apps[i].updatecheck_status;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001037 if (status == "noupdate") {
1038 // Don't update if any app has status="noupdate".
Sen Jiang81259682017-03-30 15:11:30 -07001039 LOG(INFO) << "No update for <app> " << i;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001040 output_object->update_exists = false;
1041 break;
Sen Jiang81259682017-03-30 15:11:30 -07001042 } else if (status == "ok") {
Sen Jiang00adf7b2017-06-26 15:57:29 -07001043 if (parser_data->apps[i].action_postinstall_attrs["noupdate"] == "true") {
1044 // noupdate="true" in postinstall attributes means it's an update to
1045 // self, only update if there's at least one app really have update.
1046 LOG(INFO) << "Update to self for <app> " << i;
1047 } else {
1048 LOG(INFO) << "Update for <app> " << i;
1049 output_object->update_exists = true;
1050 }
Sen Jiang81259682017-03-30 15:11:30 -07001051 } else {
1052 LOG(ERROR) << "Unknown Omaha response status: " << status;
1053 completer->set_code(ErrorCode::kOmahaResponseInvalid);
1054 return false;
1055 }
1056 }
1057 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001058 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001059 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001060 }
1061
Sen Jiang81259682017-03-30 15:11:30 -07001062 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001063}
1064
David Zeuthene8ed8632014-07-24 13:38:10 -04001065bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001066 OmahaResponse* output_object,
1067 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001068 map<string, string> attrs;
1069 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001070 if (app.id == params_->GetAppId()) {
1071 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -07001072 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001073 } else if (!params_->system_app_id().empty() &&
1074 app.id == params_->system_app_id()) {
1075 // this is the system app (this check is intentionally skipped if there is
1076 // no system_app_id set)
1077 output_object->system_version = app.manifest_version;
1078 }
1079 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -07001080 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001081 }
Sen Jiang81259682017-03-30 15:11:30 -07001082 }
Chris Sosa3b748432013-06-20 16:42:59 -07001083 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -07001084 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001085 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -07001086 return false;
1087 }
1088
1089 LOG(INFO) << "Received omaha response to update to version "
1090 << output_object->version;
1091
David Zeuthene8ed8632014-07-24 13:38:10 -04001092 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001093 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001094 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001095 return false;
1096 }
1097
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001098 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -04001099 output_object->more_info_url = attrs[kTagMoreInfo];
David Zeuthene8ed8632014-07-24 13:38:10 -04001100 output_object->prompt = ParseBool(attrs[kTagPrompt]);
1101 output_object->deadline = attrs[kTagDeadline];
1102 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001103 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -04001104 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001105 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -04001106 ParseBool(attrs[kTagDisableP2PForSharing]);
1107 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001108
David Zeuthene8ed8632014-07-24 13:38:10 -04001109 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -08001110 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001111 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001112
Jay Srinivasan08262882012-12-28 19:29:43 -08001113 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -04001114 ParseBool(attrs[kTagDisablePayloadBackoff]);
Sen Jiangfe284402018-03-21 14:03:50 -07001115 output_object->powerwash_required = ParseBool(attrs[kTagPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -08001116
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001117 return true;
1118}
1119
David Zeuthene8ed8632014-07-24 13:38:10 -04001120// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +00001121// and fill in the appropriate fields of the output object. Also, notifies
1122// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -07001123void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
1124 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +00001125 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001126 string current_response(response_buffer_.begin(), response_buffer_.end());
1127 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001128
Gilad Arnold74b5f552014-10-07 08:17:16 -07001129 PayloadStateInterface* const payload_state = system_state_->payload_state();
1130
Zentaro Kavanagh76af2662018-05-15 10:54:53 -07001131 // Set the max kernel key version based on whether rollback is allowed.
1132 SetMaxKernelKeyVersionForRollback();
1133
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001134 // Events are best effort transactions -- assume they always succeed.
1135 if (IsEvent()) {
1136 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001137 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001138 return;
1139 }
1140
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001141 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001142 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -07001143 int code = GetHTTPResponseCode();
1144 // Makes sure we send sane error values.
1145 if (code < 0 || code >= 1000) {
1146 code = 999;
1147 }
David Zeuthena99981f2013-04-29 13:42:47 -07001148 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001149 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +00001150 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001151 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001152
David Zeuthene8ed8632014-07-24 13:38:10 -04001153 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -04001154 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -04001155 XML_SetUserData(parser, &parser_data);
1156 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -04001157 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001158 XML_Status res = XML_Parse(
1159 parser,
1160 reinterpret_cast<const char*>(response_buffer_.data()),
1161 response_buffer_.size(),
1162 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -04001163 XML_ParserFree(parser);
1164
1165 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -07001166 LOG(ERROR) << "Omaha response not valid XML: "
1167 << XML_ErrorString(XML_GetErrorCode(parser))
1168 << " at line " << XML_GetCurrentLineNumber(parser)
1169 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -04001170 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
1171 if (response_buffer_.empty()) {
1172 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
1173 } else if (parser_data.entity_decl) {
1174 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
1175 }
1176 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001177 return;
1178 }
1179
Alex Deymoebbe7ef2014-10-30 13:02:49 -07001180 // Update the last ping day preferences based on the server daystart response
1181 // even if we didn't send a ping. Omaha always includes the daystart in the
1182 // response, but log the error if it didn't.
1183 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
1184 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -07001185
Amin Hassani1677e812017-06-21 13:36:36 -07001186 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
1187 // we have got a response from omaha and if its value has never been set to
1188 // true before. Failure of this function should be ignored. There should be no
1189 // need to check if a=-1 has been sent because older devices have already sent
1190 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
1191 // future checks.
1192 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
Amin Hassani80f4d4c2018-05-16 13:34:00 -07001193 if (!system_state_->hardware()->SetFirstActiveOmahaPingSent()) {
1194 system_state_->metrics_reporter()->ReportInternalErrorCode(
1195 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
1196 }
Amin Hassani1677e812017-06-21 13:36:36 -07001197 }
1198
Thieu Le116fda32011-04-19 11:01:54 -07001199 if (!HasOutputPipe()) {
1200 // Just set success to whether or not the http transfer succeeded,
1201 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001202 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001203 return;
1204 }
1205
Darin Petkov6a5b3222010-07-13 14:55:28 -07001206 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001207 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001208 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001209 output_object.update_exists = true;
1210 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001211
Weidong Guo421ff332017-04-17 10:08:38 -07001212 ErrorCode error = ErrorCode::kSuccess;
1213 if (ShouldIgnoreUpdate(&error, output_object)) {
1214 // No need to change output_object.update_exists here, since the value
1215 // has been output to the pipe.
1216 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001217 return;
1218 }
1219
David Zeuthen8f191b22013-08-06 12:27:50 -07001220 // If Omaha says to disable p2p, respect that
1221 if (output_object.disable_p2p_for_downloading) {
1222 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1223 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001224 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001225 }
1226 if (output_object.disable_p2p_for_sharing) {
1227 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1228 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001229 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001230 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001231
1232 // Update the payload state with the current response. The payload state
1233 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001234 // from what's stored already. We are updating the payload state as late
1235 // as possible in this method so that if a new release gets pushed and then
1236 // got pulled back due to some issues, we don't want to clear our internal
1237 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001238 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001239
David Zeuthen8f191b22013-08-06 12:27:50 -07001240 // It could be we've already exceeded the deadline for when p2p is
1241 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001242 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001243 payload_state->P2PNewAttempt();
1244 if (!payload_state->P2PAttemptAllowed()) {
1245 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1246 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001247 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001248 }
1249 }
1250
1251 // From here on, we'll complete stuff in CompleteProcessing() so
1252 // disable |completer| since we'll create a new one in that
1253 // function.
1254 completer.set_should_complete(false);
1255
1256 // If we're allowed to use p2p for downloading we do not pay
1257 // attention to wall-clock-based waiting if the URL is indeed
1258 // available via p2p. Therefore, check if the file is available via
1259 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001260 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001261 LookupPayloadViaP2P(output_object);
1262 } else {
1263 CompleteProcessing();
1264 }
1265}
1266
1267void OmahaRequestAction::CompleteProcessing() {
1268 ScopedActionCompleter completer(processor_, this);
1269 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1270 PayloadStateInterface* payload_state = system_state_->payload_state();
1271
Alex Deymo46a9aae2016-05-04 20:20:11 -07001272 if (system_state_->hardware()->IsOOBEEnabled() &&
1273 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
Marton Hunyadyc2882062018-05-14 17:28:25 +02001274 (output_object.deadline.empty() ||
1275 payload_state->GetRollbackHappened()) &&
Kevin Cernekeec5081a82016-04-08 12:29:52 -07001276 params_->app_version() != "ForcedUpdate") {
Kevin Cernekee2494e282016-03-29 18:03:53 -07001277 output_object.update_exists = false;
1278 LOG(INFO) << "Ignoring non-critical Omaha updates until OOBE is done.";
1279 completer.set_code(ErrorCode::kNonCriticalUpdateInOOBE);
1280 return;
1281 }
1282
David Zeuthen8f191b22013-08-06 12:27:50 -07001283 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001284 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001285 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001286 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001287 return;
1288 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001289
Chris Sosa20f005c2013-09-05 13:53:08 -07001290 if (payload_state->ShouldBackoffDownload()) {
1291 output_object.update_exists = false;
1292 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1293 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001294 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001295 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001296 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001297 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001298}
1299
1300void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1301 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1302 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001303 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001304 } else {
1305 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1306 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001307 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001308 }
1309 CompleteProcessing();
1310}
1311
1312void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001313 // If the device is in the middle of an update, the state variables
1314 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1315 // tracks the offset and length of the operation currently in
1316 // progress. The offset is based from the end of the manifest which
1317 // is kPrefsManifestMetadataSize bytes long.
1318 //
1319 // To make forward progress and avoid deadlocks, we need to find a
1320 // peer that has at least the entire operation we're currently
1321 // working on. Otherwise we may end up in a situation where two
1322 // devices bounce back and forth downloading from each other,
1323 // neither making any forward progress until one of them decides to
1324 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1325 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001326 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001327 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001328 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001329 int64_t next_data_offset = 0;
1330 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001331 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001332 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1333 &manifest_metadata_size) &&
1334 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001335 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1336 &manifest_signature_size) &&
1337 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001338 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001339 &next_data_offset) &&
1340 next_data_offset != -1 &&
1341 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1342 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001343 minimum_size = manifest_metadata_size + manifest_signature_size +
1344 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001345 }
1346
Sen Jiang0affc2c2017-02-10 15:55:05 -08001347 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001348 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001349 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001350 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001351 string file_id =
1352 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001353 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001354 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1355 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001356 system_state_->p2p_manager()->LookupUrlForFile(
1357 file_id,
1358 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001359 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001360 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1361 base::Unretained(this)));
1362 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001363}
1364
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001365bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001366 if (params_->interactive()) {
1367 LOG(INFO) << "Not deferring download because update is interactive.";
1368 return false;
1369 }
1370
David Zeuthen8f191b22013-08-06 12:27:50 -07001371 // If we're using p2p to download _and_ we have a p2p URL, we never
1372 // defer the download. This is because the download will always
1373 // happen from a peer on the LAN and we've been waiting in line for
1374 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001375 const PayloadStateInterface* payload_state = system_state_->payload_state();
1376 if (payload_state->GetUsingP2PForDownloading() &&
1377 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001378 LOG(INFO) << "Download not deferred because download "
1379 << "will happen from a local peer (via p2p).";
1380 return false;
1381 }
1382
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001383 // We should defer the downloads only if we've first satisfied the
1384 // wall-clock-based-waiting period and then the update-check-based waiting
1385 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001386 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001387 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1388 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001389 return false;
1390 }
1391
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001392 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001393 case kWallClockWaitNotSatisfied:
1394 // We haven't even satisfied the first condition, passing the
1395 // wall-clock-based waiting period, so we should defer the downloads
1396 // until that happens.
1397 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1398 return true;
1399
1400 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1401 LOG(INFO) << "wall-clock-based-wait satisfied and "
1402 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001403 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001404
1405 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1406 // Wall-clock-based waiting period is satisfied, and it's determined
1407 // that we do not need the update-check-based wait. so no need to
1408 // defer downloads.
1409 LOG(INFO) << "wall-clock-based-wait satisfied and "
1410 << "update-check-based-wait is not required.";
1411 return false;
1412
1413 default:
1414 // Returning false for this default case so we err on the
1415 // side of downloading updates than deferring in case of any bugs.
1416 NOTREACHED();
1417 return false;
1418 }
1419}
1420
1421OmahaRequestAction::WallClockWaitResult
1422OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001423 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001424 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001425 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001426
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001427 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1428 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1429 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001430 // Note: This timestamp could be that of ANY update we saw in the past
1431 // (not necessarily this particular update we're considering to apply)
1432 // but never got to apply because of some reason (e.g. stop AU policy,
1433 // updates being pulled out from Omaha, changes in target version prefix,
1434 // new update being rolled out, etc.). But for the purposes of scattering
1435 // it doesn't matter which update the timestamp corresponds to. i.e.
1436 // the clock starts ticking the first time we see an update and we're
1437 // ready to apply when the random wait period is satisfied relative to
1438 // that first seen timestamp.
1439 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1440 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1441 << utils::ToString(update_first_seen_at);
1442 } else {
1443 // This seems like an unexpected error where the persisted value exists
1444 // but it's not readable for some reason. Just skip scattering in this
1445 // case to be safe.
1446 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1447 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1448 }
1449 } else {
Sen Jiang7c1171e2016-06-23 11:35:40 -07001450 update_first_seen_at = system_state_->clock()->GetWallclockTime();
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001451 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001452 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1453 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001454 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1455 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001456 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001457 // This seems like an unexpected error where the value cannot be
1458 // persisted for some reason. Just skip scattering in this
1459 // case to be safe.
1460 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1461 << utils::ToString(update_first_seen_at)
1462 << " cannot be persisted";
1463 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1464 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001465 }
1466
Sen Jiang7c1171e2016-06-23 11:35:40 -07001467 TimeDelta elapsed_time =
1468 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1469 TimeDelta max_scatter_period =
1470 TimeDelta::FromDays(output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001471
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001472 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001473 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001474 << ", Time Elapsed = "
1475 << utils::FormatSecs(elapsed_time.InSeconds())
1476 << ", MaxDaysToScatter = "
1477 << max_scatter_period.InDays();
1478
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001479 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001480 // The deadline is set for all rules which serve a delta update from a
1481 // previous FSI, which means this update will be applied mostly in OOBE
1482 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1483 // quickly.
1484 LOG(INFO) << "Not scattering as deadline flag is set";
1485 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1486 }
1487
1488 if (max_scatter_period.InDays() == 0) {
1489 // This means the Omaha rule creator decides that this rule
1490 // should not be scattered irrespective of the policy.
1491 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1492 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1493 }
1494
1495 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001496 // This means we've waited more than the upperbound wait in the rule
1497 // from the time we first saw a valid update available to us.
1498 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001499 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1500 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1501 }
1502
1503 // This means we are required to participate in scattering.
1504 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001505 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001506 if (remaining_wait_time.InSeconds() <= 0) {
1507 // Yes, it's our turn now.
1508 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1509
1510 // But we can't download until the update-check-count-based wait is also
1511 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001512 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001513 kWallClockWaitDoneButUpdateCheckWaitRequired :
1514 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1515 }
1516
1517 // Not our turn yet, so we have to wait until our turn to
1518 // help scatter the downloads across all clients of the enterprise.
1519 LOG(INFO) << "Update deferred for another "
1520 << utils::FormatSecs(remaining_wait_time.InSeconds())
1521 << " per policy.";
1522 return kWallClockWaitNotSatisfied;
1523}
1524
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001525bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001526 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001527
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001528 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1529 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1530 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001531 // We are unable to read the update check count from file for some reason.
1532 // So let's proceed anyway so as to not stall the update.
1533 LOG(ERROR) << "Unable to read update check count. "
1534 << "Skipping update-check-count-based-wait.";
1535 return true;
1536 }
1537 } else {
1538 // This file does not exist. This means we haven't started our update
1539 // check count down yet, so this is the right time to start the count down.
1540 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001541 params_->min_update_checks_needed(),
1542 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001543
1544 LOG(INFO) << "Randomly picked update check count value = "
1545 << update_check_count_value;
1546
1547 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001548 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1549 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001550 // We weren't able to write the update check count file for some reason.
1551 // So let's proceed anyway so as to not stall the update.
1552 LOG(ERROR) << "Unable to write update check count. "
1553 << "Skipping update-check-count-based-wait.";
1554 return true;
1555 }
1556 }
1557
1558 if (update_check_count_value == 0) {
1559 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1560 return true;
1561 }
1562
1563 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001564 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001565 // We err on the side of skipping scattering logic instead of stalling
1566 // a machine from receiving any updates in case of any unexpected state.
1567 LOG(ERROR) << "Invalid value for update check count detected. "
1568 << "Skipping update-check-count-based-wait.";
1569 return true;
1570 }
1571
1572 // Legal value, we need to wait for more update checks to happen
1573 // until this becomes 0.
1574 LOG(INFO) << "Deferring Omaha updates for another "
1575 << update_check_count_value
1576 << " update checks per policy";
1577 return false;
1578}
1579
David Zeuthen639aa362014-02-03 16:23:44 -08001580// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001581bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001582 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001583 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001584 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001585 &elapsed_days))
1586 return false;
1587
1588 if (elapsed_days < 0)
1589 return false;
1590
1591 output_object->install_date_days = elapsed_days;
1592 return true;
1593}
1594
1595// static
1596bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1597 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001598 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001599 return false;
1600
1601 return prefs->Exists(kPrefsInstallDateDays);
1602}
1603
1604// static
1605bool OmahaRequestAction::PersistInstallDate(
1606 SystemState *system_state,
1607 int install_date_days,
1608 InstallDateProvisioningSource source) {
1609 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1610
1611 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001612 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001613 return false;
1614
1615 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1616 return false;
1617
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001618 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001619 static_cast<int>(source), // Sample.
1620 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001621 return true;
1622}
1623
Alex Deymo8e18f932015-03-27 16:16:59 -07001624bool OmahaRequestAction::PersistCohortData(
1625 const string& prefs_key,
1626 const string& new_value) {
1627 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1628 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1629 return system_state_->prefs()->Delete(prefs_key);
1630 } else if (!new_value.empty()) {
1631 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1632 return system_state_->prefs()->SetString(prefs_key, new_value);
1633 }
1634 return true;
1635}
1636
Alex Deymob3fa53b2016-04-18 19:57:58 -07001637bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
1638 auto eol_attr = attrs.find(kEolAttr);
1639 if (eol_attr != attrs.end()) {
1640 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1641 eol_attr->second);
1642 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1643 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1644 }
1645 return true;
1646}
1647
David Zeuthen33bae492014-02-25 16:16:18 -08001648void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1649 // We only want to report this on "update check".
1650 if (ping_only_ || event_ != nullptr)
1651 return;
1652
1653 metrics::CheckResult result = metrics::CheckResult::kUnset;
1654 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1655 metrics::DownloadErrorCode download_error_code =
1656 metrics::DownloadErrorCode::kUnset;
1657
1658 // Regular update attempt.
1659 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001660 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001661 // OK, we parsed the response successfully but that does
1662 // necessarily mean that an update is available.
1663 if (HasOutputPipe()) {
1664 const OmahaResponse& response = GetOutputObject();
1665 if (response.update_exists) {
1666 result = metrics::CheckResult::kUpdateAvailable;
1667 reaction = metrics::CheckReaction::kUpdating;
1668 } else {
1669 result = metrics::CheckResult::kNoUpdateAvailable;
1670 }
1671 } else {
1672 result = metrics::CheckResult::kNoUpdateAvailable;
1673 }
1674 break;
1675
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001676 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
Weidong Guo421ff332017-04-17 10:08:38 -07001677 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
David Zeuthen33bae492014-02-25 16:16:18 -08001678 result = metrics::CheckResult::kUpdateAvailable;
1679 reaction = metrics::CheckReaction::kIgnored;
1680 break;
1681
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001682 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001683 result = metrics::CheckResult::kUpdateAvailable;
1684 reaction = metrics::CheckReaction::kDeferring;
1685 break;
1686
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001687 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001688 result = metrics::CheckResult::kUpdateAvailable;
1689 reaction = metrics::CheckReaction::kBackingOff;
1690 break;
1691
1692 default:
1693 // We report two flavors of errors, "Download errors" and "Parsing
1694 // error". Try to convert to the former and if that doesn't work
1695 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001696 metrics::DownloadErrorCode tmp_error =
1697 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001698 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1699 result = metrics::CheckResult::kDownloadError;
1700 download_error_code = tmp_error;
1701 } else {
1702 result = metrics::CheckResult::kParsingError;
1703 }
1704 break;
1705 }
1706
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001707 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1708 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001709}
1710
Chris Sosa77f79e82014-06-02 18:16:24 -07001711bool OmahaRequestAction::ShouldIgnoreUpdate(
Weidong Guo421ff332017-04-17 10:08:38 -07001712 ErrorCode* error, const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001713 // Note: policy decision to not update to a version we rolled back from.
1714 string rollback_version =
1715 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001716 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001717 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001718 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001719 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001720 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001721 return true;
1722 }
1723 }
1724
Weidong Guo421ff332017-04-17 10:08:38 -07001725 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001726 LOG(INFO) << "Update is not allowed over current connection.";
1727 return true;
1728 }
1729
1730 // Note: We could technically delete the UpdateFirstSeenAt state when we
1731 // return true. If we do, it'll mean a device has to restart the
1732 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1733 // turned on again. On the other hand, it also increases the chance of update
1734 // starvation if an admin turns AU on/off more frequently. We choose to err on
1735 // the side of preventing starvation at the cost of not applying scattering in
1736 // those cases.
1737 return false;
1738}
1739
Weidong Guo421ff332017-04-17 10:08:38 -07001740bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1741 const OmahaResponse& response) const {
1742 PrefsInterface* prefs = system_state_->prefs();
1743
1744 if (!prefs) {
1745 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1746 "not available.";
1747 return false;
1748 }
1749
1750 bool is_allowed;
1751
1752 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1753 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1754 is_allowed) {
1755 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1756 "set to true.";
1757 return true;
1758 }
1759
1760 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1761 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1762 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1763 "set to false or does not exist while target does not exist.";
1764 return false;
1765 }
1766
1767 std::string target_version;
1768 int64_t target_size;
1769
1770 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1771 &target_version) ||
1772 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1773 LOG(INFO) << "Disabling updates over cellular as the target version or "
1774 "size is not accessible.";
1775 return false;
1776 }
1777
1778 uint64_t total_packages_size = 0;
1779 for (const auto& package : response.packages) {
1780 total_packages_size += package.size;
1781 }
1782 if (target_version == response.version &&
1783 static_cast<uint64_t>(target_size) == total_packages_size) {
1784 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1785 "omaha response.";
1786 return true;
1787 } else {
1788 LOG(INFO) << "Disabling updates over cellular as the target does not"
1789 "match the omaha response.";
1790 return false;
1791 }
1792}
1793
1794bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1795 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001796 ConnectionType type;
1797 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001798 ConnectionManagerInterface* connection_manager =
1799 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001800 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001801 LOG(INFO) << "We could not determine our connection type. "
1802 << "Defaulting to allow updates.";
1803 return true;
1804 }
Weidong Guo421ff332017-04-17 10:08:38 -07001805
Chris Sosa77f79e82014-06-02 18:16:24 -07001806 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001807 bool is_device_policy_set =
1808 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1809 // Treats tethered connection as if it is cellular connection.
1810 bool is_over_cellular = type == ConnectionType::kCellular ||
1811 tethering == ConnectionTethering::kConfirmed;
1812
1813 if (!is_over_cellular) {
1814 // There's no need to further check user preferences as we are not over
1815 // cellular connection.
1816 if (!is_allowed)
1817 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1818 } else if (is_device_policy_set) {
1819 // There's no need to further check user preferences as the device policy
1820 // is set regarding updates over cellular.
1821 if (!is_allowed)
1822 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1823 } else {
1824 // Deivce policy is not set, so user preferences overwrite whether to
1825 // allow updates over cellular.
1826 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1827 if (!is_allowed)
1828 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1829 }
1830
Chris Sosa77f79e82014-06-02 18:16:24 -07001831 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001832 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001833 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1834 return is_allowed;
1835}
1836
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001837bool OmahaRequestAction::IsRollbackEnabled() const {
1838 if (policy_provider_->IsConsumerDevice()) {
1839 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1840 return false;
1841 }
1842
1843 if (!policy_provider_->device_policy_is_loaded()) {
1844 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1845 return true;
1846 }
1847
1848 int allowed_milestones;
1849 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1850 &allowed_milestones)) {
1851 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1852 "Defaulting to rollback enabled.";
1853 return true;
1854 }
1855
1856 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1857 return allowed_milestones > 0;
1858}
1859
1860void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001861 int max_kernel_rollforward;
1862 int min_kernel_version = system_state_->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001863 if (IsRollbackEnabled()) {
1864 // If rollback is enabled, set the max kernel key version to the current
1865 // kernel key version. This has the effect of freezing kernel key roll
1866 // forwards.
1867 //
1868 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1869 // key roll forward happens until the server side components of rollback
1870 // are implemented. Future changes will allow the Omaha server to return
1871 // the kernel key version from max_rollback_versions in the past. At that
1872 // point the max kernel key version will be set to that value, creating a
1873 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001874 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001875 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001876 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001877 } else {
1878 // For devices that are not rollback enabled (ie. consumer devices), the
1879 // max kernel key version is set to 0xfffffffe, which is logically
1880 // infinity. This maintains the previous behavior that that kernel key
1881 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001882 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001883 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001884 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001885 }
1886
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001887 bool max_rollforward_set =
1888 system_state_->hardware()->SetMaxKernelKeyRollforward(
1889 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001890 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001891 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001892 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001893 // Report metrics
1894 system_state_->metrics_reporter()->ReportKeyVersionMetrics(
1895 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001896}
1897
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001898} // namespace chromeos_update_engine