blob: 68099799ffe004a1f3a0960a5339a5ce13584d2f [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";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080081
Alex Deymoac41a822015-09-15 20:52:53 -070082static const char* kOmahaUpdaterVersion = "0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +000083
Sen Jiang42fa45e2018-03-12 11:02:14 -070084// X-Goog-Update headers.
85static const char* kXGoogleUpdateInteractivity = "X-Goog-Update-Interactivity";
86static const char* kXGoogleUpdateAppId = "X-Goog-Update-AppId";
87static const char* kXGoogleUpdateUpdater = "X-Goog-Update-Updater";
Alex Deymo14ad88e2016-06-29 12:30:14 -070088
Alex Deymob3fa53b2016-04-18 19:57:58 -070089// updatecheck attributes (without the underscore prefix).
90static const char* kEolAttr = "eol";
91
Alex Deymoac41a822015-09-15 20:52:53 -070092namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +000093
Darin Petkov1cbd78f2010-07-29 12:38:34 -070094// Returns an XML ping element attribute assignment with attribute
95// |name| and value |ping_days| if |ping_days| has a value that needs
96// to be sent, or an empty string otherwise.
97string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -070098 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -070099 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700100 return "";
101}
102
103// Returns an XML ping element if any of the elapsed days need to be
104// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700105string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700106 string ping_active = GetPingAttribute("a", ping_active_days);
107 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
108 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700109 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700110 ping_active.c_str(),
111 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700112 }
113 return "";
114}
115
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700116// Returns an XML that goes into the body of the <app> element of the Omaha
117// request based on the given parameters.
118string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700119 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700120 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700121 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700122 int ping_active_days,
123 int ping_roll_call_days,
124 PrefsInterface* prefs) {
125 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700126 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700127 if (include_ping)
128 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700129 if (!ping_only) {
Marton Hunyadyba51c3f2018-04-25 15:18:10 +0200130 app_body += " <updatecheck";
131 if (!params->target_version_prefix().empty()) {
132 app_body += base::StringPrintf(
133 " targetversionprefix=\"%s\"",
134 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
135 // Rollback requires target_version_prefix set.
136 if (params->rollback_allowed()) {
137 app_body += " rollback_allowed=\"true\"";
138 }
139 }
140 app_body += "></updatecheck>\n";
Jay Srinivasan0a708742012-03-20 11:26:12 -0700141
Darin Petkov265f2902011-05-09 15:17:40 -0700142 // If this is the first update check after a reboot following a previous
143 // update, generate an event containing the previous version number. If
144 // the previous version preference file doesn't exist the event is still
145 // generated with a previous version of 0.0.0.0 -- this is relevant for
146 // older clients or new installs. The previous version event is not sent
147 // for ping-only requests because they come before the client has
Alex Deymo87c08862015-10-30 21:56:55 -0700148 // rebooted. The previous version event is also not sent if it was already
149 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700150 string prev_version;
151 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
152 prev_version = "0.0.0.0";
153 }
Alex Deymo87c08862015-10-30 21:56:55 -0700154 // We only store a non-empty previous version value after a successful
155 // update in the previous boot. After reporting it back to the server,
156 // we clear the previous version value so it doesn't get reported again.
157 if (!prev_version.empty()) {
158 app_body += base::StringPrintf(
159 " <event eventtype=\"%d\" eventresult=\"%d\" "
160 "previousversion=\"%s\"></event>\n",
Alex Deymo9fded1e2015-11-05 12:31:19 -0800161 OmahaEvent::kTypeRebootedAfterUpdate,
162 OmahaEvent::kResultSuccess,
Alex Deymo87c08862015-10-30 21:56:55 -0700163 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
164 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
165 << "Unable to reset the previous version.";
166 }
Darin Petkov95508da2011-01-05 12:42:29 -0800167 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700168 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800169 // The error code is an optional attribute so append it only if the result
170 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700171 string error_code;
172 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700173 error_code = base::StringPrintf(" errorcode=\"%d\"",
174 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700175 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700176 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700177 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700178 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700179 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700180
181 return app_body;
182}
183
Alex Deymo8e18f932015-03-27 16:16:59 -0700184// Returns the cohort* argument to include in the <app> tag for the passed
185// |arg_name| and |prefs_key|, if any. The return value is suitable to
186// concatenate to the list of arguments and includes a space at the end.
187string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700188 const string arg_name,
189 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700190 // There's nothing wrong with not having a given cohort setting, so we check
191 // existance first to avoid the warning log message.
192 if (!prefs->Exists(prefs_key))
193 return "";
194 string cohort_value;
195 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
196 return "";
197 // This is a sanity check to avoid sending a huge XML file back to Ohama due
198 // to a compromised stateful partition making the update check fail in low
199 // network environments envent after a reboot.
200 if (cohort_value.size() > 1024) {
201 LOG(WARNING) << "The omaha cohort setting " << arg_name
202 << " has a too big value, which must be an error or an "
203 "attacker trying to inhibit updates.";
204 return "";
205 }
206
Alex Deymob0d74eb2015-03-30 17:59:17 -0700207 string escaped_xml_value;
208 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
209 LOG(WARNING) << "The omaha cohort setting " << arg_name
210 << " is ASCII-7 invalid, ignoring it.";
211 return "";
212 }
213
Alex Deymo8e18f932015-03-27 16:16:59 -0700214 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700215 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700216}
217
Sen Jiang94a4dec2017-03-28 18:23:35 -0700218struct OmahaAppData {
219 string id;
220 string version;
Sen Jiang684c9cd2017-10-17 16:26:45 -0700221 string product_components;
Sen Jiang94a4dec2017-03-28 18:23:35 -0700222};
223
Sen Jiang684c9cd2017-10-17 16:26:45 -0700224bool IsValidComponentID(const string& id) {
225 for (char c : id) {
226 if (!isalnum(c) && c != '-' && c != '_' && c != '.')
227 return false;
228 }
229 return true;
230}
231
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700232// Returns an XML that corresponds to the entire <app> node of the Omaha
233// request based on the given parameters.
234string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700235 OmahaRequestParams* params,
Sen Jiang94a4dec2017-03-28 18:23:35 -0700236 const OmahaAppData& app_data,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700237 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700238 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700239 int ping_active_days,
240 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800241 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700242 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700243 string app_body = GetAppBody(event, params, ping_only, include_ping,
244 ping_active_days, ping_roll_call_days,
245 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700246 string app_versions;
247
Sen Jiang8cd42342018-01-31 12:06:59 -0800248 // If we are downgrading to a more stable channel and we are allowed to do
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700249 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
250 // highest-versioned payload on the destination channel.
Sen Jiang8500d3a2018-02-08 12:04:05 -0800251 if (params->ShouldPowerwash()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700252 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
253 << "on downgrading to the version in the more stable channel";
254 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700255 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700256 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700257 app_versions = "version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700258 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700259 }
260
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700261 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700262 string app_channels =
263 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
264 if (params->current_channel() != download_channel) {
265 app_channels += "from_track=\"" + XmlEncodeWithDefault(
266 params->current_channel(), "") + "\" ";
267 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700268
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700269 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700270
David Zeuthen639aa362014-02-03 16:23:44 -0800271 // If install_date_days is not set (e.g. its value is -1 ), don't
272 // include the attribute.
273 string install_date_in_days_str = "";
274 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700275 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
276 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800277 }
278
Alex Deymo8e18f932015-03-27 16:16:59 -0700279 string app_cohort_args;
280 app_cohort_args += GetCohortArgXml(system_state->prefs(),
281 "cohort", kPrefsOmahaCohort);
282 app_cohort_args += GetCohortArgXml(system_state->prefs(),
283 "cohorthint", kPrefsOmahaCohortHint);
284 app_cohort_args += GetCohortArgXml(system_state->prefs(),
285 "cohortname", kPrefsOmahaCohortName);
286
Alex Deymoebf6e122017-03-10 16:12:01 -0800287 string fingerprint_arg;
288 if (!params->os_build_fingerprint().empty()) {
Sen Jiang8cd42342018-01-31 12:06:59 -0800289 fingerprint_arg = "fingerprint=\"" +
290 XmlEncodeWithDefault(params->os_build_fingerprint(), "") +
291 "\" ";
Alex Deymoebf6e122017-03-10 16:12:01 -0800292 }
293
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700294 string buildtype_arg;
295 if (!params->os_build_type().empty()) {
296 buildtype_arg = "os_build_type=\"" +
297 XmlEncodeWithDefault(params->os_build_type(), "") + "\" ";
298 }
299
Sen Jiang684c9cd2017-10-17 16:26:45 -0700300 string product_components_args;
Sen Jiang8500d3a2018-02-08 12:04:05 -0800301 if (!params->ShouldPowerwash() && !app_data.product_components.empty()) {
Sen Jiang684c9cd2017-10-17 16:26:45 -0700302 brillo::KeyValueStore store;
303 if (store.LoadFromString(app_data.product_components)) {
304 for (const string& key : store.GetKeys()) {
305 if (!IsValidComponentID(key)) {
306 LOG(ERROR) << "Invalid component id: " << key;
307 continue;
308 }
309 string version;
310 if (!store.GetString(key, &version)) {
311 LOG(ERROR) << "Failed to get version for " << key
312 << " in product_components.";
313 continue;
314 }
315 product_components_args +=
316 base::StringPrintf("_%s.version=\"%s\" ",
317 key.c_str(),
318 XmlEncodeWithDefault(version, "").c_str());
319 }
320 } else {
321 LOG(ERROR) << "Failed to parse product_components:\n"
322 << app_data.product_components;
323 }
324 }
325
326 // clang-format off
Alex Deymob0d74eb2015-03-30 17:59:17 -0700327 string app_xml = " <app "
Sen Jiang94a4dec2017-03-28 18:23:35 -0700328 "appid=\"" + XmlEncodeWithDefault(app_data.id, "") + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700329 app_cohort_args +
330 app_versions +
331 app_channels +
Sen Jiang684c9cd2017-10-17 16:26:45 -0700332 product_components_args +
Alex Deymoebf6e122017-03-10 16:12:01 -0800333 fingerprint_arg +
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700334 buildtype_arg +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700335 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
336 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
337 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
338 "delta_okay=\"" + delta_okay_str + "\" "
339 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
340 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
341 install_date_in_days_str +
342 ">\n" +
343 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700344 " </app>\n";
Sen Jiang684c9cd2017-10-17 16:26:45 -0700345 // clang-format on
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700346 return app_xml;
347}
348
349// Returns an XML that corresponds to the entire <os> node of the Omaha
350// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700351string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700352 string os_xml =" <os "
353 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
354 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
355 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
356 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700357 return os_xml;
358}
359
360// Returns an XML that corresponds to the entire Omaha request based on the
361// given parameters.
362string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700363 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700364 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700365 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700366 int ping_active_days,
367 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800368 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700369 SystemState* system_state) {
370 string os_xml = GetOsXml(params);
Sen Jiang684c9cd2017-10-17 16:26:45 -0700371 OmahaAppData product_app = {
372 .id = params->GetAppId(),
373 .version = params->app_version(),
374 .product_components = params->product_components()};
Sen Jiang94a4dec2017-03-28 18:23:35 -0700375 string app_xml = GetAppXml(event,
376 params,
377 product_app,
378 ping_only,
379 include_ping,
380 ping_active_days,
381 ping_roll_call_days,
382 install_date_in_days,
383 system_state);
384 if (!params->system_app_id().empty()) {
385 OmahaAppData system_app = {.id = params->system_app_id(),
386 .version = params->system_version()};
387 app_xml += GetAppXml(event,
388 params,
389 system_app,
390 ping_only,
391 include_ping,
392 ping_active_days,
393 ping_roll_call_days,
394 install_date_in_days,
395 system_state);
396 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700397
Alex Vakulenko75039d72014-03-25 12:36:28 -0700398 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700399 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700400
Alex Deymoac41a822015-09-15 20:52:53 -0700401 string updater_version = XmlEncodeWithDefault(
402 base::StringPrintf("%s-%s",
403 constants::kOmahaUpdaterID,
404 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700405 string request_xml =
406 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700407 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700408 "version=\"" + updater_version + "\" "
409 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700410 install_source +
411 "ismachine=\"1\">\n") +
412 os_xml +
413 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700414 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700415
416 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000417}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700418
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700419} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000420
David Zeuthene8ed8632014-07-24 13:38:10 -0400421// Struct used for holding data obtained when parsing the XML.
422struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400423 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
424
425 // Pointer to the expat XML_Parser object.
426 XML_Parser xml_parser;
427
David Zeuthene8ed8632014-07-24 13:38:10 -0400428 // This is the state of the parser as it's processing the XML.
429 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400430 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400431 string current_path;
432
433 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400434 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700435 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400436 string daystart_elapsed_days;
437 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800438
Sen Jiang81259682017-03-30 15:11:30 -0700439 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700440 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700441 vector<string> url_codebase;
442 string manifest_version;
443 map<string, string> action_postinstall_attrs;
444 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700445 string cohort;
446 string cohorthint;
447 string cohortname;
448 bool cohort_set = false;
449 bool cohorthint_set = false;
450 bool cohortname_set = false;
Sen Jiang81259682017-03-30 15:11:30 -0700451
452 struct Package {
453 string name;
454 string size;
455 string hash;
456 };
457 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800458 };
Sen Jiang81259682017-03-30 15:11:30 -0700459 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400460};
461
462namespace {
463
464// Callback function invoked by expat.
465void ParserHandlerStart(void* user_data, const XML_Char* element,
466 const XML_Char** attr) {
467 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
468
469 if (data->failed)
470 return;
471
472 data->current_path += string("/") + element;
473
474 map<string, string> attrs;
475 if (attr != nullptr) {
476 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
477 string key = attr[n];
478 string value = attr[n + 1];
479 attrs[key] = value;
480 }
481 }
482
Alex Deymo8e18f932015-03-27 16:16:59 -0700483 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700484 OmahaParserData::App app;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700485 if (attrs.find("appid") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700486 app.id = attrs["appid"];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700487 }
Alex Deymo8e18f932015-03-27 16:16:59 -0700488 if (attrs.find("cohort") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700489 app.cohort_set = true;
490 app.cohort = attrs["cohort"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700491 }
492 if (attrs.find("cohorthint") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700493 app.cohorthint_set = true;
494 app.cohorthint = attrs["cohorthint"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700495 }
496 if (attrs.find("cohortname") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700497 app.cohortname_set = true;
498 app.cohortname = attrs["cohortname"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700499 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700500 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700501 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700502 if (!data->apps.empty())
503 data->apps.back().updatecheck_status = attrs["status"];
504 if (data->updatecheck_poll_interval.empty())
505 data->updatecheck_poll_interval = attrs["PollInterval"];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700506 // Omaha sends arbitrary key-value pairs as extra attributes starting with
507 // an underscore.
508 for (const auto& attr : attrs) {
509 if (!attr.first.empty() && attr.first[0] == '_')
510 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
511 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400512 } else if (data->current_path == "/response/daystart") {
513 // Get the install-date.
514 data->daystart_elapsed_days = attrs["elapsed_days"];
515 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
516 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
517 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700518 if (!data->apps.empty())
519 data->apps.back().url_codebase.push_back(attrs["codebase"]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800520 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400521 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800522 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700523 if (!data->apps.empty())
524 data->apps.back().packages.push_back({.name = attrs["name"],
525 .size = attrs["size"],
526 .hash = attrs["hash_sha256"]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400527 } else if (data->current_path == "/response/app/updatecheck/manifest") {
528 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700529 if (!data->apps.empty())
530 data->apps.back().manifest_version = attrs[kTagVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400531 } else if (data->current_path ==
532 "/response/app/updatecheck/manifest/actions/action") {
533 // We only care about the postinstall action.
Sen Jiang81259682017-03-30 15:11:30 -0700534 if (attrs["event"] == "postinstall" && !data->apps.empty()) {
535 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400536 }
537 }
538}
539
540// Callback function invoked by expat.
541void ParserHandlerEnd(void* user_data, const XML_Char* element) {
542 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
543 if (data->failed)
544 return;
545
546 const string path_suffix = string("/") + element;
547
Alex Vakulenko0103c362016-01-20 07:56:15 -0800548 if (!base::EndsWith(data->current_path, path_suffix,
549 base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400550 LOG(ERROR) << "Unexpected end element '" << element
551 << "' with current_path='" << data->current_path << "'";
552 data->failed = true;
553 return;
554 }
555 data->current_path.resize(data->current_path.size() - path_suffix.size());
556}
557
David Zeuthenf3e28012014-08-26 18:23:52 -0400558// Callback function invoked by expat.
559//
560// This is called for entity declarations. Since Omaha is guaranteed
561// to never return any XML with entities our course of action is to
562// just stop parsing. This avoids potential resource exhaustion
563// problems AKA the "billion laughs". CVE-2013-0340.
564void ParserHandlerEntityDecl(void *user_data,
565 const XML_Char *entity_name,
566 int is_parameter_entity,
567 const XML_Char *value,
568 int value_length,
569 const XML_Char *base,
570 const XML_Char *system_id,
571 const XML_Char *public_id,
572 const XML_Char *notation_name) {
573 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
574
575 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
576 data->failed = true;
577 data->entity_decl = true;
578 XML_StopParser(data->xml_parser, false);
579}
580
David Zeuthene8ed8632014-07-24 13:38:10 -0400581} // namespace
582
Alex Deymob0d74eb2015-03-30 17:59:17 -0700583bool XmlEncode(const string& input, string* output) {
584 if (std::find_if(input.begin(), input.end(),
585 [](const char c){return c & 0x80;}) != input.end()) {
586 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
587 utils::HexDumpString(input);
588 return false;
589 }
Alex Deymocc457852015-06-18 18:35:50 -0700590 output->clear();
591 // We need at least input.size() space in the output, but the code below will
592 // handle it if we need more.
593 output->reserve(input.size());
594 for (char c : input) {
595 switch (c) {
596 case '\"':
597 output->append("&quot;");
598 break;
599 case '\'':
600 output->append("&apos;");
601 break;
602 case '&':
603 output->append("&amp;");
604 break;
605 case '<':
606 output->append("&lt;");
607 break;
608 case '>':
609 output->append("&gt;");
610 break;
611 default:
612 output->push_back(c);
613 }
614 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700615 return true;
616}
617
618string XmlEncodeWithDefault(const string& input, const string& default_value) {
619 string output;
620 if (XmlEncode(input, &output))
621 return output;
622 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000623}
624
Alex Deymoc1c17b42015-11-23 03:53:15 -0300625OmahaRequestAction::OmahaRequestAction(
626 SystemState* system_state,
627 OmahaEvent* event,
628 std::unique_ptr<HttpFetcher> http_fetcher,
629 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800630 : system_state_(system_state),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800631 params_(system_state->request_params()),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700632 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300633 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800634 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700635 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700636 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700637 ping_roll_call_days_(0) {
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800638 policy_provider_->Reload();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700639}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000640
Darin Petkov6a5b3222010-07-13 14:55:28 -0700641OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000642
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700643// Calculates the value to use for the ping days parameter.
644int OmahaRequestAction::CalculatePingDays(const string& key) {
645 int days = kNeverPinged;
646 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800647 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700648 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
649 if (days < 0) {
650 // If |days| is negative, then the system clock must have jumped
651 // back in time since the ping was sent. Mark the value so that
652 // it doesn't get sent to the server but we still update the
653 // last ping daystart preference. This way the next ping time
654 // will be correct, hopefully.
655 days = kPingTimeJump;
656 LOG(WARNING) <<
657 "System clock jumped back in time. Resetting ping daystarts.";
658 }
659 }
660 return days;
661}
662
663void OmahaRequestAction::InitPingDays() {
664 // We send pings only along with update checks, not with events.
665 if (IsEvent()) {
666 return;
667 }
668 // TODO(petkov): Figure a way to distinguish active use pings
669 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700670 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700671 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
672 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
673}
674
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700675bool OmahaRequestAction::ShouldPing() const {
676 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
677 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
678 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
679 if (powerwash_count > 0) {
680 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
681 << "powerwash_count is " << powerwash_count;
682 return false;
683 }
Amin Hassani1677e812017-06-21 13:36:36 -0700684 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
685 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
686 << "the first_active_omaha_ping_sent is true";
687 return false;
688 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700689 return true;
690 }
691 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
692}
693
David Zeuthen639aa362014-02-03 16:23:44 -0800694// static
695int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
696 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700697 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800698 return -1;
699
700 // If we have the value stored on disk, just return it.
701 int64_t stored_value;
702 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
703 // Convert and sanity-check.
704 int install_date_days = static_cast<int>(stored_value);
705 if (install_date_days >= 0)
706 return install_date_days;
707 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
708 << install_date_days << " looks suspicious.";
709 prefs->Delete(kPrefsInstallDateDays);
710 }
711
712 // Otherwise, if OOBE is not complete then do nothing and wait for
713 // ParseResponse() to call ParseInstallDate() and then
714 // PersistInstallDate() to set the kPrefsInstallDateDays state
715 // variable. Once that is done, we'll then report back in future
716 // Omaha requests. This works exactly because OOBE triggers an
717 // update check.
718 //
719 // However, if OOBE is complete and the kPrefsInstallDateDays state
720 // variable is not set, there are two possibilities
721 //
722 // 1. The update check in OOBE failed so we never got a response
723 // from Omaha (no network etc.); or
724 //
725 // 2. OOBE was done on an older version that didn't write to the
726 // kPrefsInstallDateDays state variable.
727 //
728 // In both cases, we approximate the install date by simply
729 // inspecting the timestamp of when OOBE happened.
730
731 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700732 if (!system_state->hardware()->IsOOBEEnabled() ||
733 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800734 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700735 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800736 return -1;
737 }
738
739 int num_days;
740 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
741 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
742 << "as its value '" << utils::ToString(time_of_oobe)
743 << "' looks suspicious.";
744 return -1;
745 }
746
747 // Persist this to disk, for future use.
748 if (!OmahaRequestAction::PersistInstallDate(system_state,
749 num_days,
750 kProvisionedFromOOBEMarker))
751 return -1;
752
753 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
754 << num_days << " days";
755
756 return num_days;
757}
758
Darin Petkov6a5b3222010-07-13 14:55:28 -0700759void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000760 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700761 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700762 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700763 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700764 return;
765 }
David Zeuthen639aa362014-02-03 16:23:44 -0800766
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700767 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700768 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700769 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700770 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700771 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800772 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800773 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700774 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700775
Sen Jiang42fa45e2018-03-12 11:02:14 -0700776 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700777 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
778 params_->interactive() ? "fg" : "bg");
779 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
780 http_fetcher_->SetHeader(
781 kXGoogleUpdateUpdater,
782 base::StringPrintf(
783 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
784
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800785 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
786 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700787 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700788 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700789 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000790}
791
Darin Petkov6a5b3222010-07-13 14:55:28 -0700792void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000793 http_fetcher_->TerminateTransfer();
794}
795
796// We just store the response in the buffer. Once we've received all bytes,
797// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700798void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800799 const void* bytes,
800 size_t length) {
801 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
802 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000803}
804
805namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000806
807// Parses a 64 bit base-10 int from a string and returns it. Returns 0
808// on error. If the string contains "0", that's indistinguishable from
809// error.
810off_t ParseInt(const string& str) {
811 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700812 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000813 if (rc < 1) {
814 // failure
815 return 0;
816 }
817 return ret;
818}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700819
David Zeuthene8ed8632014-07-24 13:38:10 -0400820// Parses |str| and returns |true| if, and only if, its value is "true".
821bool ParseBool(const string& str) {
822 return str == "true";
823}
824
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700825// Update the last ping day preferences based on the server daystart
826// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400827bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700828 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400829 TEST_AND_RETURN_FALSE(
830 base::StringToInt64(parser_data->daystart_elapsed_seconds,
831 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700832 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
833
834 // Remember the local time that matches the server's last midnight
835 // time.
836 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
837 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
838 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
839 return true;
840}
Sen Jiang81259682017-03-30 15:11:30 -0700841
842// Parses the package node in the given XML document and populates
843// |output_object| if valid. Returns true if we should continue the parsing.
844// False otherwise, in which case it sets any error code using |completer|.
845bool ParsePackage(OmahaParserData::App* app,
846 OmahaResponse* output_object,
847 ScopedActionCompleter* completer) {
848 if (app->updatecheck_status == "noupdate") {
849 if (!app->packages.empty()) {
850 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
851 completer->set_code(ErrorCode::kOmahaResponseInvalid);
852 return false;
853 }
854 return true;
855 }
856 if (app->packages.empty()) {
857 LOG(ERROR) << "Omaha Response has no packages";
858 completer->set_code(ErrorCode::kOmahaResponseInvalid);
859 return false;
860 }
861 if (app->url_codebase.empty()) {
862 LOG(ERROR) << "No Omaha Response URLs";
863 completer->set_code(ErrorCode::kOmahaResponseInvalid);
864 return false;
865 }
866 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
867 vector<string> metadata_sizes =
868 base::SplitString(app->action_postinstall_attrs[kTagMetadataSize],
869 ":",
870 base::TRIM_WHITESPACE,
871 base::SPLIT_WANT_ALL);
872 vector<string> metadata_signatures =
873 base::SplitString(app->action_postinstall_attrs[kTagMetadataSignatureRsa],
874 ":",
875 base::TRIM_WHITESPACE,
876 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700877 vector<string> is_delta_payloads =
878 base::SplitString(app->action_postinstall_attrs[kTagIsDeltaPayload],
879 ":",
880 base::TRIM_WHITESPACE,
881 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700882 for (size_t i = 0; i < app->packages.size(); i++) {
883 const auto& package = app->packages[i];
884 if (package.name.empty()) {
885 LOG(ERROR) << "Omaha Response has empty package name";
886 completer->set_code(ErrorCode::kOmahaResponseInvalid);
887 return false;
888 }
889 LOG(INFO) << "Found package " << package.name;
890
891 OmahaResponse::Package out_package;
892 for (const string& codebase : app->url_codebase) {
893 if (codebase.empty()) {
894 LOG(ERROR) << "Omaha Response URL has empty codebase";
895 completer->set_code(ErrorCode::kOmahaResponseInvalid);
896 return false;
897 }
898 out_package.payload_urls.push_back(codebase + package.name);
899 }
900 // Parse the payload size.
901 base::StringToUint64(package.size, &out_package.size);
902 if (out_package.size <= 0) {
903 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
904 completer->set_code(ErrorCode::kOmahaResponseInvalid);
905 return false;
906 }
907 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
908
909 if (i < metadata_sizes.size())
910 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
911 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
912 << " bytes";
913
914 if (i < metadata_signatures.size())
915 out_package.metadata_signature = metadata_signatures[i];
916 LOG(INFO) << "Payload metadata signature = "
917 << out_package.metadata_signature;
918
919 out_package.hash = package.hash;
920 if (out_package.hash.empty()) {
921 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
922 completer->set_code(ErrorCode::kOmahaResponseInvalid);
923 return false;
924 }
925 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700926
927 if (i < is_delta_payloads.size())
928 out_package.is_delta = ParseBool(is_delta_payloads[i]);
929 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
930
Sen Jiang81259682017-03-30 15:11:30 -0700931 output_object->packages.push_back(std::move(out_package));
932 }
933
934 return true;
935}
936
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700937} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000938
David Zeuthene8ed8632014-07-24 13:38:10 -0400939bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700940 OmahaResponse* output_object,
941 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700942 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700943 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700944 return false;
945 }
Sen Jiang81259682017-03-30 15:11:30 -0700946 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700947
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800948 // chromium-os:37289: The PollInterval is not supported by Omaha server
949 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700950 // slow down the request rate from the server-side. Note that the PollInterval
951 // is not persisted, so it has to be sent by the server on every response to
952 // guarantee that the scheduler uses this value (otherwise, if the device got
953 // rebooted after the last server-indicated value, it'll revert to the default
954 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
955 // based on the assumption that we perform an update check every hour so that
956 // the max value of 8 will roughly be equivalent to one work day. If we decide
957 // to use PollInterval permanently, we should update the
958 // max_update_checks_allowed to take PollInterval into account. Note: The
959 // parsing for PollInterval happens even before parsing of the status because
960 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400961 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700962 &output_object->poll_interval);
963
David Zeuthen639aa362014-02-03 16:23:44 -0800964 // Check for the "elapsed_days" attribute in the "daystart"
965 // element. This is the number of days since Jan 1 2007, 0:00
966 // PST. If we don't have a persisted value of the Omaha InstallDate,
967 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400968 if (ParseInstallDate(parser_data, output_object) &&
969 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800970 // Since output_object->install_date_days is never negative, the
971 // elapsed_days -> install-date calculation is reduced to simply
972 // rounding down to the nearest number divisible by 7.
973 int remainder = output_object->install_date_days % 7;
974 int install_date_days_rounded =
975 output_object->install_date_days - remainder;
976 if (PersistInstallDate(system_state_,
977 install_date_days_rounded,
978 kProvisionedFromOmahaResponse)) {
979 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
980 << install_date_days_rounded << " days";
981 }
982 }
983
Alex Deymo00d79ac2015-06-29 15:41:49 -0700984 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -0700985 for (const auto& app : parser_data->apps) {
986 if (app.id == params_->GetAppId()) {
987 if (app.cohort_set)
988 PersistCohortData(kPrefsOmahaCohort, app.cohort);
989 if (app.cohorthint_set)
990 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
991 if (app.cohortname_set)
992 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
993 break;
994 }
995 }
Alex Deymo00d79ac2015-06-29 15:41:49 -0700996
Alex Deymob3fa53b2016-04-18 19:57:58 -0700997 // Parse the updatecheck attributes.
998 PersistEolStatus(parser_data->updatecheck_attrs);
999
David Zeuthene8ed8632014-07-24 13:38:10 -04001000 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001001 return false;
1002
David Zeuthene8ed8632014-07-24 13:38:10 -04001003 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001004 return false;
1005
Sen Jiang0affc2c2017-02-10 15:55:05 -08001006 // Package has to be parsed after Params now because ParseParams need to make
1007 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -07001008 for (auto& app : parser_data->apps)
1009 if (!ParsePackage(&app, output_object, completer))
1010 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001011
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001012 return true;
1013}
1014
David Zeuthene8ed8632014-07-24 13:38:10 -04001015bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001016 OmahaResponse* output_object,
1017 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001018 output_object->update_exists = false;
1019 for (size_t i = 0; i < parser_data->apps.size(); i++) {
1020 const string& status = parser_data->apps[i].updatecheck_status;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001021 if (status == "noupdate") {
1022 // Don't update if any app has status="noupdate".
Sen Jiang81259682017-03-30 15:11:30 -07001023 LOG(INFO) << "No update for <app> " << i;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001024 output_object->update_exists = false;
1025 break;
Sen Jiang81259682017-03-30 15:11:30 -07001026 } else if (status == "ok") {
Sen Jiang00adf7b2017-06-26 15:57:29 -07001027 if (parser_data->apps[i].action_postinstall_attrs["noupdate"] == "true") {
1028 // noupdate="true" in postinstall attributes means it's an update to
1029 // self, only update if there's at least one app really have update.
1030 LOG(INFO) << "Update to self for <app> " << i;
1031 } else {
1032 LOG(INFO) << "Update for <app> " << i;
1033 output_object->update_exists = true;
1034 }
Sen Jiang81259682017-03-30 15:11:30 -07001035 } else {
1036 LOG(ERROR) << "Unknown Omaha response status: " << status;
1037 completer->set_code(ErrorCode::kOmahaResponseInvalid);
1038 return false;
1039 }
1040 }
1041 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001042 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001043 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001044 }
1045
Sen Jiang81259682017-03-30 15:11:30 -07001046 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001047}
1048
David Zeuthene8ed8632014-07-24 13:38:10 -04001049bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001050 OmahaResponse* output_object,
1051 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001052 map<string, string> attrs;
1053 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001054 if (app.id == params_->GetAppId()) {
1055 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -07001056 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001057 } else if (!params_->system_app_id().empty() &&
1058 app.id == params_->system_app_id()) {
1059 // this is the system app (this check is intentionally skipped if there is
1060 // no system_app_id set)
1061 output_object->system_version = app.manifest_version;
1062 }
1063 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -07001064 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001065 }
Sen Jiang81259682017-03-30 15:11:30 -07001066 }
Chris Sosa3b748432013-06-20 16:42:59 -07001067 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -07001068 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001069 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -07001070 return false;
1071 }
1072
1073 LOG(INFO) << "Received omaha response to update to version "
1074 << output_object->version;
1075
David Zeuthene8ed8632014-07-24 13:38:10 -04001076 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001077 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001078 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001079 return false;
1080 }
1081
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001082 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -04001083 output_object->more_info_url = attrs[kTagMoreInfo];
David Zeuthene8ed8632014-07-24 13:38:10 -04001084 output_object->prompt = ParseBool(attrs[kTagPrompt]);
1085 output_object->deadline = attrs[kTagDeadline];
1086 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001087 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -04001088 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001089 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -04001090 ParseBool(attrs[kTagDisableP2PForSharing]);
1091 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001092
David Zeuthene8ed8632014-07-24 13:38:10 -04001093 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -08001094 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001095 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001096
Jay Srinivasan08262882012-12-28 19:29:43 -08001097 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -04001098 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -08001099
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001100 return true;
1101}
1102
David Zeuthene8ed8632014-07-24 13:38:10 -04001103// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +00001104// and fill in the appropriate fields of the output object. Also, notifies
1105// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -07001106void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
1107 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +00001108 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001109 string current_response(response_buffer_.begin(), response_buffer_.end());
1110 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001111
Gilad Arnold74b5f552014-10-07 08:17:16 -07001112 PayloadStateInterface* const payload_state = system_state_->payload_state();
1113
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001114 // Events are best effort transactions -- assume they always succeed.
1115 if (IsEvent()) {
1116 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001117 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001118 return;
1119 }
1120
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001121 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001122 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -07001123 int code = GetHTTPResponseCode();
1124 // Makes sure we send sane error values.
1125 if (code < 0 || code >= 1000) {
1126 code = 999;
1127 }
David Zeuthena99981f2013-04-29 13:42:47 -07001128 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001129 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +00001130 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001131 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001132
David Zeuthene8ed8632014-07-24 13:38:10 -04001133 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -04001134 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -04001135 XML_SetUserData(parser, &parser_data);
1136 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -04001137 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001138 XML_Status res = XML_Parse(
1139 parser,
1140 reinterpret_cast<const char*>(response_buffer_.data()),
1141 response_buffer_.size(),
1142 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -04001143 XML_ParserFree(parser);
1144
1145 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -07001146 LOG(ERROR) << "Omaha response not valid XML: "
1147 << XML_ErrorString(XML_GetErrorCode(parser))
1148 << " at line " << XML_GetCurrentLineNumber(parser)
1149 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -04001150 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
1151 if (response_buffer_.empty()) {
1152 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
1153 } else if (parser_data.entity_decl) {
1154 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
1155 }
1156 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001157 return;
1158 }
1159
Alex Deymoebbe7ef2014-10-30 13:02:49 -07001160 // Update the last ping day preferences based on the server daystart response
1161 // even if we didn't send a ping. Omaha always includes the daystart in the
1162 // response, but log the error if it didn't.
1163 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
1164 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -07001165
Amin Hassani1677e812017-06-21 13:36:36 -07001166 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
1167 // we have got a response from omaha and if its value has never been set to
1168 // true before. Failure of this function should be ignored. There should be no
1169 // need to check if a=-1 has been sent because older devices have already sent
1170 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
1171 // future checks.
1172 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
1173 system_state_->hardware()->SetFirstActiveOmahaPingSent();
1174 }
1175
Thieu Le116fda32011-04-19 11:01:54 -07001176 if (!HasOutputPipe()) {
1177 // Just set success to whether or not the http transfer succeeded,
1178 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001179 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001180 return;
1181 }
1182
Darin Petkov6a5b3222010-07-13 14:55:28 -07001183 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001184 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001185 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001186 output_object.update_exists = true;
1187 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001188
Weidong Guo421ff332017-04-17 10:08:38 -07001189 ErrorCode error = ErrorCode::kSuccess;
1190 if (ShouldIgnoreUpdate(&error, output_object)) {
1191 // No need to change output_object.update_exists here, since the value
1192 // has been output to the pipe.
1193 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001194 return;
1195 }
1196
David Zeuthen8f191b22013-08-06 12:27:50 -07001197 // If Omaha says to disable p2p, respect that
1198 if (output_object.disable_p2p_for_downloading) {
1199 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1200 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001201 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001202 }
1203 if (output_object.disable_p2p_for_sharing) {
1204 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1205 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001206 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001207 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001208
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001209 // Set the max kernel key version based on whether rollback is allowed.
1210 SetMaxKernelKeyVersionForRollback();
1211
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001212 // Update the payload state with the current response. The payload state
1213 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001214 // from what's stored already. We are updating the payload state as late
1215 // as possible in this method so that if a new release gets pushed and then
1216 // got pulled back due to some issues, we don't want to clear our internal
1217 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001218 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001219
David Zeuthen8f191b22013-08-06 12:27:50 -07001220 // It could be we've already exceeded the deadline for when p2p is
1221 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001222 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001223 payload_state->P2PNewAttempt();
1224 if (!payload_state->P2PAttemptAllowed()) {
1225 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1226 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001227 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001228 }
1229 }
1230
1231 // From here on, we'll complete stuff in CompleteProcessing() so
1232 // disable |completer| since we'll create a new one in that
1233 // function.
1234 completer.set_should_complete(false);
1235
1236 // If we're allowed to use p2p for downloading we do not pay
1237 // attention to wall-clock-based waiting if the URL is indeed
1238 // available via p2p. Therefore, check if the file is available via
1239 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001240 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001241 LookupPayloadViaP2P(output_object);
1242 } else {
1243 CompleteProcessing();
1244 }
1245}
1246
1247void OmahaRequestAction::CompleteProcessing() {
1248 ScopedActionCompleter completer(processor_, this);
1249 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1250 PayloadStateInterface* payload_state = system_state_->payload_state();
1251
Alex Deymo46a9aae2016-05-04 20:20:11 -07001252 if (system_state_->hardware()->IsOOBEEnabled() &&
1253 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
Kevin Cernekeec5081a82016-04-08 12:29:52 -07001254 output_object.deadline.empty() &&
1255 params_->app_version() != "ForcedUpdate") {
Kevin Cernekee2494e282016-03-29 18:03:53 -07001256 output_object.update_exists = false;
1257 LOG(INFO) << "Ignoring non-critical Omaha updates until OOBE is done.";
1258 completer.set_code(ErrorCode::kNonCriticalUpdateInOOBE);
1259 return;
1260 }
1261
David Zeuthen8f191b22013-08-06 12:27:50 -07001262 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001263 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001264 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001265 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001266 return;
1267 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001268
Chris Sosa20f005c2013-09-05 13:53:08 -07001269 if (payload_state->ShouldBackoffDownload()) {
1270 output_object.update_exists = false;
1271 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1272 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001273 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001274 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001275 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001276 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001277}
1278
1279void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1280 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1281 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001282 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001283 } else {
1284 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1285 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001286 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001287 }
1288 CompleteProcessing();
1289}
1290
1291void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001292 // If the device is in the middle of an update, the state variables
1293 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1294 // tracks the offset and length of the operation currently in
1295 // progress. The offset is based from the end of the manifest which
1296 // is kPrefsManifestMetadataSize bytes long.
1297 //
1298 // To make forward progress and avoid deadlocks, we need to find a
1299 // peer that has at least the entire operation we're currently
1300 // working on. Otherwise we may end up in a situation where two
1301 // devices bounce back and forth downloading from each other,
1302 // neither making any forward progress until one of them decides to
1303 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1304 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001305 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001306 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001307 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001308 int64_t next_data_offset = 0;
1309 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001310 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001311 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1312 &manifest_metadata_size) &&
1313 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001314 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1315 &manifest_signature_size) &&
1316 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001317 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001318 &next_data_offset) &&
1319 next_data_offset != -1 &&
1320 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1321 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001322 minimum_size = manifest_metadata_size + manifest_signature_size +
1323 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001324 }
1325
Sen Jiang0affc2c2017-02-10 15:55:05 -08001326 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001327 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001328 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001329 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001330 string file_id =
1331 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001332 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001333 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1334 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001335 system_state_->p2p_manager()->LookupUrlForFile(
1336 file_id,
1337 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001338 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001339 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1340 base::Unretained(this)));
1341 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001342}
1343
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001344bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001345 if (params_->interactive()) {
1346 LOG(INFO) << "Not deferring download because update is interactive.";
1347 return false;
1348 }
1349
David Zeuthen8f191b22013-08-06 12:27:50 -07001350 // If we're using p2p to download _and_ we have a p2p URL, we never
1351 // defer the download. This is because the download will always
1352 // happen from a peer on the LAN and we've been waiting in line for
1353 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001354 const PayloadStateInterface* payload_state = system_state_->payload_state();
1355 if (payload_state->GetUsingP2PForDownloading() &&
1356 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001357 LOG(INFO) << "Download not deferred because download "
1358 << "will happen from a local peer (via p2p).";
1359 return false;
1360 }
1361
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001362 // We should defer the downloads only if we've first satisfied the
1363 // wall-clock-based-waiting period and then the update-check-based waiting
1364 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001365 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001366 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1367 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001368 return false;
1369 }
1370
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001371 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001372 case kWallClockWaitNotSatisfied:
1373 // We haven't even satisfied the first condition, passing the
1374 // wall-clock-based waiting period, so we should defer the downloads
1375 // until that happens.
1376 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1377 return true;
1378
1379 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1380 LOG(INFO) << "wall-clock-based-wait satisfied and "
1381 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001382 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001383
1384 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1385 // Wall-clock-based waiting period is satisfied, and it's determined
1386 // that we do not need the update-check-based wait. so no need to
1387 // defer downloads.
1388 LOG(INFO) << "wall-clock-based-wait satisfied and "
1389 << "update-check-based-wait is not required.";
1390 return false;
1391
1392 default:
1393 // Returning false for this default case so we err on the
1394 // side of downloading updates than deferring in case of any bugs.
1395 NOTREACHED();
1396 return false;
1397 }
1398}
1399
1400OmahaRequestAction::WallClockWaitResult
1401OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001402 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001403 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001404 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001405
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001406 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1407 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1408 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001409 // Note: This timestamp could be that of ANY update we saw in the past
1410 // (not necessarily this particular update we're considering to apply)
1411 // but never got to apply because of some reason (e.g. stop AU policy,
1412 // updates being pulled out from Omaha, changes in target version prefix,
1413 // new update being rolled out, etc.). But for the purposes of scattering
1414 // it doesn't matter which update the timestamp corresponds to. i.e.
1415 // the clock starts ticking the first time we see an update and we're
1416 // ready to apply when the random wait period is satisfied relative to
1417 // that first seen timestamp.
1418 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1419 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1420 << utils::ToString(update_first_seen_at);
1421 } else {
1422 // This seems like an unexpected error where the persisted value exists
1423 // but it's not readable for some reason. Just skip scattering in this
1424 // case to be safe.
1425 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1426 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1427 }
1428 } else {
Sen Jiang7c1171e2016-06-23 11:35:40 -07001429 update_first_seen_at = system_state_->clock()->GetWallclockTime();
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001430 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001431 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1432 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001433 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1434 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001435 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001436 // This seems like an unexpected error where the value cannot be
1437 // persisted for some reason. Just skip scattering in this
1438 // case to be safe.
1439 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1440 << utils::ToString(update_first_seen_at)
1441 << " cannot be persisted";
1442 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1443 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001444 }
1445
Sen Jiang7c1171e2016-06-23 11:35:40 -07001446 TimeDelta elapsed_time =
1447 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1448 TimeDelta max_scatter_period =
1449 TimeDelta::FromDays(output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001450
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001451 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001452 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001453 << ", Time Elapsed = "
1454 << utils::FormatSecs(elapsed_time.InSeconds())
1455 << ", MaxDaysToScatter = "
1456 << max_scatter_period.InDays();
1457
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001458 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001459 // The deadline is set for all rules which serve a delta update from a
1460 // previous FSI, which means this update will be applied mostly in OOBE
1461 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1462 // quickly.
1463 LOG(INFO) << "Not scattering as deadline flag is set";
1464 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1465 }
1466
1467 if (max_scatter_period.InDays() == 0) {
1468 // This means the Omaha rule creator decides that this rule
1469 // should not be scattered irrespective of the policy.
1470 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1471 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1472 }
1473
1474 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001475 // This means we've waited more than the upperbound wait in the rule
1476 // from the time we first saw a valid update available to us.
1477 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001478 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1479 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1480 }
1481
1482 // This means we are required to participate in scattering.
1483 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001484 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001485 if (remaining_wait_time.InSeconds() <= 0) {
1486 // Yes, it's our turn now.
1487 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1488
1489 // But we can't download until the update-check-count-based wait is also
1490 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001491 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001492 kWallClockWaitDoneButUpdateCheckWaitRequired :
1493 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1494 }
1495
1496 // Not our turn yet, so we have to wait until our turn to
1497 // help scatter the downloads across all clients of the enterprise.
1498 LOG(INFO) << "Update deferred for another "
1499 << utils::FormatSecs(remaining_wait_time.InSeconds())
1500 << " per policy.";
1501 return kWallClockWaitNotSatisfied;
1502}
1503
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001504bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001505 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001506
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001507 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1508 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1509 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001510 // We are unable to read the update check count from file for some reason.
1511 // So let's proceed anyway so as to not stall the update.
1512 LOG(ERROR) << "Unable to read update check count. "
1513 << "Skipping update-check-count-based-wait.";
1514 return true;
1515 }
1516 } else {
1517 // This file does not exist. This means we haven't started our update
1518 // check count down yet, so this is the right time to start the count down.
1519 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001520 params_->min_update_checks_needed(),
1521 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001522
1523 LOG(INFO) << "Randomly picked update check count value = "
1524 << update_check_count_value;
1525
1526 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001527 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1528 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001529 // We weren't able to write the update check count file for some reason.
1530 // So let's proceed anyway so as to not stall the update.
1531 LOG(ERROR) << "Unable to write update check count. "
1532 << "Skipping update-check-count-based-wait.";
1533 return true;
1534 }
1535 }
1536
1537 if (update_check_count_value == 0) {
1538 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1539 return true;
1540 }
1541
1542 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001543 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001544 // We err on the side of skipping scattering logic instead of stalling
1545 // a machine from receiving any updates in case of any unexpected state.
1546 LOG(ERROR) << "Invalid value for update check count detected. "
1547 << "Skipping update-check-count-based-wait.";
1548 return true;
1549 }
1550
1551 // Legal value, we need to wait for more update checks to happen
1552 // until this becomes 0.
1553 LOG(INFO) << "Deferring Omaha updates for another "
1554 << update_check_count_value
1555 << " update checks per policy";
1556 return false;
1557}
1558
David Zeuthen639aa362014-02-03 16:23:44 -08001559// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001560bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001561 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001562 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001563 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001564 &elapsed_days))
1565 return false;
1566
1567 if (elapsed_days < 0)
1568 return false;
1569
1570 output_object->install_date_days = elapsed_days;
1571 return true;
1572}
1573
1574// static
1575bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1576 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001577 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001578 return false;
1579
1580 return prefs->Exists(kPrefsInstallDateDays);
1581}
1582
1583// static
1584bool OmahaRequestAction::PersistInstallDate(
1585 SystemState *system_state,
1586 int install_date_days,
1587 InstallDateProvisioningSource source) {
1588 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1589
1590 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001591 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001592 return false;
1593
1594 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1595 return false;
1596
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001597 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001598 static_cast<int>(source), // Sample.
1599 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001600 return true;
1601}
1602
Alex Deymo8e18f932015-03-27 16:16:59 -07001603bool OmahaRequestAction::PersistCohortData(
1604 const string& prefs_key,
1605 const string& new_value) {
1606 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1607 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1608 return system_state_->prefs()->Delete(prefs_key);
1609 } else if (!new_value.empty()) {
1610 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1611 return system_state_->prefs()->SetString(prefs_key, new_value);
1612 }
1613 return true;
1614}
1615
Alex Deymob3fa53b2016-04-18 19:57:58 -07001616bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
1617 auto eol_attr = attrs.find(kEolAttr);
1618 if (eol_attr != attrs.end()) {
1619 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1620 eol_attr->second);
1621 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1622 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1623 }
1624 return true;
1625}
1626
David Zeuthen33bae492014-02-25 16:16:18 -08001627void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1628 // We only want to report this on "update check".
1629 if (ping_only_ || event_ != nullptr)
1630 return;
1631
1632 metrics::CheckResult result = metrics::CheckResult::kUnset;
1633 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1634 metrics::DownloadErrorCode download_error_code =
1635 metrics::DownloadErrorCode::kUnset;
1636
1637 // Regular update attempt.
1638 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001639 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001640 // OK, we parsed the response successfully but that does
1641 // necessarily mean that an update is available.
1642 if (HasOutputPipe()) {
1643 const OmahaResponse& response = GetOutputObject();
1644 if (response.update_exists) {
1645 result = metrics::CheckResult::kUpdateAvailable;
1646 reaction = metrics::CheckReaction::kUpdating;
1647 } else {
1648 result = metrics::CheckResult::kNoUpdateAvailable;
1649 }
1650 } else {
1651 result = metrics::CheckResult::kNoUpdateAvailable;
1652 }
1653 break;
1654
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001655 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
Weidong Guo421ff332017-04-17 10:08:38 -07001656 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
David Zeuthen33bae492014-02-25 16:16:18 -08001657 result = metrics::CheckResult::kUpdateAvailable;
1658 reaction = metrics::CheckReaction::kIgnored;
1659 break;
1660
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001661 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001662 result = metrics::CheckResult::kUpdateAvailable;
1663 reaction = metrics::CheckReaction::kDeferring;
1664 break;
1665
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001666 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001667 result = metrics::CheckResult::kUpdateAvailable;
1668 reaction = metrics::CheckReaction::kBackingOff;
1669 break;
1670
1671 default:
1672 // We report two flavors of errors, "Download errors" and "Parsing
1673 // error". Try to convert to the former and if that doesn't work
1674 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001675 metrics::DownloadErrorCode tmp_error =
1676 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001677 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1678 result = metrics::CheckResult::kDownloadError;
1679 download_error_code = tmp_error;
1680 } else {
1681 result = metrics::CheckResult::kParsingError;
1682 }
1683 break;
1684 }
1685
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001686 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1687 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001688}
1689
Chris Sosa77f79e82014-06-02 18:16:24 -07001690bool OmahaRequestAction::ShouldIgnoreUpdate(
Weidong Guo421ff332017-04-17 10:08:38 -07001691 ErrorCode* error, const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001692 // Note: policy decision to not update to a version we rolled back from.
1693 string rollback_version =
1694 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001695 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001696 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001697 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001698 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001699 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001700 return true;
1701 }
1702 }
1703
Weidong Guo421ff332017-04-17 10:08:38 -07001704 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001705 LOG(INFO) << "Update is not allowed over current connection.";
1706 return true;
1707 }
1708
1709 // Note: We could technically delete the UpdateFirstSeenAt state when we
1710 // return true. If we do, it'll mean a device has to restart the
1711 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1712 // turned on again. On the other hand, it also increases the chance of update
1713 // starvation if an admin turns AU on/off more frequently. We choose to err on
1714 // the side of preventing starvation at the cost of not applying scattering in
1715 // those cases.
1716 return false;
1717}
1718
Weidong Guo421ff332017-04-17 10:08:38 -07001719bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1720 const OmahaResponse& response) const {
1721 PrefsInterface* prefs = system_state_->prefs();
1722
1723 if (!prefs) {
1724 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1725 "not available.";
1726 return false;
1727 }
1728
1729 bool is_allowed;
1730
1731 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1732 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1733 is_allowed) {
1734 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1735 "set to true.";
1736 return true;
1737 }
1738
1739 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1740 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1741 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1742 "set to false or does not exist while target does not exist.";
1743 return false;
1744 }
1745
1746 std::string target_version;
1747 int64_t target_size;
1748
1749 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1750 &target_version) ||
1751 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1752 LOG(INFO) << "Disabling updates over cellular as the target version or "
1753 "size is not accessible.";
1754 return false;
1755 }
1756
1757 uint64_t total_packages_size = 0;
1758 for (const auto& package : response.packages) {
1759 total_packages_size += package.size;
1760 }
1761 if (target_version == response.version &&
1762 static_cast<uint64_t>(target_size) == total_packages_size) {
1763 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1764 "omaha response.";
1765 return true;
1766 } else {
1767 LOG(INFO) << "Disabling updates over cellular as the target does not"
1768 "match the omaha response.";
1769 return false;
1770 }
1771}
1772
1773bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1774 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001775 ConnectionType type;
1776 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001777 ConnectionManagerInterface* connection_manager =
1778 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001779 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001780 LOG(INFO) << "We could not determine our connection type. "
1781 << "Defaulting to allow updates.";
1782 return true;
1783 }
Weidong Guo421ff332017-04-17 10:08:38 -07001784
Chris Sosa77f79e82014-06-02 18:16:24 -07001785 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001786 bool is_device_policy_set =
1787 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1788 // Treats tethered connection as if it is cellular connection.
1789 bool is_over_cellular = type == ConnectionType::kCellular ||
1790 tethering == ConnectionTethering::kConfirmed;
1791
1792 if (!is_over_cellular) {
1793 // There's no need to further check user preferences as we are not over
1794 // cellular connection.
1795 if (!is_allowed)
1796 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1797 } else if (is_device_policy_set) {
1798 // There's no need to further check user preferences as the device policy
1799 // is set regarding updates over cellular.
1800 if (!is_allowed)
1801 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1802 } else {
1803 // Deivce policy is not set, so user preferences overwrite whether to
1804 // allow updates over cellular.
1805 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1806 if (!is_allowed)
1807 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1808 }
1809
Chris Sosa77f79e82014-06-02 18:16:24 -07001810 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001811 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001812 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1813 return is_allowed;
1814}
1815
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001816bool OmahaRequestAction::IsRollbackEnabled() const {
1817 if (policy_provider_->IsConsumerDevice()) {
1818 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1819 return false;
1820 }
1821
1822 if (!policy_provider_->device_policy_is_loaded()) {
1823 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1824 return true;
1825 }
1826
1827 int allowed_milestones;
1828 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1829 &allowed_milestones)) {
1830 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1831 "Defaulting to rollback enabled.";
1832 return true;
1833 }
1834
1835 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1836 return allowed_milestones > 0;
1837}
1838
1839void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
1840 bool max_rollforward_set = false;
1841 if (IsRollbackEnabled()) {
1842 // If rollback is enabled, set the max kernel key version to the current
1843 // kernel key version. This has the effect of freezing kernel key roll
1844 // forwards.
1845 //
1846 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1847 // key roll forward happens until the server side components of rollback
1848 // are implemented. Future changes will allow the Omaha server to return
1849 // the kernel key version from max_rollback_versions in the past. At that
1850 // point the max kernel key version will be set to that value, creating a
1851 // sliding window of versions that can be rolled back to.
1852 int min_kernel_version =
1853 system_state_->hardware()->GetMinKernelKeyVersion();
1854 LOG(INFO) << "Rollback is enabled. Setting max_kernel_rollforward to "
1855 << min_kernel_version;
1856 max_rollforward_set = system_state_->hardware()->SetMaxKernelKeyRollforward(
1857 min_kernel_version);
1858 } else {
1859 // For devices that are not rollback enabled (ie. consumer devices), the
1860 // max kernel key version is set to 0xfffffffe, which is logically
1861 // infinity. This maintains the previous behavior that that kernel key
1862 // versions roll forward each time they are incremented.
1863 LOG(INFO) << "Rollback is disabled. Setting max_kernel_rollforward to "
1864 << kRollforwardInfinity;
1865 max_rollforward_set = system_state_->hardware()->SetMaxKernelKeyRollforward(
1866 kRollforwardInfinity);
1867 }
1868
1869 if (!max_rollforward_set) {
1870 LOG(ERROR) << "Failed to set max_kernel_rollforward";
1871 }
1872}
1873
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001874} // namespace chromeos_update_engine