blob: 424cb6675f3375b58f4219aa4c26451605f2cbcf [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) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700130 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700131 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700132 "></updatecheck>\n",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700133 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700134
Darin Petkov265f2902011-05-09 15:17:40 -0700135 // If this is the first update check after a reboot following a previous
136 // update, generate an event containing the previous version number. If
137 // the previous version preference file doesn't exist the event is still
138 // generated with a previous version of 0.0.0.0 -- this is relevant for
139 // older clients or new installs. The previous version event is not sent
140 // for ping-only requests because they come before the client has
Alex Deymo87c08862015-10-30 21:56:55 -0700141 // rebooted. The previous version event is also not sent if it was already
142 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700143 string prev_version;
144 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
145 prev_version = "0.0.0.0";
146 }
Alex Deymo87c08862015-10-30 21:56:55 -0700147 // We only store a non-empty previous version value after a successful
148 // update in the previous boot. After reporting it back to the server,
149 // we clear the previous version value so it doesn't get reported again.
150 if (!prev_version.empty()) {
151 app_body += base::StringPrintf(
152 " <event eventtype=\"%d\" eventresult=\"%d\" "
153 "previousversion=\"%s\"></event>\n",
Alex Deymo9fded1e2015-11-05 12:31:19 -0800154 OmahaEvent::kTypeRebootedAfterUpdate,
155 OmahaEvent::kResultSuccess,
Alex Deymo87c08862015-10-30 21:56:55 -0700156 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
157 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
158 << "Unable to reset the previous version.";
159 }
Darin Petkov95508da2011-01-05 12:42:29 -0800160 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700161 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800162 // The error code is an optional attribute so append it only if the result
163 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700164 string error_code;
165 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700166 error_code = base::StringPrintf(" errorcode=\"%d\"",
167 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700168 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700169 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700170 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700171 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700172 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700173
174 return app_body;
175}
176
Alex Deymo8e18f932015-03-27 16:16:59 -0700177// Returns the cohort* argument to include in the <app> tag for the passed
178// |arg_name| and |prefs_key|, if any. The return value is suitable to
179// concatenate to the list of arguments and includes a space at the end.
180string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700181 const string arg_name,
182 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700183 // There's nothing wrong with not having a given cohort setting, so we check
184 // existance first to avoid the warning log message.
185 if (!prefs->Exists(prefs_key))
186 return "";
187 string cohort_value;
188 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
189 return "";
190 // This is a sanity check to avoid sending a huge XML file back to Ohama due
191 // to a compromised stateful partition making the update check fail in low
192 // network environments envent after a reboot.
193 if (cohort_value.size() > 1024) {
194 LOG(WARNING) << "The omaha cohort setting " << arg_name
195 << " has a too big value, which must be an error or an "
196 "attacker trying to inhibit updates.";
197 return "";
198 }
199
Alex Deymob0d74eb2015-03-30 17:59:17 -0700200 string escaped_xml_value;
201 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
202 LOG(WARNING) << "The omaha cohort setting " << arg_name
203 << " is ASCII-7 invalid, ignoring it.";
204 return "";
205 }
206
Alex Deymo8e18f932015-03-27 16:16:59 -0700207 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700208 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700209}
210
Sen Jiang94a4dec2017-03-28 18:23:35 -0700211struct OmahaAppData {
212 string id;
213 string version;
Sen Jiang684c9cd2017-10-17 16:26:45 -0700214 string product_components;
Sen Jiang94a4dec2017-03-28 18:23:35 -0700215};
216
Sen Jiang684c9cd2017-10-17 16:26:45 -0700217bool IsValidComponentID(const string& id) {
218 for (char c : id) {
219 if (!isalnum(c) && c != '-' && c != '_' && c != '.')
220 return false;
221 }
222 return true;
223}
224
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700225// Returns an XML that corresponds to the entire <app> node of the Omaha
226// request based on the given parameters.
227string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700228 OmahaRequestParams* params,
Sen Jiang94a4dec2017-03-28 18:23:35 -0700229 const OmahaAppData& app_data,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700230 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700231 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700232 int ping_active_days,
233 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800234 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700235 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700236 string app_body = GetAppBody(event, params, ping_only, include_ping,
237 ping_active_days, ping_roll_call_days,
238 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700239 string app_versions;
240
Sen Jiang8cd42342018-01-31 12:06:59 -0800241 // If we are downgrading to a more stable channel and we are allowed to do
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700242 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
243 // highest-versioned payload on the destination channel.
Sen Jiang8500d3a2018-02-08 12:04:05 -0800244 if (params->ShouldPowerwash()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700245 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
246 << "on downgrading to the version in the more stable channel";
247 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700248 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700249 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700250 app_versions = "version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700251 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700252 }
253
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700254 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700255 string app_channels =
256 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
257 if (params->current_channel() != download_channel) {
258 app_channels += "from_track=\"" + XmlEncodeWithDefault(
259 params->current_channel(), "") + "\" ";
260 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700261
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700262 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700263
David Zeuthen639aa362014-02-03 16:23:44 -0800264 // If install_date_days is not set (e.g. its value is -1 ), don't
265 // include the attribute.
266 string install_date_in_days_str = "";
267 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700268 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
269 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800270 }
271
Alex Deymo8e18f932015-03-27 16:16:59 -0700272 string app_cohort_args;
273 app_cohort_args += GetCohortArgXml(system_state->prefs(),
274 "cohort", kPrefsOmahaCohort);
275 app_cohort_args += GetCohortArgXml(system_state->prefs(),
276 "cohorthint", kPrefsOmahaCohortHint);
277 app_cohort_args += GetCohortArgXml(system_state->prefs(),
278 "cohortname", kPrefsOmahaCohortName);
279
Alex Deymoebf6e122017-03-10 16:12:01 -0800280 string fingerprint_arg;
281 if (!params->os_build_fingerprint().empty()) {
Sen Jiang8cd42342018-01-31 12:06:59 -0800282 fingerprint_arg = "fingerprint=\"" +
283 XmlEncodeWithDefault(params->os_build_fingerprint(), "") +
284 "\" ";
Alex Deymoebf6e122017-03-10 16:12:01 -0800285 }
286
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700287 string buildtype_arg;
288 if (!params->os_build_type().empty()) {
289 buildtype_arg = "os_build_type=\"" +
290 XmlEncodeWithDefault(params->os_build_type(), "") + "\" ";
291 }
292
Sen Jiang684c9cd2017-10-17 16:26:45 -0700293 string product_components_args;
Sen Jiang8500d3a2018-02-08 12:04:05 -0800294 if (!params->ShouldPowerwash() && !app_data.product_components.empty()) {
Sen Jiang684c9cd2017-10-17 16:26:45 -0700295 brillo::KeyValueStore store;
296 if (store.LoadFromString(app_data.product_components)) {
297 for (const string& key : store.GetKeys()) {
298 if (!IsValidComponentID(key)) {
299 LOG(ERROR) << "Invalid component id: " << key;
300 continue;
301 }
302 string version;
303 if (!store.GetString(key, &version)) {
304 LOG(ERROR) << "Failed to get version for " << key
305 << " in product_components.";
306 continue;
307 }
308 product_components_args +=
309 base::StringPrintf("_%s.version=\"%s\" ",
310 key.c_str(),
311 XmlEncodeWithDefault(version, "").c_str());
312 }
313 } else {
314 LOG(ERROR) << "Failed to parse product_components:\n"
315 << app_data.product_components;
316 }
317 }
318
319 // clang-format off
Alex Deymob0d74eb2015-03-30 17:59:17 -0700320 string app_xml = " <app "
Sen Jiang94a4dec2017-03-28 18:23:35 -0700321 "appid=\"" + XmlEncodeWithDefault(app_data.id, "") + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700322 app_cohort_args +
323 app_versions +
324 app_channels +
Sen Jiang684c9cd2017-10-17 16:26:45 -0700325 product_components_args +
Alex Deymoebf6e122017-03-10 16:12:01 -0800326 fingerprint_arg +
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700327 buildtype_arg +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700328 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
329 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
330 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
331 "delta_okay=\"" + delta_okay_str + "\" "
332 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
333 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
334 install_date_in_days_str +
335 ">\n" +
336 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700337 " </app>\n";
Sen Jiang684c9cd2017-10-17 16:26:45 -0700338 // clang-format on
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700339 return app_xml;
340}
341
342// Returns an XML that corresponds to the entire <os> node of the Omaha
343// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700344string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700345 string os_xml =" <os "
346 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
347 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
348 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
349 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700350 return os_xml;
351}
352
353// Returns an XML that corresponds to the entire Omaha request based on the
354// given parameters.
355string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700356 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700357 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700358 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700359 int ping_active_days,
360 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800361 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700362 SystemState* system_state) {
363 string os_xml = GetOsXml(params);
Sen Jiang684c9cd2017-10-17 16:26:45 -0700364 OmahaAppData product_app = {
365 .id = params->GetAppId(),
366 .version = params->app_version(),
367 .product_components = params->product_components()};
Sen Jiang94a4dec2017-03-28 18:23:35 -0700368 string app_xml = GetAppXml(event,
369 params,
370 product_app,
371 ping_only,
372 include_ping,
373 ping_active_days,
374 ping_roll_call_days,
375 install_date_in_days,
376 system_state);
377 if (!params->system_app_id().empty()) {
378 OmahaAppData system_app = {.id = params->system_app_id(),
379 .version = params->system_version()};
380 app_xml += GetAppXml(event,
381 params,
382 system_app,
383 ping_only,
384 include_ping,
385 ping_active_days,
386 ping_roll_call_days,
387 install_date_in_days,
388 system_state);
389 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700390
Alex Vakulenko75039d72014-03-25 12:36:28 -0700391 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700392 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700393
Alex Deymoac41a822015-09-15 20:52:53 -0700394 string updater_version = XmlEncodeWithDefault(
395 base::StringPrintf("%s-%s",
396 constants::kOmahaUpdaterID,
397 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700398 string request_xml =
399 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700400 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700401 "version=\"" + updater_version + "\" "
402 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700403 install_source +
404 "ismachine=\"1\">\n") +
405 os_xml +
406 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700407 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700408
409 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000410}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700411
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700412} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000413
David Zeuthene8ed8632014-07-24 13:38:10 -0400414// Struct used for holding data obtained when parsing the XML.
415struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400416 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
417
418 // Pointer to the expat XML_Parser object.
419 XML_Parser xml_parser;
420
David Zeuthene8ed8632014-07-24 13:38:10 -0400421 // This is the state of the parser as it's processing the XML.
422 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400423 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400424 string current_path;
425
426 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400427 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700428 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400429 string daystart_elapsed_days;
430 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800431
Sen Jiang81259682017-03-30 15:11:30 -0700432 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700433 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700434 vector<string> url_codebase;
435 string manifest_version;
436 map<string, string> action_postinstall_attrs;
437 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700438 string cohort;
439 string cohorthint;
440 string cohortname;
441 bool cohort_set = false;
442 bool cohorthint_set = false;
443 bool cohortname_set = false;
Sen Jiang81259682017-03-30 15:11:30 -0700444
445 struct Package {
446 string name;
447 string size;
448 string hash;
449 };
450 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800451 };
Sen Jiang81259682017-03-30 15:11:30 -0700452 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400453};
454
455namespace {
456
457// Callback function invoked by expat.
458void ParserHandlerStart(void* user_data, const XML_Char* element,
459 const XML_Char** attr) {
460 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
461
462 if (data->failed)
463 return;
464
465 data->current_path += string("/") + element;
466
467 map<string, string> attrs;
468 if (attr != nullptr) {
469 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
470 string key = attr[n];
471 string value = attr[n + 1];
472 attrs[key] = value;
473 }
474 }
475
Alex Deymo8e18f932015-03-27 16:16:59 -0700476 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700477 OmahaParserData::App app;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700478 if (attrs.find("appid") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700479 app.id = attrs["appid"];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700480 }
Alex Deymo8e18f932015-03-27 16:16:59 -0700481 if (attrs.find("cohort") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700482 app.cohort_set = true;
483 app.cohort = attrs["cohort"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700484 }
485 if (attrs.find("cohorthint") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700486 app.cohorthint_set = true;
487 app.cohorthint = attrs["cohorthint"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700488 }
489 if (attrs.find("cohortname") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700490 app.cohortname_set = true;
491 app.cohortname = attrs["cohortname"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700492 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700493 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700494 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700495 if (!data->apps.empty())
496 data->apps.back().updatecheck_status = attrs["status"];
497 if (data->updatecheck_poll_interval.empty())
498 data->updatecheck_poll_interval = attrs["PollInterval"];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700499 // Omaha sends arbitrary key-value pairs as extra attributes starting with
500 // an underscore.
501 for (const auto& attr : attrs) {
502 if (!attr.first.empty() && attr.first[0] == '_')
503 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
504 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400505 } else if (data->current_path == "/response/daystart") {
506 // Get the install-date.
507 data->daystart_elapsed_days = attrs["elapsed_days"];
508 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
509 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
510 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700511 if (!data->apps.empty())
512 data->apps.back().url_codebase.push_back(attrs["codebase"]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800513 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400514 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800515 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700516 if (!data->apps.empty())
517 data->apps.back().packages.push_back({.name = attrs["name"],
518 .size = attrs["size"],
519 .hash = attrs["hash_sha256"]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400520 } else if (data->current_path == "/response/app/updatecheck/manifest") {
521 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700522 if (!data->apps.empty())
523 data->apps.back().manifest_version = attrs[kTagVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400524 } else if (data->current_path ==
525 "/response/app/updatecheck/manifest/actions/action") {
526 // We only care about the postinstall action.
Sen Jiang81259682017-03-30 15:11:30 -0700527 if (attrs["event"] == "postinstall" && !data->apps.empty()) {
528 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400529 }
530 }
531}
532
533// Callback function invoked by expat.
534void ParserHandlerEnd(void* user_data, const XML_Char* element) {
535 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
536 if (data->failed)
537 return;
538
539 const string path_suffix = string("/") + element;
540
Alex Vakulenko0103c362016-01-20 07:56:15 -0800541 if (!base::EndsWith(data->current_path, path_suffix,
542 base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400543 LOG(ERROR) << "Unexpected end element '" << element
544 << "' with current_path='" << data->current_path << "'";
545 data->failed = true;
546 return;
547 }
548 data->current_path.resize(data->current_path.size() - path_suffix.size());
549}
550
David Zeuthenf3e28012014-08-26 18:23:52 -0400551// Callback function invoked by expat.
552//
553// This is called for entity declarations. Since Omaha is guaranteed
554// to never return any XML with entities our course of action is to
555// just stop parsing. This avoids potential resource exhaustion
556// problems AKA the "billion laughs". CVE-2013-0340.
557void ParserHandlerEntityDecl(void *user_data,
558 const XML_Char *entity_name,
559 int is_parameter_entity,
560 const XML_Char *value,
561 int value_length,
562 const XML_Char *base,
563 const XML_Char *system_id,
564 const XML_Char *public_id,
565 const XML_Char *notation_name) {
566 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
567
568 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
569 data->failed = true;
570 data->entity_decl = true;
571 XML_StopParser(data->xml_parser, false);
572}
573
David Zeuthene8ed8632014-07-24 13:38:10 -0400574} // namespace
575
Alex Deymob0d74eb2015-03-30 17:59:17 -0700576bool XmlEncode(const string& input, string* output) {
577 if (std::find_if(input.begin(), input.end(),
578 [](const char c){return c & 0x80;}) != input.end()) {
579 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
580 utils::HexDumpString(input);
581 return false;
582 }
Alex Deymocc457852015-06-18 18:35:50 -0700583 output->clear();
584 // We need at least input.size() space in the output, but the code below will
585 // handle it if we need more.
586 output->reserve(input.size());
587 for (char c : input) {
588 switch (c) {
589 case '\"':
590 output->append("&quot;");
591 break;
592 case '\'':
593 output->append("&apos;");
594 break;
595 case '&':
596 output->append("&amp;");
597 break;
598 case '<':
599 output->append("&lt;");
600 break;
601 case '>':
602 output->append("&gt;");
603 break;
604 default:
605 output->push_back(c);
606 }
607 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700608 return true;
609}
610
611string XmlEncodeWithDefault(const string& input, const string& default_value) {
612 string output;
613 if (XmlEncode(input, &output))
614 return output;
615 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000616}
617
Alex Deymoc1c17b42015-11-23 03:53:15 -0300618OmahaRequestAction::OmahaRequestAction(
619 SystemState* system_state,
620 OmahaEvent* event,
621 std::unique_ptr<HttpFetcher> http_fetcher,
622 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800623 : system_state_(system_state),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800624 params_(system_state->request_params()),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700625 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300626 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800627 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700628 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700629 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700630 ping_roll_call_days_(0) {
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800631 policy_provider_->Reload();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700632}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000633
Darin Petkov6a5b3222010-07-13 14:55:28 -0700634OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000635
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700636// Calculates the value to use for the ping days parameter.
637int OmahaRequestAction::CalculatePingDays(const string& key) {
638 int days = kNeverPinged;
639 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800640 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700641 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
642 if (days < 0) {
643 // If |days| is negative, then the system clock must have jumped
644 // back in time since the ping was sent. Mark the value so that
645 // it doesn't get sent to the server but we still update the
646 // last ping daystart preference. This way the next ping time
647 // will be correct, hopefully.
648 days = kPingTimeJump;
649 LOG(WARNING) <<
650 "System clock jumped back in time. Resetting ping daystarts.";
651 }
652 }
653 return days;
654}
655
656void OmahaRequestAction::InitPingDays() {
657 // We send pings only along with update checks, not with events.
658 if (IsEvent()) {
659 return;
660 }
661 // TODO(petkov): Figure a way to distinguish active use pings
662 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700663 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700664 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
665 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
666}
667
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700668bool OmahaRequestAction::ShouldPing() const {
669 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
670 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
671 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
672 if (powerwash_count > 0) {
673 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
674 << "powerwash_count is " << powerwash_count;
675 return false;
676 }
Amin Hassani1677e812017-06-21 13:36:36 -0700677 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
678 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
679 << "the first_active_omaha_ping_sent is true";
680 return false;
681 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700682 return true;
683 }
684 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
685}
686
David Zeuthen639aa362014-02-03 16:23:44 -0800687// static
688int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
689 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700690 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800691 return -1;
692
693 // If we have the value stored on disk, just return it.
694 int64_t stored_value;
695 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
696 // Convert and sanity-check.
697 int install_date_days = static_cast<int>(stored_value);
698 if (install_date_days >= 0)
699 return install_date_days;
700 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
701 << install_date_days << " looks suspicious.";
702 prefs->Delete(kPrefsInstallDateDays);
703 }
704
705 // Otherwise, if OOBE is not complete then do nothing and wait for
706 // ParseResponse() to call ParseInstallDate() and then
707 // PersistInstallDate() to set the kPrefsInstallDateDays state
708 // variable. Once that is done, we'll then report back in future
709 // Omaha requests. This works exactly because OOBE triggers an
710 // update check.
711 //
712 // However, if OOBE is complete and the kPrefsInstallDateDays state
713 // variable is not set, there are two possibilities
714 //
715 // 1. The update check in OOBE failed so we never got a response
716 // from Omaha (no network etc.); or
717 //
718 // 2. OOBE was done on an older version that didn't write to the
719 // kPrefsInstallDateDays state variable.
720 //
721 // In both cases, we approximate the install date by simply
722 // inspecting the timestamp of when OOBE happened.
723
724 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700725 if (!system_state->hardware()->IsOOBEEnabled() ||
726 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800727 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700728 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800729 return -1;
730 }
731
732 int num_days;
733 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
734 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
735 << "as its value '" << utils::ToString(time_of_oobe)
736 << "' looks suspicious.";
737 return -1;
738 }
739
740 // Persist this to disk, for future use.
741 if (!OmahaRequestAction::PersistInstallDate(system_state,
742 num_days,
743 kProvisionedFromOOBEMarker))
744 return -1;
745
746 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
747 << num_days << " days";
748
749 return num_days;
750}
751
Darin Petkov6a5b3222010-07-13 14:55:28 -0700752void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000753 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700754 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700755 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700756 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700757 return;
758 }
David Zeuthen639aa362014-02-03 16:23:44 -0800759
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700760 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700761 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700762 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700763 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700764 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800765 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800766 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700767 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700768
Sen Jiang42fa45e2018-03-12 11:02:14 -0700769 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700770 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
771 params_->interactive() ? "fg" : "bg");
772 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
773 http_fetcher_->SetHeader(
774 kXGoogleUpdateUpdater,
775 base::StringPrintf(
776 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
777
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800778 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
779 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700780 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700781 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700782 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000783}
784
Darin Petkov6a5b3222010-07-13 14:55:28 -0700785void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000786 http_fetcher_->TerminateTransfer();
787}
788
789// We just store the response in the buffer. Once we've received all bytes,
790// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700791void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800792 const void* bytes,
793 size_t length) {
794 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
795 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000796}
797
798namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000799
800// Parses a 64 bit base-10 int from a string and returns it. Returns 0
801// on error. If the string contains "0", that's indistinguishable from
802// error.
803off_t ParseInt(const string& str) {
804 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700805 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000806 if (rc < 1) {
807 // failure
808 return 0;
809 }
810 return ret;
811}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700812
David Zeuthene8ed8632014-07-24 13:38:10 -0400813// Parses |str| and returns |true| if, and only if, its value is "true".
814bool ParseBool(const string& str) {
815 return str == "true";
816}
817
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700818// Update the last ping day preferences based on the server daystart
819// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400820bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700821 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400822 TEST_AND_RETURN_FALSE(
823 base::StringToInt64(parser_data->daystart_elapsed_seconds,
824 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700825 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
826
827 // Remember the local time that matches the server's last midnight
828 // time.
829 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
830 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
831 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
832 return true;
833}
Sen Jiang81259682017-03-30 15:11:30 -0700834
835// Parses the package node in the given XML document and populates
836// |output_object| if valid. Returns true if we should continue the parsing.
837// False otherwise, in which case it sets any error code using |completer|.
838bool ParsePackage(OmahaParserData::App* app,
839 OmahaResponse* output_object,
840 ScopedActionCompleter* completer) {
841 if (app->updatecheck_status == "noupdate") {
842 if (!app->packages.empty()) {
843 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
844 completer->set_code(ErrorCode::kOmahaResponseInvalid);
845 return false;
846 }
847 return true;
848 }
849 if (app->packages.empty()) {
850 LOG(ERROR) << "Omaha Response has no packages";
851 completer->set_code(ErrorCode::kOmahaResponseInvalid);
852 return false;
853 }
854 if (app->url_codebase.empty()) {
855 LOG(ERROR) << "No Omaha Response URLs";
856 completer->set_code(ErrorCode::kOmahaResponseInvalid);
857 return false;
858 }
859 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
860 vector<string> metadata_sizes =
861 base::SplitString(app->action_postinstall_attrs[kTagMetadataSize],
862 ":",
863 base::TRIM_WHITESPACE,
864 base::SPLIT_WANT_ALL);
865 vector<string> metadata_signatures =
866 base::SplitString(app->action_postinstall_attrs[kTagMetadataSignatureRsa],
867 ":",
868 base::TRIM_WHITESPACE,
869 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700870 vector<string> is_delta_payloads =
871 base::SplitString(app->action_postinstall_attrs[kTagIsDeltaPayload],
872 ":",
873 base::TRIM_WHITESPACE,
874 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700875 for (size_t i = 0; i < app->packages.size(); i++) {
876 const auto& package = app->packages[i];
877 if (package.name.empty()) {
878 LOG(ERROR) << "Omaha Response has empty package name";
879 completer->set_code(ErrorCode::kOmahaResponseInvalid);
880 return false;
881 }
882 LOG(INFO) << "Found package " << package.name;
883
884 OmahaResponse::Package out_package;
885 for (const string& codebase : app->url_codebase) {
886 if (codebase.empty()) {
887 LOG(ERROR) << "Omaha Response URL has empty codebase";
888 completer->set_code(ErrorCode::kOmahaResponseInvalid);
889 return false;
890 }
891 out_package.payload_urls.push_back(codebase + package.name);
892 }
893 // Parse the payload size.
894 base::StringToUint64(package.size, &out_package.size);
895 if (out_package.size <= 0) {
896 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
897 completer->set_code(ErrorCode::kOmahaResponseInvalid);
898 return false;
899 }
900 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
901
902 if (i < metadata_sizes.size())
903 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
904 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
905 << " bytes";
906
907 if (i < metadata_signatures.size())
908 out_package.metadata_signature = metadata_signatures[i];
909 LOG(INFO) << "Payload metadata signature = "
910 << out_package.metadata_signature;
911
912 out_package.hash = package.hash;
913 if (out_package.hash.empty()) {
914 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
915 completer->set_code(ErrorCode::kOmahaResponseInvalid);
916 return false;
917 }
918 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700919
920 if (i < is_delta_payloads.size())
921 out_package.is_delta = ParseBool(is_delta_payloads[i]);
922 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
923
Sen Jiang81259682017-03-30 15:11:30 -0700924 output_object->packages.push_back(std::move(out_package));
925 }
926
927 return true;
928}
929
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700930} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000931
David Zeuthene8ed8632014-07-24 13:38:10 -0400932bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700933 OmahaResponse* output_object,
934 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700935 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700936 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700937 return false;
938 }
Sen Jiang81259682017-03-30 15:11:30 -0700939 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700940
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800941 // chromium-os:37289: The PollInterval is not supported by Omaha server
942 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700943 // slow down the request rate from the server-side. Note that the PollInterval
944 // is not persisted, so it has to be sent by the server on every response to
945 // guarantee that the scheduler uses this value (otherwise, if the device got
946 // rebooted after the last server-indicated value, it'll revert to the default
947 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
948 // based on the assumption that we perform an update check every hour so that
949 // the max value of 8 will roughly be equivalent to one work day. If we decide
950 // to use PollInterval permanently, we should update the
951 // max_update_checks_allowed to take PollInterval into account. Note: The
952 // parsing for PollInterval happens even before parsing of the status because
953 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400954 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700955 &output_object->poll_interval);
956
David Zeuthen639aa362014-02-03 16:23:44 -0800957 // Check for the "elapsed_days" attribute in the "daystart"
958 // element. This is the number of days since Jan 1 2007, 0:00
959 // PST. If we don't have a persisted value of the Omaha InstallDate,
960 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400961 if (ParseInstallDate(parser_data, output_object) &&
962 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800963 // Since output_object->install_date_days is never negative, the
964 // elapsed_days -> install-date calculation is reduced to simply
965 // rounding down to the nearest number divisible by 7.
966 int remainder = output_object->install_date_days % 7;
967 int install_date_days_rounded =
968 output_object->install_date_days - remainder;
969 if (PersistInstallDate(system_state_,
970 install_date_days_rounded,
971 kProvisionedFromOmahaResponse)) {
972 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
973 << install_date_days_rounded << " days";
974 }
975 }
976
Alex Deymo00d79ac2015-06-29 15:41:49 -0700977 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -0700978 for (const auto& app : parser_data->apps) {
979 if (app.id == params_->GetAppId()) {
980 if (app.cohort_set)
981 PersistCohortData(kPrefsOmahaCohort, app.cohort);
982 if (app.cohorthint_set)
983 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
984 if (app.cohortname_set)
985 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
986 break;
987 }
988 }
Alex Deymo00d79ac2015-06-29 15:41:49 -0700989
Alex Deymob3fa53b2016-04-18 19:57:58 -0700990 // Parse the updatecheck attributes.
991 PersistEolStatus(parser_data->updatecheck_attrs);
992
David Zeuthene8ed8632014-07-24 13:38:10 -0400993 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700994 return false;
995
David Zeuthene8ed8632014-07-24 13:38:10 -0400996 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700997 return false;
998
Sen Jiang0affc2c2017-02-10 15:55:05 -0800999 // Package has to be parsed after Params now because ParseParams need to make
1000 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -07001001 for (auto& app : parser_data->apps)
1002 if (!ParsePackage(&app, output_object, completer))
1003 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001004
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001005 return true;
1006}
1007
David Zeuthene8ed8632014-07-24 13:38:10 -04001008bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001009 OmahaResponse* output_object,
1010 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001011 output_object->update_exists = false;
1012 for (size_t i = 0; i < parser_data->apps.size(); i++) {
1013 const string& status = parser_data->apps[i].updatecheck_status;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001014 if (status == "noupdate") {
1015 // Don't update if any app has status="noupdate".
Sen Jiang81259682017-03-30 15:11:30 -07001016 LOG(INFO) << "No update for <app> " << i;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001017 output_object->update_exists = false;
1018 break;
Sen Jiang81259682017-03-30 15:11:30 -07001019 } else if (status == "ok") {
Sen Jiang00adf7b2017-06-26 15:57:29 -07001020 if (parser_data->apps[i].action_postinstall_attrs["noupdate"] == "true") {
1021 // noupdate="true" in postinstall attributes means it's an update to
1022 // self, only update if there's at least one app really have update.
1023 LOG(INFO) << "Update to self for <app> " << i;
1024 } else {
1025 LOG(INFO) << "Update for <app> " << i;
1026 output_object->update_exists = true;
1027 }
Sen Jiang81259682017-03-30 15:11:30 -07001028 } else {
1029 LOG(ERROR) << "Unknown Omaha response status: " << status;
1030 completer->set_code(ErrorCode::kOmahaResponseInvalid);
1031 return false;
1032 }
1033 }
1034 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001035 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001036 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001037 }
1038
Sen Jiang81259682017-03-30 15:11:30 -07001039 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001040}
1041
David Zeuthene8ed8632014-07-24 13:38:10 -04001042bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001043 OmahaResponse* output_object,
1044 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001045 map<string, string> attrs;
1046 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001047 if (app.id == params_->GetAppId()) {
1048 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -07001049 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001050 } else if (!params_->system_app_id().empty() &&
1051 app.id == params_->system_app_id()) {
1052 // this is the system app (this check is intentionally skipped if there is
1053 // no system_app_id set)
1054 output_object->system_version = app.manifest_version;
1055 }
1056 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -07001057 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001058 }
Sen Jiang81259682017-03-30 15:11:30 -07001059 }
Chris Sosa3b748432013-06-20 16:42:59 -07001060 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -07001061 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001062 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -07001063 return false;
1064 }
1065
1066 LOG(INFO) << "Received omaha response to update to version "
1067 << output_object->version;
1068
David Zeuthene8ed8632014-07-24 13:38:10 -04001069 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001070 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001071 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001072 return false;
1073 }
1074
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001075 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -04001076 output_object->more_info_url = attrs[kTagMoreInfo];
David Zeuthene8ed8632014-07-24 13:38:10 -04001077 output_object->prompt = ParseBool(attrs[kTagPrompt]);
1078 output_object->deadline = attrs[kTagDeadline];
1079 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001080 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -04001081 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001082 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -04001083 ParseBool(attrs[kTagDisableP2PForSharing]);
1084 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001085
David Zeuthene8ed8632014-07-24 13:38:10 -04001086 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -08001087 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001088 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001089
Jay Srinivasan08262882012-12-28 19:29:43 -08001090 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -04001091 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -08001092
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001093 return true;
1094}
1095
David Zeuthene8ed8632014-07-24 13:38:10 -04001096// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +00001097// and fill in the appropriate fields of the output object. Also, notifies
1098// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -07001099void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
1100 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +00001101 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001102 string current_response(response_buffer_.begin(), response_buffer_.end());
1103 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001104
Gilad Arnold74b5f552014-10-07 08:17:16 -07001105 PayloadStateInterface* const payload_state = system_state_->payload_state();
1106
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001107 // Events are best effort transactions -- assume they always succeed.
1108 if (IsEvent()) {
1109 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001110 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001111 return;
1112 }
1113
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001114 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001115 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -07001116 int code = GetHTTPResponseCode();
1117 // Makes sure we send sane error values.
1118 if (code < 0 || code >= 1000) {
1119 code = 999;
1120 }
David Zeuthena99981f2013-04-29 13:42:47 -07001121 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001122 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +00001123 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001124 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001125
David Zeuthene8ed8632014-07-24 13:38:10 -04001126 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -04001127 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -04001128 XML_SetUserData(parser, &parser_data);
1129 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -04001130 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001131 XML_Status res = XML_Parse(
1132 parser,
1133 reinterpret_cast<const char*>(response_buffer_.data()),
1134 response_buffer_.size(),
1135 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -04001136 XML_ParserFree(parser);
1137
1138 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -07001139 LOG(ERROR) << "Omaha response not valid XML: "
1140 << XML_ErrorString(XML_GetErrorCode(parser))
1141 << " at line " << XML_GetCurrentLineNumber(parser)
1142 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -04001143 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
1144 if (response_buffer_.empty()) {
1145 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
1146 } else if (parser_data.entity_decl) {
1147 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
1148 }
1149 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001150 return;
1151 }
1152
Alex Deymoebbe7ef2014-10-30 13:02:49 -07001153 // Update the last ping day preferences based on the server daystart response
1154 // even if we didn't send a ping. Omaha always includes the daystart in the
1155 // response, but log the error if it didn't.
1156 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
1157 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -07001158
Amin Hassani1677e812017-06-21 13:36:36 -07001159 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
1160 // we have got a response from omaha and if its value has never been set to
1161 // true before. Failure of this function should be ignored. There should be no
1162 // need to check if a=-1 has been sent because older devices have already sent
1163 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
1164 // future checks.
1165 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
1166 system_state_->hardware()->SetFirstActiveOmahaPingSent();
1167 }
1168
Thieu Le116fda32011-04-19 11:01:54 -07001169 if (!HasOutputPipe()) {
1170 // Just set success to whether or not the http transfer succeeded,
1171 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001172 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001173 return;
1174 }
1175
Darin Petkov6a5b3222010-07-13 14:55:28 -07001176 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001177 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001178 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001179 output_object.update_exists = true;
1180 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001181
Weidong Guo421ff332017-04-17 10:08:38 -07001182 ErrorCode error = ErrorCode::kSuccess;
1183 if (ShouldIgnoreUpdate(&error, output_object)) {
1184 // No need to change output_object.update_exists here, since the value
1185 // has been output to the pipe.
1186 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001187 return;
1188 }
1189
David Zeuthen8f191b22013-08-06 12:27:50 -07001190 // If Omaha says to disable p2p, respect that
1191 if (output_object.disable_p2p_for_downloading) {
1192 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1193 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001194 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001195 }
1196 if (output_object.disable_p2p_for_sharing) {
1197 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1198 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001199 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001200 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001201
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001202 // Set the max kernel key version based on whether rollback is allowed.
1203 SetMaxKernelKeyVersionForRollback();
1204
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001205 // Update the payload state with the current response. The payload state
1206 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001207 // from what's stored already. We are updating the payload state as late
1208 // as possible in this method so that if a new release gets pushed and then
1209 // got pulled back due to some issues, we don't want to clear our internal
1210 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001211 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001212
David Zeuthen8f191b22013-08-06 12:27:50 -07001213 // It could be we've already exceeded the deadline for when p2p is
1214 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001215 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001216 payload_state->P2PNewAttempt();
1217 if (!payload_state->P2PAttemptAllowed()) {
1218 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1219 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001220 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001221 }
1222 }
1223
1224 // From here on, we'll complete stuff in CompleteProcessing() so
1225 // disable |completer| since we'll create a new one in that
1226 // function.
1227 completer.set_should_complete(false);
1228
1229 // If we're allowed to use p2p for downloading we do not pay
1230 // attention to wall-clock-based waiting if the URL is indeed
1231 // available via p2p. Therefore, check if the file is available via
1232 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001233 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001234 LookupPayloadViaP2P(output_object);
1235 } else {
1236 CompleteProcessing();
1237 }
1238}
1239
1240void OmahaRequestAction::CompleteProcessing() {
1241 ScopedActionCompleter completer(processor_, this);
1242 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1243 PayloadStateInterface* payload_state = system_state_->payload_state();
1244
Alex Deymo46a9aae2016-05-04 20:20:11 -07001245 if (system_state_->hardware()->IsOOBEEnabled() &&
1246 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
Kevin Cernekeec5081a82016-04-08 12:29:52 -07001247 output_object.deadline.empty() &&
1248 params_->app_version() != "ForcedUpdate") {
Kevin Cernekee2494e282016-03-29 18:03:53 -07001249 output_object.update_exists = false;
1250 LOG(INFO) << "Ignoring non-critical Omaha updates until OOBE is done.";
1251 completer.set_code(ErrorCode::kNonCriticalUpdateInOOBE);
1252 return;
1253 }
1254
David Zeuthen8f191b22013-08-06 12:27:50 -07001255 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001256 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001257 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001258 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001259 return;
1260 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001261
Chris Sosa20f005c2013-09-05 13:53:08 -07001262 if (payload_state->ShouldBackoffDownload()) {
1263 output_object.update_exists = false;
1264 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1265 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001266 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001267 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001268 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001269 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001270}
1271
1272void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1273 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1274 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001275 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001276 } else {
1277 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1278 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001279 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001280 }
1281 CompleteProcessing();
1282}
1283
1284void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001285 // If the device is in the middle of an update, the state variables
1286 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1287 // tracks the offset and length of the operation currently in
1288 // progress. The offset is based from the end of the manifest which
1289 // is kPrefsManifestMetadataSize bytes long.
1290 //
1291 // To make forward progress and avoid deadlocks, we need to find a
1292 // peer that has at least the entire operation we're currently
1293 // working on. Otherwise we may end up in a situation where two
1294 // devices bounce back and forth downloading from each other,
1295 // neither making any forward progress until one of them decides to
1296 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1297 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001298 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001299 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001300 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001301 int64_t next_data_offset = 0;
1302 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001303 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001304 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1305 &manifest_metadata_size) &&
1306 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001307 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1308 &manifest_signature_size) &&
1309 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001310 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001311 &next_data_offset) &&
1312 next_data_offset != -1 &&
1313 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1314 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001315 minimum_size = manifest_metadata_size + manifest_signature_size +
1316 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001317 }
1318
Sen Jiang0affc2c2017-02-10 15:55:05 -08001319 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001320 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001321 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001322 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001323 string file_id =
1324 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001325 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001326 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1327 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001328 system_state_->p2p_manager()->LookupUrlForFile(
1329 file_id,
1330 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001331 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001332 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1333 base::Unretained(this)));
1334 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001335}
1336
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001337bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001338 if (params_->interactive()) {
1339 LOG(INFO) << "Not deferring download because update is interactive.";
1340 return false;
1341 }
1342
David Zeuthen8f191b22013-08-06 12:27:50 -07001343 // If we're using p2p to download _and_ we have a p2p URL, we never
1344 // defer the download. This is because the download will always
1345 // happen from a peer on the LAN and we've been waiting in line for
1346 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001347 const PayloadStateInterface* payload_state = system_state_->payload_state();
1348 if (payload_state->GetUsingP2PForDownloading() &&
1349 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001350 LOG(INFO) << "Download not deferred because download "
1351 << "will happen from a local peer (via p2p).";
1352 return false;
1353 }
1354
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001355 // We should defer the downloads only if we've first satisfied the
1356 // wall-clock-based-waiting period and then the update-check-based waiting
1357 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001358 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001359 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1360 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001361 return false;
1362 }
1363
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001364 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001365 case kWallClockWaitNotSatisfied:
1366 // We haven't even satisfied the first condition, passing the
1367 // wall-clock-based waiting period, so we should defer the downloads
1368 // until that happens.
1369 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1370 return true;
1371
1372 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1373 LOG(INFO) << "wall-clock-based-wait satisfied and "
1374 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001375 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001376
1377 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1378 // Wall-clock-based waiting period is satisfied, and it's determined
1379 // that we do not need the update-check-based wait. so no need to
1380 // defer downloads.
1381 LOG(INFO) << "wall-clock-based-wait satisfied and "
1382 << "update-check-based-wait is not required.";
1383 return false;
1384
1385 default:
1386 // Returning false for this default case so we err on the
1387 // side of downloading updates than deferring in case of any bugs.
1388 NOTREACHED();
1389 return false;
1390 }
1391}
1392
1393OmahaRequestAction::WallClockWaitResult
1394OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001395 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001396 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001397 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001398
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001399 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1400 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1401 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001402 // Note: This timestamp could be that of ANY update we saw in the past
1403 // (not necessarily this particular update we're considering to apply)
1404 // but never got to apply because of some reason (e.g. stop AU policy,
1405 // updates being pulled out from Omaha, changes in target version prefix,
1406 // new update being rolled out, etc.). But for the purposes of scattering
1407 // it doesn't matter which update the timestamp corresponds to. i.e.
1408 // the clock starts ticking the first time we see an update and we're
1409 // ready to apply when the random wait period is satisfied relative to
1410 // that first seen timestamp.
1411 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1412 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1413 << utils::ToString(update_first_seen_at);
1414 } else {
1415 // This seems like an unexpected error where the persisted value exists
1416 // but it's not readable for some reason. Just skip scattering in this
1417 // case to be safe.
1418 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1419 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1420 }
1421 } else {
Sen Jiang7c1171e2016-06-23 11:35:40 -07001422 update_first_seen_at = system_state_->clock()->GetWallclockTime();
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001423 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001424 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1425 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001426 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1427 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001428 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001429 // This seems like an unexpected error where the value cannot be
1430 // persisted for some reason. Just skip scattering in this
1431 // case to be safe.
1432 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1433 << utils::ToString(update_first_seen_at)
1434 << " cannot be persisted";
1435 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1436 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001437 }
1438
Sen Jiang7c1171e2016-06-23 11:35:40 -07001439 TimeDelta elapsed_time =
1440 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1441 TimeDelta max_scatter_period =
1442 TimeDelta::FromDays(output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001443
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001444 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001445 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001446 << ", Time Elapsed = "
1447 << utils::FormatSecs(elapsed_time.InSeconds())
1448 << ", MaxDaysToScatter = "
1449 << max_scatter_period.InDays();
1450
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001451 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001452 // The deadline is set for all rules which serve a delta update from a
1453 // previous FSI, which means this update will be applied mostly in OOBE
1454 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1455 // quickly.
1456 LOG(INFO) << "Not scattering as deadline flag is set";
1457 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1458 }
1459
1460 if (max_scatter_period.InDays() == 0) {
1461 // This means the Omaha rule creator decides that this rule
1462 // should not be scattered irrespective of the policy.
1463 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1464 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1465 }
1466
1467 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001468 // This means we've waited more than the upperbound wait in the rule
1469 // from the time we first saw a valid update available to us.
1470 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001471 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1472 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1473 }
1474
1475 // This means we are required to participate in scattering.
1476 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001477 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001478 if (remaining_wait_time.InSeconds() <= 0) {
1479 // Yes, it's our turn now.
1480 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1481
1482 // But we can't download until the update-check-count-based wait is also
1483 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001484 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001485 kWallClockWaitDoneButUpdateCheckWaitRequired :
1486 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1487 }
1488
1489 // Not our turn yet, so we have to wait until our turn to
1490 // help scatter the downloads across all clients of the enterprise.
1491 LOG(INFO) << "Update deferred for another "
1492 << utils::FormatSecs(remaining_wait_time.InSeconds())
1493 << " per policy.";
1494 return kWallClockWaitNotSatisfied;
1495}
1496
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001497bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001498 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001499
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001500 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1501 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1502 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001503 // We are unable to read the update check count from file for some reason.
1504 // So let's proceed anyway so as to not stall the update.
1505 LOG(ERROR) << "Unable to read update check count. "
1506 << "Skipping update-check-count-based-wait.";
1507 return true;
1508 }
1509 } else {
1510 // This file does not exist. This means we haven't started our update
1511 // check count down yet, so this is the right time to start the count down.
1512 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001513 params_->min_update_checks_needed(),
1514 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001515
1516 LOG(INFO) << "Randomly picked update check count value = "
1517 << update_check_count_value;
1518
1519 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001520 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1521 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001522 // We weren't able to write the update check count file for some reason.
1523 // So let's proceed anyway so as to not stall the update.
1524 LOG(ERROR) << "Unable to write update check count. "
1525 << "Skipping update-check-count-based-wait.";
1526 return true;
1527 }
1528 }
1529
1530 if (update_check_count_value == 0) {
1531 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1532 return true;
1533 }
1534
1535 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001536 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001537 // We err on the side of skipping scattering logic instead of stalling
1538 // a machine from receiving any updates in case of any unexpected state.
1539 LOG(ERROR) << "Invalid value for update check count detected. "
1540 << "Skipping update-check-count-based-wait.";
1541 return true;
1542 }
1543
1544 // Legal value, we need to wait for more update checks to happen
1545 // until this becomes 0.
1546 LOG(INFO) << "Deferring Omaha updates for another "
1547 << update_check_count_value
1548 << " update checks per policy";
1549 return false;
1550}
1551
David Zeuthen639aa362014-02-03 16:23:44 -08001552// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001553bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001554 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001555 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001556 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001557 &elapsed_days))
1558 return false;
1559
1560 if (elapsed_days < 0)
1561 return false;
1562
1563 output_object->install_date_days = elapsed_days;
1564 return true;
1565}
1566
1567// static
1568bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1569 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001570 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001571 return false;
1572
1573 return prefs->Exists(kPrefsInstallDateDays);
1574}
1575
1576// static
1577bool OmahaRequestAction::PersistInstallDate(
1578 SystemState *system_state,
1579 int install_date_days,
1580 InstallDateProvisioningSource source) {
1581 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1582
1583 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001584 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001585 return false;
1586
1587 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1588 return false;
1589
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001590 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001591 static_cast<int>(source), // Sample.
1592 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001593 return true;
1594}
1595
Alex Deymo8e18f932015-03-27 16:16:59 -07001596bool OmahaRequestAction::PersistCohortData(
1597 const string& prefs_key,
1598 const string& new_value) {
1599 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1600 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1601 return system_state_->prefs()->Delete(prefs_key);
1602 } else if (!new_value.empty()) {
1603 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1604 return system_state_->prefs()->SetString(prefs_key, new_value);
1605 }
1606 return true;
1607}
1608
Alex Deymob3fa53b2016-04-18 19:57:58 -07001609bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
1610 auto eol_attr = attrs.find(kEolAttr);
1611 if (eol_attr != attrs.end()) {
1612 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1613 eol_attr->second);
1614 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1615 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1616 }
1617 return true;
1618}
1619
David Zeuthen33bae492014-02-25 16:16:18 -08001620void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1621 // We only want to report this on "update check".
1622 if (ping_only_ || event_ != nullptr)
1623 return;
1624
1625 metrics::CheckResult result = metrics::CheckResult::kUnset;
1626 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1627 metrics::DownloadErrorCode download_error_code =
1628 metrics::DownloadErrorCode::kUnset;
1629
1630 // Regular update attempt.
1631 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001632 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001633 // OK, we parsed the response successfully but that does
1634 // necessarily mean that an update is available.
1635 if (HasOutputPipe()) {
1636 const OmahaResponse& response = GetOutputObject();
1637 if (response.update_exists) {
1638 result = metrics::CheckResult::kUpdateAvailable;
1639 reaction = metrics::CheckReaction::kUpdating;
1640 } else {
1641 result = metrics::CheckResult::kNoUpdateAvailable;
1642 }
1643 } else {
1644 result = metrics::CheckResult::kNoUpdateAvailable;
1645 }
1646 break;
1647
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001648 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
Weidong Guo421ff332017-04-17 10:08:38 -07001649 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
David Zeuthen33bae492014-02-25 16:16:18 -08001650 result = metrics::CheckResult::kUpdateAvailable;
1651 reaction = metrics::CheckReaction::kIgnored;
1652 break;
1653
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001654 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001655 result = metrics::CheckResult::kUpdateAvailable;
1656 reaction = metrics::CheckReaction::kDeferring;
1657 break;
1658
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001659 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001660 result = metrics::CheckResult::kUpdateAvailable;
1661 reaction = metrics::CheckReaction::kBackingOff;
1662 break;
1663
1664 default:
1665 // We report two flavors of errors, "Download errors" and "Parsing
1666 // error". Try to convert to the former and if that doesn't work
1667 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001668 metrics::DownloadErrorCode tmp_error =
1669 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001670 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1671 result = metrics::CheckResult::kDownloadError;
1672 download_error_code = tmp_error;
1673 } else {
1674 result = metrics::CheckResult::kParsingError;
1675 }
1676 break;
1677 }
1678
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001679 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1680 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001681}
1682
Chris Sosa77f79e82014-06-02 18:16:24 -07001683bool OmahaRequestAction::ShouldIgnoreUpdate(
Weidong Guo421ff332017-04-17 10:08:38 -07001684 ErrorCode* error, const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001685 // Note: policy decision to not update to a version we rolled back from.
1686 string rollback_version =
1687 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001688 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001689 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001690 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001691 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001692 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001693 return true;
1694 }
1695 }
1696
Weidong Guo421ff332017-04-17 10:08:38 -07001697 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001698 LOG(INFO) << "Update is not allowed over current connection.";
1699 return true;
1700 }
1701
1702 // Note: We could technically delete the UpdateFirstSeenAt state when we
1703 // return true. If we do, it'll mean a device has to restart the
1704 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1705 // turned on again. On the other hand, it also increases the chance of update
1706 // starvation if an admin turns AU on/off more frequently. We choose to err on
1707 // the side of preventing starvation at the cost of not applying scattering in
1708 // those cases.
1709 return false;
1710}
1711
Weidong Guo421ff332017-04-17 10:08:38 -07001712bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1713 const OmahaResponse& response) const {
1714 PrefsInterface* prefs = system_state_->prefs();
1715
1716 if (!prefs) {
1717 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1718 "not available.";
1719 return false;
1720 }
1721
1722 bool is_allowed;
1723
1724 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1725 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1726 is_allowed) {
1727 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1728 "set to true.";
1729 return true;
1730 }
1731
1732 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1733 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1734 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1735 "set to false or does not exist while target does not exist.";
1736 return false;
1737 }
1738
1739 std::string target_version;
1740 int64_t target_size;
1741
1742 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1743 &target_version) ||
1744 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1745 LOG(INFO) << "Disabling updates over cellular as the target version or "
1746 "size is not accessible.";
1747 return false;
1748 }
1749
1750 uint64_t total_packages_size = 0;
1751 for (const auto& package : response.packages) {
1752 total_packages_size += package.size;
1753 }
1754 if (target_version == response.version &&
1755 static_cast<uint64_t>(target_size) == total_packages_size) {
1756 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1757 "omaha response.";
1758 return true;
1759 } else {
1760 LOG(INFO) << "Disabling updates over cellular as the target does not"
1761 "match the omaha response.";
1762 return false;
1763 }
1764}
1765
1766bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1767 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001768 ConnectionType type;
1769 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001770 ConnectionManagerInterface* connection_manager =
1771 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001772 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001773 LOG(INFO) << "We could not determine our connection type. "
1774 << "Defaulting to allow updates.";
1775 return true;
1776 }
Weidong Guo421ff332017-04-17 10:08:38 -07001777
Chris Sosa77f79e82014-06-02 18:16:24 -07001778 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001779 bool is_device_policy_set =
1780 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1781 // Treats tethered connection as if it is cellular connection.
1782 bool is_over_cellular = type == ConnectionType::kCellular ||
1783 tethering == ConnectionTethering::kConfirmed;
1784
1785 if (!is_over_cellular) {
1786 // There's no need to further check user preferences as we are not over
1787 // cellular connection.
1788 if (!is_allowed)
1789 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1790 } else if (is_device_policy_set) {
1791 // There's no need to further check user preferences as the device policy
1792 // is set regarding updates over cellular.
1793 if (!is_allowed)
1794 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1795 } else {
1796 // Deivce policy is not set, so user preferences overwrite whether to
1797 // allow updates over cellular.
1798 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1799 if (!is_allowed)
1800 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1801 }
1802
Chris Sosa77f79e82014-06-02 18:16:24 -07001803 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001804 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001805 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1806 return is_allowed;
1807}
1808
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001809bool OmahaRequestAction::IsRollbackEnabled() const {
1810 if (policy_provider_->IsConsumerDevice()) {
1811 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1812 return false;
1813 }
1814
1815 if (!policy_provider_->device_policy_is_loaded()) {
1816 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1817 return true;
1818 }
1819
1820 int allowed_milestones;
1821 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1822 &allowed_milestones)) {
1823 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1824 "Defaulting to rollback enabled.";
1825 return true;
1826 }
1827
1828 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1829 return allowed_milestones > 0;
1830}
1831
1832void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
1833 bool max_rollforward_set = false;
1834 if (IsRollbackEnabled()) {
1835 // If rollback is enabled, set the max kernel key version to the current
1836 // kernel key version. This has the effect of freezing kernel key roll
1837 // forwards.
1838 //
1839 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1840 // key roll forward happens until the server side components of rollback
1841 // are implemented. Future changes will allow the Omaha server to return
1842 // the kernel key version from max_rollback_versions in the past. At that
1843 // point the max kernel key version will be set to that value, creating a
1844 // sliding window of versions that can be rolled back to.
1845 int min_kernel_version =
1846 system_state_->hardware()->GetMinKernelKeyVersion();
1847 LOG(INFO) << "Rollback is enabled. Setting max_kernel_rollforward to "
1848 << min_kernel_version;
1849 max_rollforward_set = system_state_->hardware()->SetMaxKernelKeyRollforward(
1850 min_kernel_version);
1851 } else {
1852 // For devices that are not rollback enabled (ie. consumer devices), the
1853 // max kernel key version is set to 0xfffffffe, which is logically
1854 // infinity. This maintains the previous behavior that that kernel key
1855 // versions roll forward each time they are incremented.
1856 LOG(INFO) << "Rollback is disabled. Setting max_kernel_rollforward to "
1857 << kRollforwardInfinity;
1858 max_rollforward_set = system_state_->hardware()->SetMaxKernelKeyRollforward(
1859 kRollforwardInfinity);
1860 }
1861
1862 if (!max_rollforward_set) {
1863 LOG(ERROR) << "Failed to set max_kernel_rollforward";
1864 }
1865}
1866
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001867} // namespace chromeos_update_engine