blob: 9021e3f085edf98d11f55c9b8c13646ca4618a3c [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";
Marton Hunyady199152d2018-05-07 19:08:48 +020091static const char* kRollback = "rollback";
92static const char* kFirmwareVersion = "firmware_version";
93static const char* kKernelVersion = "kernel_version";
Alex Deymob3fa53b2016-04-18 19:57:58 -070094
Alex Deymoac41a822015-09-15 20:52:53 -070095namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +000096
Darin Petkov1cbd78f2010-07-29 12:38:34 -070097// Returns an XML ping element attribute assignment with attribute
98// |name| and value |ping_days| if |ping_days| has a value that needs
99// to be sent, or an empty string otherwise.
100string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700101 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700102 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700103 return "";
104}
105
106// Returns an XML ping element if any of the elapsed days need to be
107// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700108string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700109 string ping_active = GetPingAttribute("a", ping_active_days);
110 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
111 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700112 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700113 ping_active.c_str(),
114 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700115 }
116 return "";
117}
118
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700119// Returns an XML that goes into the body of the <app> element of the Omaha
120// request based on the given parameters.
121string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700122 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700123 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700124 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700125 int ping_active_days,
126 int ping_roll_call_days,
127 PrefsInterface* prefs) {
128 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700129 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700130 if (include_ping)
131 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700132 if (!ping_only) {
Marton Hunyadyba51c3f2018-04-25 15:18:10 +0200133 app_body += " <updatecheck";
134 if (!params->target_version_prefix().empty()) {
135 app_body += base::StringPrintf(
136 " targetversionprefix=\"%s\"",
137 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
138 // Rollback requires target_version_prefix set.
139 if (params->rollback_allowed()) {
140 app_body += " rollback_allowed=\"true\"";
141 }
142 }
143 app_body += "></updatecheck>\n";
Jay Srinivasan0a708742012-03-20 11:26:12 -0700144
Darin Petkov265f2902011-05-09 15:17:40 -0700145 // If this is the first update check after a reboot following a previous
146 // update, generate an event containing the previous version number. If
147 // the previous version preference file doesn't exist the event is still
148 // generated with a previous version of 0.0.0.0 -- this is relevant for
149 // older clients or new installs. The previous version event is not sent
150 // for ping-only requests because they come before the client has
Alex Deymo87c08862015-10-30 21:56:55 -0700151 // rebooted. The previous version event is also not sent if it was already
152 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700153 string prev_version;
154 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
155 prev_version = "0.0.0.0";
156 }
Alex Deymo87c08862015-10-30 21:56:55 -0700157 // We only store a non-empty previous version value after a successful
158 // update in the previous boot. After reporting it back to the server,
159 // we clear the previous version value so it doesn't get reported again.
160 if (!prev_version.empty()) {
161 app_body += base::StringPrintf(
162 " <event eventtype=\"%d\" eventresult=\"%d\" "
163 "previousversion=\"%s\"></event>\n",
Alex Deymo9fded1e2015-11-05 12:31:19 -0800164 OmahaEvent::kTypeRebootedAfterUpdate,
165 OmahaEvent::kResultSuccess,
Alex Deymo87c08862015-10-30 21:56:55 -0700166 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
167 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
168 << "Unable to reset the previous version.";
169 }
Darin Petkov95508da2011-01-05 12:42:29 -0800170 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700171 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800172 // The error code is an optional attribute so append it only if the result
173 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700174 string error_code;
175 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700176 error_code = base::StringPrintf(" errorcode=\"%d\"",
177 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700178 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700179 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700180 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700181 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700182 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700183
184 return app_body;
185}
186
Alex Deymo8e18f932015-03-27 16:16:59 -0700187// Returns the cohort* argument to include in the <app> tag for the passed
188// |arg_name| and |prefs_key|, if any. The return value is suitable to
189// concatenate to the list of arguments and includes a space at the end.
190string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700191 const string arg_name,
192 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700193 // There's nothing wrong with not having a given cohort setting, so we check
194 // existance first to avoid the warning log message.
195 if (!prefs->Exists(prefs_key))
196 return "";
197 string cohort_value;
198 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
199 return "";
200 // This is a sanity check to avoid sending a huge XML file back to Ohama due
201 // to a compromised stateful partition making the update check fail in low
202 // network environments envent after a reboot.
203 if (cohort_value.size() > 1024) {
204 LOG(WARNING) << "The omaha cohort setting " << arg_name
205 << " has a too big value, which must be an error or an "
206 "attacker trying to inhibit updates.";
207 return "";
208 }
209
Alex Deymob0d74eb2015-03-30 17:59:17 -0700210 string escaped_xml_value;
211 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
212 LOG(WARNING) << "The omaha cohort setting " << arg_name
213 << " is ASCII-7 invalid, ignoring it.";
214 return "";
215 }
216
Alex Deymo8e18f932015-03-27 16:16:59 -0700217 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700218 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700219}
220
Sen Jiang94a4dec2017-03-28 18:23:35 -0700221struct OmahaAppData {
222 string id;
223 string version;
Sen Jiang684c9cd2017-10-17 16:26:45 -0700224 string product_components;
Sen Jiang94a4dec2017-03-28 18:23:35 -0700225};
226
Sen Jiang684c9cd2017-10-17 16:26:45 -0700227bool IsValidComponentID(const string& id) {
228 for (char c : id) {
229 if (!isalnum(c) && c != '-' && c != '_' && c != '.')
230 return false;
231 }
232 return true;
233}
234
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700235// Returns an XML that corresponds to the entire <app> node of the Omaha
236// request based on the given parameters.
237string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700238 OmahaRequestParams* params,
Sen Jiang94a4dec2017-03-28 18:23:35 -0700239 const OmahaAppData& app_data,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700240 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700241 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700242 int ping_active_days,
243 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800244 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700245 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700246 string app_body = GetAppBody(event, params, ping_only, include_ping,
247 ping_active_days, ping_roll_call_days,
248 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700249 string app_versions;
250
Sen Jiang8cd42342018-01-31 12:06:59 -0800251 // If we are downgrading to a more stable channel and we are allowed to do
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700252 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
253 // highest-versioned payload on the destination channel.
Sen Jiang8500d3a2018-02-08 12:04:05 -0800254 if (params->ShouldPowerwash()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700255 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
256 << "on downgrading to the version in the more stable channel";
257 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700258 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700259 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700260 app_versions = "version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700261 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700262 }
263
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700264 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700265 string app_channels =
266 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
267 if (params->current_channel() != download_channel) {
268 app_channels += "from_track=\"" + XmlEncodeWithDefault(
269 params->current_channel(), "") + "\" ";
270 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700271
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700272 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700273
David Zeuthen639aa362014-02-03 16:23:44 -0800274 // If install_date_days is not set (e.g. its value is -1 ), don't
275 // include the attribute.
276 string install_date_in_days_str = "";
277 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700278 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
279 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800280 }
281
Alex Deymo8e18f932015-03-27 16:16:59 -0700282 string app_cohort_args;
283 app_cohort_args += GetCohortArgXml(system_state->prefs(),
284 "cohort", kPrefsOmahaCohort);
285 app_cohort_args += GetCohortArgXml(system_state->prefs(),
286 "cohorthint", kPrefsOmahaCohortHint);
287 app_cohort_args += GetCohortArgXml(system_state->prefs(),
288 "cohortname", kPrefsOmahaCohortName);
289
Alex Deymoebf6e122017-03-10 16:12:01 -0800290 string fingerprint_arg;
291 if (!params->os_build_fingerprint().empty()) {
Sen Jiang8cd42342018-01-31 12:06:59 -0800292 fingerprint_arg = "fingerprint=\"" +
293 XmlEncodeWithDefault(params->os_build_fingerprint(), "") +
294 "\" ";
Alex Deymoebf6e122017-03-10 16:12:01 -0800295 }
296
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700297 string buildtype_arg;
298 if (!params->os_build_type().empty()) {
299 buildtype_arg = "os_build_type=\"" +
300 XmlEncodeWithDefault(params->os_build_type(), "") + "\" ";
301 }
302
Sen Jiang684c9cd2017-10-17 16:26:45 -0700303 string product_components_args;
Sen Jiang8500d3a2018-02-08 12:04:05 -0800304 if (!params->ShouldPowerwash() && !app_data.product_components.empty()) {
Sen Jiang684c9cd2017-10-17 16:26:45 -0700305 brillo::KeyValueStore store;
306 if (store.LoadFromString(app_data.product_components)) {
307 for (const string& key : store.GetKeys()) {
308 if (!IsValidComponentID(key)) {
309 LOG(ERROR) << "Invalid component id: " << key;
310 continue;
311 }
312 string version;
313 if (!store.GetString(key, &version)) {
314 LOG(ERROR) << "Failed to get version for " << key
315 << " in product_components.";
316 continue;
317 }
318 product_components_args +=
319 base::StringPrintf("_%s.version=\"%s\" ",
320 key.c_str(),
321 XmlEncodeWithDefault(version, "").c_str());
322 }
323 } else {
324 LOG(ERROR) << "Failed to parse product_components:\n"
325 << app_data.product_components;
326 }
327 }
328
329 // clang-format off
Alex Deymob0d74eb2015-03-30 17:59:17 -0700330 string app_xml = " <app "
Sen Jiang94a4dec2017-03-28 18:23:35 -0700331 "appid=\"" + XmlEncodeWithDefault(app_data.id, "") + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700332 app_cohort_args +
333 app_versions +
334 app_channels +
Sen Jiang684c9cd2017-10-17 16:26:45 -0700335 product_components_args +
Alex Deymoebf6e122017-03-10 16:12:01 -0800336 fingerprint_arg +
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700337 buildtype_arg +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700338 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
339 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
340 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
341 "delta_okay=\"" + delta_okay_str + "\" "
342 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
343 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
344 install_date_in_days_str +
345 ">\n" +
346 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700347 " </app>\n";
Sen Jiang684c9cd2017-10-17 16:26:45 -0700348 // clang-format on
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700349 return app_xml;
350}
351
352// Returns an XML that corresponds to the entire <os> node of the Omaha
353// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700354string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700355 string os_xml =" <os "
356 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
357 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
358 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
359 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700360 return os_xml;
361}
362
363// Returns an XML that corresponds to the entire Omaha request based on the
364// given parameters.
365string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700366 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700367 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700368 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700369 int ping_active_days,
370 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800371 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700372 SystemState* system_state) {
373 string os_xml = GetOsXml(params);
Sen Jiang684c9cd2017-10-17 16:26:45 -0700374 OmahaAppData product_app = {
375 .id = params->GetAppId(),
376 .version = params->app_version(),
377 .product_components = params->product_components()};
Sen Jiang94a4dec2017-03-28 18:23:35 -0700378 string app_xml = GetAppXml(event,
379 params,
380 product_app,
381 ping_only,
382 include_ping,
383 ping_active_days,
384 ping_roll_call_days,
385 install_date_in_days,
386 system_state);
387 if (!params->system_app_id().empty()) {
388 OmahaAppData system_app = {.id = params->system_app_id(),
389 .version = params->system_version()};
390 app_xml += GetAppXml(event,
391 params,
392 system_app,
393 ping_only,
394 include_ping,
395 ping_active_days,
396 ping_roll_call_days,
397 install_date_in_days,
398 system_state);
399 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700400
Alex Vakulenko75039d72014-03-25 12:36:28 -0700401 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700402 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700403
Alex Deymoac41a822015-09-15 20:52:53 -0700404 string updater_version = XmlEncodeWithDefault(
405 base::StringPrintf("%s-%s",
406 constants::kOmahaUpdaterID,
407 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700408 string request_xml =
409 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700410 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700411 "version=\"" + updater_version + "\" "
412 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700413 install_source +
414 "ismachine=\"1\">\n") +
415 os_xml +
416 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700417 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700418
419 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000420}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700421
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700422} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000423
David Zeuthene8ed8632014-07-24 13:38:10 -0400424// Struct used for holding data obtained when parsing the XML.
425struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400426 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
427
428 // Pointer to the expat XML_Parser object.
429 XML_Parser xml_parser;
430
David Zeuthene8ed8632014-07-24 13:38:10 -0400431 // This is the state of the parser as it's processing the XML.
432 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400433 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400434 string current_path;
435
436 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400437 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700438 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400439 string daystart_elapsed_days;
440 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800441
Sen Jiang81259682017-03-30 15:11:30 -0700442 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700443 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700444 vector<string> url_codebase;
445 string manifest_version;
446 map<string, string> action_postinstall_attrs;
447 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700448 string cohort;
449 string cohorthint;
450 string cohortname;
451 bool cohort_set = false;
452 bool cohorthint_set = false;
453 bool cohortname_set = false;
Sen Jiang81259682017-03-30 15:11:30 -0700454
455 struct Package {
456 string name;
457 string size;
458 string hash;
459 };
460 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800461 };
Sen Jiang81259682017-03-30 15:11:30 -0700462 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400463};
464
465namespace {
466
467// Callback function invoked by expat.
468void ParserHandlerStart(void* user_data, const XML_Char* element,
469 const XML_Char** attr) {
470 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
471
472 if (data->failed)
473 return;
474
475 data->current_path += string("/") + element;
476
477 map<string, string> attrs;
478 if (attr != nullptr) {
479 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
480 string key = attr[n];
481 string value = attr[n + 1];
482 attrs[key] = value;
483 }
484 }
485
Alex Deymo8e18f932015-03-27 16:16:59 -0700486 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700487 OmahaParserData::App app;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700488 if (attrs.find("appid") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700489 app.id = attrs["appid"];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700490 }
Alex Deymo8e18f932015-03-27 16:16:59 -0700491 if (attrs.find("cohort") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700492 app.cohort_set = true;
493 app.cohort = attrs["cohort"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700494 }
495 if (attrs.find("cohorthint") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700496 app.cohorthint_set = true;
497 app.cohorthint = attrs["cohorthint"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700498 }
499 if (attrs.find("cohortname") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700500 app.cohortname_set = true;
501 app.cohortname = attrs["cohortname"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700502 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700503 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700504 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700505 if (!data->apps.empty())
506 data->apps.back().updatecheck_status = attrs["status"];
507 if (data->updatecheck_poll_interval.empty())
508 data->updatecheck_poll_interval = attrs["PollInterval"];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700509 // Omaha sends arbitrary key-value pairs as extra attributes starting with
510 // an underscore.
511 for (const auto& attr : attrs) {
512 if (!attr.first.empty() && attr.first[0] == '_')
513 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
514 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400515 } else if (data->current_path == "/response/daystart") {
516 // Get the install-date.
517 data->daystart_elapsed_days = attrs["elapsed_days"];
518 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
519 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
520 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700521 if (!data->apps.empty())
522 data->apps.back().url_codebase.push_back(attrs["codebase"]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800523 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400524 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800525 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700526 if (!data->apps.empty())
527 data->apps.back().packages.push_back({.name = attrs["name"],
528 .size = attrs["size"],
529 .hash = attrs["hash_sha256"]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400530 } else if (data->current_path == "/response/app/updatecheck/manifest") {
531 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700532 if (!data->apps.empty())
533 data->apps.back().manifest_version = attrs[kTagVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400534 } else if (data->current_path ==
535 "/response/app/updatecheck/manifest/actions/action") {
536 // We only care about the postinstall action.
Sen Jiang81259682017-03-30 15:11:30 -0700537 if (attrs["event"] == "postinstall" && !data->apps.empty()) {
538 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400539 }
540 }
541}
542
543// Callback function invoked by expat.
544void ParserHandlerEnd(void* user_data, const XML_Char* element) {
545 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
546 if (data->failed)
547 return;
548
549 const string path_suffix = string("/") + element;
550
Alex Vakulenko0103c362016-01-20 07:56:15 -0800551 if (!base::EndsWith(data->current_path, path_suffix,
552 base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400553 LOG(ERROR) << "Unexpected end element '" << element
554 << "' with current_path='" << data->current_path << "'";
555 data->failed = true;
556 return;
557 }
558 data->current_path.resize(data->current_path.size() - path_suffix.size());
559}
560
David Zeuthenf3e28012014-08-26 18:23:52 -0400561// Callback function invoked by expat.
562//
563// This is called for entity declarations. Since Omaha is guaranteed
564// to never return any XML with entities our course of action is to
565// just stop parsing. This avoids potential resource exhaustion
566// problems AKA the "billion laughs". CVE-2013-0340.
567void ParserHandlerEntityDecl(void *user_data,
568 const XML_Char *entity_name,
569 int is_parameter_entity,
570 const XML_Char *value,
571 int value_length,
572 const XML_Char *base,
573 const XML_Char *system_id,
574 const XML_Char *public_id,
575 const XML_Char *notation_name) {
576 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
577
578 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
579 data->failed = true;
580 data->entity_decl = true;
581 XML_StopParser(data->xml_parser, false);
582}
583
David Zeuthene8ed8632014-07-24 13:38:10 -0400584} // namespace
585
Alex Deymob0d74eb2015-03-30 17:59:17 -0700586bool XmlEncode(const string& input, string* output) {
587 if (std::find_if(input.begin(), input.end(),
588 [](const char c){return c & 0x80;}) != input.end()) {
589 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
590 utils::HexDumpString(input);
591 return false;
592 }
Alex Deymocc457852015-06-18 18:35:50 -0700593 output->clear();
594 // We need at least input.size() space in the output, but the code below will
595 // handle it if we need more.
596 output->reserve(input.size());
597 for (char c : input) {
598 switch (c) {
599 case '\"':
600 output->append("&quot;");
601 break;
602 case '\'':
603 output->append("&apos;");
604 break;
605 case '&':
606 output->append("&amp;");
607 break;
608 case '<':
609 output->append("&lt;");
610 break;
611 case '>':
612 output->append("&gt;");
613 break;
614 default:
615 output->push_back(c);
616 }
617 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700618 return true;
619}
620
621string XmlEncodeWithDefault(const string& input, const string& default_value) {
622 string output;
623 if (XmlEncode(input, &output))
624 return output;
625 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000626}
627
Alex Deymoc1c17b42015-11-23 03:53:15 -0300628OmahaRequestAction::OmahaRequestAction(
629 SystemState* system_state,
630 OmahaEvent* event,
631 std::unique_ptr<HttpFetcher> http_fetcher,
632 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800633 : system_state_(system_state),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800634 params_(system_state->request_params()),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700635 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300636 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800637 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700638 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700639 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700640 ping_roll_call_days_(0) {
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800641 policy_provider_->Reload();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700642}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000643
Darin Petkov6a5b3222010-07-13 14:55:28 -0700644OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000645
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700646// Calculates the value to use for the ping days parameter.
647int OmahaRequestAction::CalculatePingDays(const string& key) {
648 int days = kNeverPinged;
649 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800650 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700651 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
652 if (days < 0) {
653 // If |days| is negative, then the system clock must have jumped
654 // back in time since the ping was sent. Mark the value so that
655 // it doesn't get sent to the server but we still update the
656 // last ping daystart preference. This way the next ping time
657 // will be correct, hopefully.
658 days = kPingTimeJump;
659 LOG(WARNING) <<
660 "System clock jumped back in time. Resetting ping daystarts.";
661 }
662 }
663 return days;
664}
665
666void OmahaRequestAction::InitPingDays() {
667 // We send pings only along with update checks, not with events.
668 if (IsEvent()) {
669 return;
670 }
671 // TODO(petkov): Figure a way to distinguish active use pings
672 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700673 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700674 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
675 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
676}
677
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700678bool OmahaRequestAction::ShouldPing() const {
679 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
680 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
681 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
682 if (powerwash_count > 0) {
683 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
684 << "powerwash_count is " << powerwash_count;
685 return false;
686 }
Amin Hassani1677e812017-06-21 13:36:36 -0700687 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
688 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
689 << "the first_active_omaha_ping_sent is true";
690 return false;
691 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700692 return true;
693 }
694 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
695}
696
David Zeuthen639aa362014-02-03 16:23:44 -0800697// static
698int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
699 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700700 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800701 return -1;
702
703 // If we have the value stored on disk, just return it.
704 int64_t stored_value;
705 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
706 // Convert and sanity-check.
707 int install_date_days = static_cast<int>(stored_value);
708 if (install_date_days >= 0)
709 return install_date_days;
710 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
711 << install_date_days << " looks suspicious.";
712 prefs->Delete(kPrefsInstallDateDays);
713 }
714
715 // Otherwise, if OOBE is not complete then do nothing and wait for
716 // ParseResponse() to call ParseInstallDate() and then
717 // PersistInstallDate() to set the kPrefsInstallDateDays state
718 // variable. Once that is done, we'll then report back in future
719 // Omaha requests. This works exactly because OOBE triggers an
720 // update check.
721 //
722 // However, if OOBE is complete and the kPrefsInstallDateDays state
723 // variable is not set, there are two possibilities
724 //
725 // 1. The update check in OOBE failed so we never got a response
726 // from Omaha (no network etc.); or
727 //
728 // 2. OOBE was done on an older version that didn't write to the
729 // kPrefsInstallDateDays state variable.
730 //
731 // In both cases, we approximate the install date by simply
732 // inspecting the timestamp of when OOBE happened.
733
734 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700735 if (!system_state->hardware()->IsOOBEEnabled() ||
736 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800737 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700738 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800739 return -1;
740 }
741
742 int num_days;
743 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
744 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
745 << "as its value '" << utils::ToString(time_of_oobe)
746 << "' looks suspicious.";
747 return -1;
748 }
749
750 // Persist this to disk, for future use.
751 if (!OmahaRequestAction::PersistInstallDate(system_state,
752 num_days,
753 kProvisionedFromOOBEMarker))
754 return -1;
755
756 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
757 << num_days << " days";
758
759 return num_days;
760}
761
Darin Petkov6a5b3222010-07-13 14:55:28 -0700762void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000763 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700764 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700765 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700766 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700767 return;
768 }
David Zeuthen639aa362014-02-03 16:23:44 -0800769
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700770 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700771 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700772 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700773 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700774 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800775 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800776 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700777 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700778
Sen Jiang42fa45e2018-03-12 11:02:14 -0700779 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700780 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
781 params_->interactive() ? "fg" : "bg");
782 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
783 http_fetcher_->SetHeader(
784 kXGoogleUpdateUpdater,
785 base::StringPrintf(
786 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
787
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800788 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
789 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700790 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700791 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700792 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000793}
794
Darin Petkov6a5b3222010-07-13 14:55:28 -0700795void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000796 http_fetcher_->TerminateTransfer();
797}
798
799// We just store the response in the buffer. Once we've received all bytes,
800// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700801void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800802 const void* bytes,
803 size_t length) {
804 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
805 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000806}
807
808namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000809
810// Parses a 64 bit base-10 int from a string and returns it. Returns 0
811// on error. If the string contains "0", that's indistinguishable from
812// error.
813off_t ParseInt(const string& str) {
814 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700815 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000816 if (rc < 1) {
817 // failure
818 return 0;
819 }
820 return ret;
821}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700822
David Zeuthene8ed8632014-07-24 13:38:10 -0400823// Parses |str| and returns |true| if, and only if, its value is "true".
824bool ParseBool(const string& str) {
825 return str == "true";
826}
827
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700828// Update the last ping day preferences based on the server daystart
829// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400830bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700831 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400832 TEST_AND_RETURN_FALSE(
833 base::StringToInt64(parser_data->daystart_elapsed_seconds,
834 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700835 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
836
837 // Remember the local time that matches the server's last midnight
838 // time.
839 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
840 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
841 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
842 return true;
843}
Sen Jiang81259682017-03-30 15:11:30 -0700844
845// Parses the package node in the given XML document and populates
846// |output_object| if valid. Returns true if we should continue the parsing.
847// False otherwise, in which case it sets any error code using |completer|.
848bool ParsePackage(OmahaParserData::App* app,
849 OmahaResponse* output_object,
850 ScopedActionCompleter* completer) {
851 if (app->updatecheck_status == "noupdate") {
852 if (!app->packages.empty()) {
853 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
854 completer->set_code(ErrorCode::kOmahaResponseInvalid);
855 return false;
856 }
857 return true;
858 }
859 if (app->packages.empty()) {
860 LOG(ERROR) << "Omaha Response has no packages";
861 completer->set_code(ErrorCode::kOmahaResponseInvalid);
862 return false;
863 }
864 if (app->url_codebase.empty()) {
865 LOG(ERROR) << "No Omaha Response URLs";
866 completer->set_code(ErrorCode::kOmahaResponseInvalid);
867 return false;
868 }
869 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
870 vector<string> metadata_sizes =
871 base::SplitString(app->action_postinstall_attrs[kTagMetadataSize],
872 ":",
873 base::TRIM_WHITESPACE,
874 base::SPLIT_WANT_ALL);
875 vector<string> metadata_signatures =
876 base::SplitString(app->action_postinstall_attrs[kTagMetadataSignatureRsa],
877 ":",
878 base::TRIM_WHITESPACE,
879 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700880 vector<string> is_delta_payloads =
881 base::SplitString(app->action_postinstall_attrs[kTagIsDeltaPayload],
882 ":",
883 base::TRIM_WHITESPACE,
884 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700885 for (size_t i = 0; i < app->packages.size(); i++) {
886 const auto& package = app->packages[i];
887 if (package.name.empty()) {
888 LOG(ERROR) << "Omaha Response has empty package name";
889 completer->set_code(ErrorCode::kOmahaResponseInvalid);
890 return false;
891 }
892 LOG(INFO) << "Found package " << package.name;
893
894 OmahaResponse::Package out_package;
895 for (const string& codebase : app->url_codebase) {
896 if (codebase.empty()) {
897 LOG(ERROR) << "Omaha Response URL has empty codebase";
898 completer->set_code(ErrorCode::kOmahaResponseInvalid);
899 return false;
900 }
901 out_package.payload_urls.push_back(codebase + package.name);
902 }
903 // Parse the payload size.
904 base::StringToUint64(package.size, &out_package.size);
905 if (out_package.size <= 0) {
906 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
907 completer->set_code(ErrorCode::kOmahaResponseInvalid);
908 return false;
909 }
910 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
911
912 if (i < metadata_sizes.size())
913 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
914 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
915 << " bytes";
916
917 if (i < metadata_signatures.size())
918 out_package.metadata_signature = metadata_signatures[i];
919 LOG(INFO) << "Payload metadata signature = "
920 << out_package.metadata_signature;
921
922 out_package.hash = package.hash;
923 if (out_package.hash.empty()) {
924 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
925 completer->set_code(ErrorCode::kOmahaResponseInvalid);
926 return false;
927 }
928 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700929
930 if (i < is_delta_payloads.size())
931 out_package.is_delta = ParseBool(is_delta_payloads[i]);
932 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
933
Sen Jiang81259682017-03-30 15:11:30 -0700934 output_object->packages.push_back(std::move(out_package));
935 }
936
937 return true;
938}
939
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700940} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000941
David Zeuthene8ed8632014-07-24 13:38:10 -0400942bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700943 OmahaResponse* output_object,
944 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700945 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700946 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700947 return false;
948 }
Sen Jiang81259682017-03-30 15:11:30 -0700949 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700950
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800951 // chromium-os:37289: The PollInterval is not supported by Omaha server
952 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700953 // slow down the request rate from the server-side. Note that the PollInterval
954 // is not persisted, so it has to be sent by the server on every response to
955 // guarantee that the scheduler uses this value (otherwise, if the device got
956 // rebooted after the last server-indicated value, it'll revert to the default
957 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
958 // based on the assumption that we perform an update check every hour so that
959 // the max value of 8 will roughly be equivalent to one work day. If we decide
960 // to use PollInterval permanently, we should update the
961 // max_update_checks_allowed to take PollInterval into account. Note: The
962 // parsing for PollInterval happens even before parsing of the status because
963 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400964 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700965 &output_object->poll_interval);
966
David Zeuthen639aa362014-02-03 16:23:44 -0800967 // Check for the "elapsed_days" attribute in the "daystart"
968 // element. This is the number of days since Jan 1 2007, 0:00
969 // PST. If we don't have a persisted value of the Omaha InstallDate,
970 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400971 if (ParseInstallDate(parser_data, output_object) &&
972 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800973 // Since output_object->install_date_days is never negative, the
974 // elapsed_days -> install-date calculation is reduced to simply
975 // rounding down to the nearest number divisible by 7.
976 int remainder = output_object->install_date_days % 7;
977 int install_date_days_rounded =
978 output_object->install_date_days - remainder;
979 if (PersistInstallDate(system_state_,
980 install_date_days_rounded,
981 kProvisionedFromOmahaResponse)) {
982 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
983 << install_date_days_rounded << " days";
984 }
985 }
986
Alex Deymo00d79ac2015-06-29 15:41:49 -0700987 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -0700988 for (const auto& app : parser_data->apps) {
989 if (app.id == params_->GetAppId()) {
990 if (app.cohort_set)
991 PersistCohortData(kPrefsOmahaCohort, app.cohort);
992 if (app.cohorthint_set)
993 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
994 if (app.cohortname_set)
995 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
996 break;
997 }
998 }
Alex Deymo00d79ac2015-06-29 15:41:49 -0700999
Alex Deymob3fa53b2016-04-18 19:57:58 -07001000 // Parse the updatecheck attributes.
1001 PersistEolStatus(parser_data->updatecheck_attrs);
Marton Hunyady199152d2018-05-07 19:08:48 +02001002 // Rollback-related updatecheck attributes.
1003 // Defaults to false if attribute is not present.
1004 output_object->is_rollback =
1005 ParseBool(parser_data->updatecheck_attrs[kRollback]);
1006 // Defaults to 0 if attribute is not present. This is fine for these values,
1007 // because it's the lowest possible value, and the rollback image won't be
1008 // installed, if the values in the TPM are larger than these, and in case the
1009 // values in the TPM are 0, all images will be able to boot up.
1010 output_object->firmware_version = static_cast<uint32_t>(
1011 ParseInt(parser_data->updatecheck_attrs[kFirmwareVersion]));
1012 output_object->kernel_version = static_cast<uint32_t>(
1013 ParseInt(parser_data->updatecheck_attrs[kKernelVersion]));
Alex Deymob3fa53b2016-04-18 19:57:58 -07001014
David Zeuthene8ed8632014-07-24 13:38:10 -04001015 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001016 return false;
1017
David Zeuthene8ed8632014-07-24 13:38:10 -04001018 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001019 return false;
1020
Sen Jiang0affc2c2017-02-10 15:55:05 -08001021 // Package has to be parsed after Params now because ParseParams need to make
1022 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -07001023 for (auto& app : parser_data->apps)
1024 if (!ParsePackage(&app, output_object, completer))
1025 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001026
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001027 return true;
1028}
1029
David Zeuthene8ed8632014-07-24 13:38:10 -04001030bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001031 OmahaResponse* output_object,
1032 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001033 output_object->update_exists = false;
1034 for (size_t i = 0; i < parser_data->apps.size(); i++) {
1035 const string& status = parser_data->apps[i].updatecheck_status;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001036 if (status == "noupdate") {
1037 // Don't update if any app has status="noupdate".
Sen Jiang81259682017-03-30 15:11:30 -07001038 LOG(INFO) << "No update for <app> " << i;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001039 output_object->update_exists = false;
1040 break;
Sen Jiang81259682017-03-30 15:11:30 -07001041 } else if (status == "ok") {
Sen Jiang00adf7b2017-06-26 15:57:29 -07001042 if (parser_data->apps[i].action_postinstall_attrs["noupdate"] == "true") {
1043 // noupdate="true" in postinstall attributes means it's an update to
1044 // self, only update if there's at least one app really have update.
1045 LOG(INFO) << "Update to self for <app> " << i;
1046 } else {
1047 LOG(INFO) << "Update for <app> " << i;
1048 output_object->update_exists = true;
1049 }
Sen Jiang81259682017-03-30 15:11:30 -07001050 } else {
1051 LOG(ERROR) << "Unknown Omaha response status: " << status;
1052 completer->set_code(ErrorCode::kOmahaResponseInvalid);
1053 return false;
1054 }
1055 }
1056 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001057 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001058 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001059 }
1060
Sen Jiang81259682017-03-30 15:11:30 -07001061 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001062}
1063
David Zeuthene8ed8632014-07-24 13:38:10 -04001064bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001065 OmahaResponse* output_object,
1066 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001067 map<string, string> attrs;
1068 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001069 if (app.id == params_->GetAppId()) {
1070 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -07001071 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001072 } else if (!params_->system_app_id().empty() &&
1073 app.id == params_->system_app_id()) {
1074 // this is the system app (this check is intentionally skipped if there is
1075 // no system_app_id set)
1076 output_object->system_version = app.manifest_version;
1077 }
1078 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -07001079 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001080 }
Sen Jiang81259682017-03-30 15:11:30 -07001081 }
Chris Sosa3b748432013-06-20 16:42:59 -07001082 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -07001083 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001084 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -07001085 return false;
1086 }
1087
1088 LOG(INFO) << "Received omaha response to update to version "
1089 << output_object->version;
1090
David Zeuthene8ed8632014-07-24 13:38:10 -04001091 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001092 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001093 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001094 return false;
1095 }
1096
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001097 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -04001098 output_object->more_info_url = attrs[kTagMoreInfo];
David Zeuthene8ed8632014-07-24 13:38:10 -04001099 output_object->prompt = ParseBool(attrs[kTagPrompt]);
1100 output_object->deadline = attrs[kTagDeadline];
1101 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001102 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -04001103 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001104 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -04001105 ParseBool(attrs[kTagDisableP2PForSharing]);
1106 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001107
David Zeuthene8ed8632014-07-24 13:38:10 -04001108 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -08001109 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001110 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001111
Jay Srinivasan08262882012-12-28 19:29:43 -08001112 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -04001113 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -08001114
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001115 return true;
1116}
1117
David Zeuthene8ed8632014-07-24 13:38:10 -04001118// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +00001119// and fill in the appropriate fields of the output object. Also, notifies
1120// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -07001121void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
1122 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +00001123 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001124 string current_response(response_buffer_.begin(), response_buffer_.end());
1125 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001126
Gilad Arnold74b5f552014-10-07 08:17:16 -07001127 PayloadStateInterface* const payload_state = system_state_->payload_state();
1128
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001129 // Events are best effort transactions -- assume they always succeed.
1130 if (IsEvent()) {
1131 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001132 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001133 return;
1134 }
1135
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001136 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001137 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -07001138 int code = GetHTTPResponseCode();
1139 // Makes sure we send sane error values.
1140 if (code < 0 || code >= 1000) {
1141 code = 999;
1142 }
David Zeuthena99981f2013-04-29 13:42:47 -07001143 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001144 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +00001145 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001146 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001147
David Zeuthene8ed8632014-07-24 13:38:10 -04001148 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -04001149 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -04001150 XML_SetUserData(parser, &parser_data);
1151 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -04001152 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001153 XML_Status res = XML_Parse(
1154 parser,
1155 reinterpret_cast<const char*>(response_buffer_.data()),
1156 response_buffer_.size(),
1157 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -04001158 XML_ParserFree(parser);
1159
1160 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -07001161 LOG(ERROR) << "Omaha response not valid XML: "
1162 << XML_ErrorString(XML_GetErrorCode(parser))
1163 << " at line " << XML_GetCurrentLineNumber(parser)
1164 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -04001165 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
1166 if (response_buffer_.empty()) {
1167 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
1168 } else if (parser_data.entity_decl) {
1169 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
1170 }
1171 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001172 return;
1173 }
1174
Alex Deymoebbe7ef2014-10-30 13:02:49 -07001175 // Update the last ping day preferences based on the server daystart response
1176 // even if we didn't send a ping. Omaha always includes the daystart in the
1177 // response, but log the error if it didn't.
1178 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
1179 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -07001180
Amin Hassani1677e812017-06-21 13:36:36 -07001181 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
1182 // we have got a response from omaha and if its value has never been set to
1183 // true before. Failure of this function should be ignored. There should be no
1184 // need to check if a=-1 has been sent because older devices have already sent
1185 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
1186 // future checks.
1187 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
1188 system_state_->hardware()->SetFirstActiveOmahaPingSent();
1189 }
1190
Thieu Le116fda32011-04-19 11:01:54 -07001191 if (!HasOutputPipe()) {
1192 // Just set success to whether or not the http transfer succeeded,
1193 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001194 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001195 return;
1196 }
1197
Darin Petkov6a5b3222010-07-13 14:55:28 -07001198 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001199 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001200 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001201 output_object.update_exists = true;
1202 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001203
Weidong Guo421ff332017-04-17 10:08:38 -07001204 ErrorCode error = ErrorCode::kSuccess;
1205 if (ShouldIgnoreUpdate(&error, output_object)) {
1206 // No need to change output_object.update_exists here, since the value
1207 // has been output to the pipe.
1208 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001209 return;
1210 }
1211
David Zeuthen8f191b22013-08-06 12:27:50 -07001212 // If Omaha says to disable p2p, respect that
1213 if (output_object.disable_p2p_for_downloading) {
1214 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1215 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001216 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001217 }
1218 if (output_object.disable_p2p_for_sharing) {
1219 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1220 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001221 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001222 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001223
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001224 // Set the max kernel key version based on whether rollback is allowed.
1225 SetMaxKernelKeyVersionForRollback();
1226
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001227 // Update the payload state with the current response. The payload state
1228 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001229 // from what's stored already. We are updating the payload state as late
1230 // as possible in this method so that if a new release gets pushed and then
1231 // got pulled back due to some issues, we don't want to clear our internal
1232 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001233 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001234
David Zeuthen8f191b22013-08-06 12:27:50 -07001235 // It could be we've already exceeded the deadline for when p2p is
1236 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001237 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001238 payload_state->P2PNewAttempt();
1239 if (!payload_state->P2PAttemptAllowed()) {
1240 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1241 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001242 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001243 }
1244 }
1245
1246 // From here on, we'll complete stuff in CompleteProcessing() so
1247 // disable |completer| since we'll create a new one in that
1248 // function.
1249 completer.set_should_complete(false);
1250
1251 // If we're allowed to use p2p for downloading we do not pay
1252 // attention to wall-clock-based waiting if the URL is indeed
1253 // available via p2p. Therefore, check if the file is available via
1254 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001255 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001256 LookupPayloadViaP2P(output_object);
1257 } else {
1258 CompleteProcessing();
1259 }
1260}
1261
1262void OmahaRequestAction::CompleteProcessing() {
1263 ScopedActionCompleter completer(processor_, this);
1264 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1265 PayloadStateInterface* payload_state = system_state_->payload_state();
1266
Alex Deymo46a9aae2016-05-04 20:20:11 -07001267 if (system_state_->hardware()->IsOOBEEnabled() &&
1268 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
Kevin Cernekeec5081a82016-04-08 12:29:52 -07001269 output_object.deadline.empty() &&
1270 params_->app_version() != "ForcedUpdate") {
Kevin Cernekee2494e282016-03-29 18:03:53 -07001271 output_object.update_exists = false;
1272 LOG(INFO) << "Ignoring non-critical Omaha updates until OOBE is done.";
1273 completer.set_code(ErrorCode::kNonCriticalUpdateInOOBE);
1274 return;
1275 }
1276
David Zeuthen8f191b22013-08-06 12:27:50 -07001277 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001278 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001279 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001280 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001281 return;
1282 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001283
Chris Sosa20f005c2013-09-05 13:53:08 -07001284 if (payload_state->ShouldBackoffDownload()) {
1285 output_object.update_exists = false;
1286 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1287 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001288 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001289 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001290 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001291 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001292}
1293
1294void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1295 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1296 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001297 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001298 } else {
1299 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1300 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001301 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001302 }
1303 CompleteProcessing();
1304}
1305
1306void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001307 // If the device is in the middle of an update, the state variables
1308 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1309 // tracks the offset and length of the operation currently in
1310 // progress. The offset is based from the end of the manifest which
1311 // is kPrefsManifestMetadataSize bytes long.
1312 //
1313 // To make forward progress and avoid deadlocks, we need to find a
1314 // peer that has at least the entire operation we're currently
1315 // working on. Otherwise we may end up in a situation where two
1316 // devices bounce back and forth downloading from each other,
1317 // neither making any forward progress until one of them decides to
1318 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1319 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001320 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001321 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001322 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001323 int64_t next_data_offset = 0;
1324 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001325 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001326 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1327 &manifest_metadata_size) &&
1328 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001329 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1330 &manifest_signature_size) &&
1331 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001332 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001333 &next_data_offset) &&
1334 next_data_offset != -1 &&
1335 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1336 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001337 minimum_size = manifest_metadata_size + manifest_signature_size +
1338 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001339 }
1340
Sen Jiang0affc2c2017-02-10 15:55:05 -08001341 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001342 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001343 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001344 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001345 string file_id =
1346 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001347 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001348 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1349 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001350 system_state_->p2p_manager()->LookupUrlForFile(
1351 file_id,
1352 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001353 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001354 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1355 base::Unretained(this)));
1356 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001357}
1358
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001359bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001360 if (params_->interactive()) {
1361 LOG(INFO) << "Not deferring download because update is interactive.";
1362 return false;
1363 }
1364
David Zeuthen8f191b22013-08-06 12:27:50 -07001365 // If we're using p2p to download _and_ we have a p2p URL, we never
1366 // defer the download. This is because the download will always
1367 // happen from a peer on the LAN and we've been waiting in line for
1368 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001369 const PayloadStateInterface* payload_state = system_state_->payload_state();
1370 if (payload_state->GetUsingP2PForDownloading() &&
1371 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001372 LOG(INFO) << "Download not deferred because download "
1373 << "will happen from a local peer (via p2p).";
1374 return false;
1375 }
1376
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001377 // We should defer the downloads only if we've first satisfied the
1378 // wall-clock-based-waiting period and then the update-check-based waiting
1379 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001380 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001381 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1382 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001383 return false;
1384 }
1385
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001386 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001387 case kWallClockWaitNotSatisfied:
1388 // We haven't even satisfied the first condition, passing the
1389 // wall-clock-based waiting period, so we should defer the downloads
1390 // until that happens.
1391 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1392 return true;
1393
1394 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1395 LOG(INFO) << "wall-clock-based-wait satisfied and "
1396 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001397 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001398
1399 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1400 // Wall-clock-based waiting period is satisfied, and it's determined
1401 // that we do not need the update-check-based wait. so no need to
1402 // defer downloads.
1403 LOG(INFO) << "wall-clock-based-wait satisfied and "
1404 << "update-check-based-wait is not required.";
1405 return false;
1406
1407 default:
1408 // Returning false for this default case so we err on the
1409 // side of downloading updates than deferring in case of any bugs.
1410 NOTREACHED();
1411 return false;
1412 }
1413}
1414
1415OmahaRequestAction::WallClockWaitResult
1416OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001417 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001418 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001419 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001420
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001421 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1422 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1423 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001424 // Note: This timestamp could be that of ANY update we saw in the past
1425 // (not necessarily this particular update we're considering to apply)
1426 // but never got to apply because of some reason (e.g. stop AU policy,
1427 // updates being pulled out from Omaha, changes in target version prefix,
1428 // new update being rolled out, etc.). But for the purposes of scattering
1429 // it doesn't matter which update the timestamp corresponds to. i.e.
1430 // the clock starts ticking the first time we see an update and we're
1431 // ready to apply when the random wait period is satisfied relative to
1432 // that first seen timestamp.
1433 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1434 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1435 << utils::ToString(update_first_seen_at);
1436 } else {
1437 // This seems like an unexpected error where the persisted value exists
1438 // but it's not readable for some reason. Just skip scattering in this
1439 // case to be safe.
1440 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1441 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1442 }
1443 } else {
Sen Jiang7c1171e2016-06-23 11:35:40 -07001444 update_first_seen_at = system_state_->clock()->GetWallclockTime();
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001445 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001446 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1447 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001448 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1449 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001450 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001451 // This seems like an unexpected error where the value cannot be
1452 // persisted for some reason. Just skip scattering in this
1453 // case to be safe.
1454 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1455 << utils::ToString(update_first_seen_at)
1456 << " cannot be persisted";
1457 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1458 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001459 }
1460
Sen Jiang7c1171e2016-06-23 11:35:40 -07001461 TimeDelta elapsed_time =
1462 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1463 TimeDelta max_scatter_period =
1464 TimeDelta::FromDays(output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001465
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001466 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001467 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001468 << ", Time Elapsed = "
1469 << utils::FormatSecs(elapsed_time.InSeconds())
1470 << ", MaxDaysToScatter = "
1471 << max_scatter_period.InDays();
1472
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001473 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001474 // The deadline is set for all rules which serve a delta update from a
1475 // previous FSI, which means this update will be applied mostly in OOBE
1476 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1477 // quickly.
1478 LOG(INFO) << "Not scattering as deadline flag is set";
1479 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1480 }
1481
1482 if (max_scatter_period.InDays() == 0) {
1483 // This means the Omaha rule creator decides that this rule
1484 // should not be scattered irrespective of the policy.
1485 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1486 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1487 }
1488
1489 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001490 // This means we've waited more than the upperbound wait in the rule
1491 // from the time we first saw a valid update available to us.
1492 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001493 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1494 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1495 }
1496
1497 // This means we are required to participate in scattering.
1498 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001499 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001500 if (remaining_wait_time.InSeconds() <= 0) {
1501 // Yes, it's our turn now.
1502 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1503
1504 // But we can't download until the update-check-count-based wait is also
1505 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001506 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001507 kWallClockWaitDoneButUpdateCheckWaitRequired :
1508 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1509 }
1510
1511 // Not our turn yet, so we have to wait until our turn to
1512 // help scatter the downloads across all clients of the enterprise.
1513 LOG(INFO) << "Update deferred for another "
1514 << utils::FormatSecs(remaining_wait_time.InSeconds())
1515 << " per policy.";
1516 return kWallClockWaitNotSatisfied;
1517}
1518
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001519bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001520 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001521
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001522 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1523 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1524 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001525 // We are unable to read the update check count from file for some reason.
1526 // So let's proceed anyway so as to not stall the update.
1527 LOG(ERROR) << "Unable to read update check count. "
1528 << "Skipping update-check-count-based-wait.";
1529 return true;
1530 }
1531 } else {
1532 // This file does not exist. This means we haven't started our update
1533 // check count down yet, so this is the right time to start the count down.
1534 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001535 params_->min_update_checks_needed(),
1536 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001537
1538 LOG(INFO) << "Randomly picked update check count value = "
1539 << update_check_count_value;
1540
1541 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001542 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1543 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001544 // We weren't able to write the update check count file for some reason.
1545 // So let's proceed anyway so as to not stall the update.
1546 LOG(ERROR) << "Unable to write update check count. "
1547 << "Skipping update-check-count-based-wait.";
1548 return true;
1549 }
1550 }
1551
1552 if (update_check_count_value == 0) {
1553 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1554 return true;
1555 }
1556
1557 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001558 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001559 // We err on the side of skipping scattering logic instead of stalling
1560 // a machine from receiving any updates in case of any unexpected state.
1561 LOG(ERROR) << "Invalid value for update check count detected. "
1562 << "Skipping update-check-count-based-wait.";
1563 return true;
1564 }
1565
1566 // Legal value, we need to wait for more update checks to happen
1567 // until this becomes 0.
1568 LOG(INFO) << "Deferring Omaha updates for another "
1569 << update_check_count_value
1570 << " update checks per policy";
1571 return false;
1572}
1573
David Zeuthen639aa362014-02-03 16:23:44 -08001574// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001575bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001576 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001577 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001578 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001579 &elapsed_days))
1580 return false;
1581
1582 if (elapsed_days < 0)
1583 return false;
1584
1585 output_object->install_date_days = elapsed_days;
1586 return true;
1587}
1588
1589// static
1590bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1591 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001592 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001593 return false;
1594
1595 return prefs->Exists(kPrefsInstallDateDays);
1596}
1597
1598// static
1599bool OmahaRequestAction::PersistInstallDate(
1600 SystemState *system_state,
1601 int install_date_days,
1602 InstallDateProvisioningSource source) {
1603 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1604
1605 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001606 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001607 return false;
1608
1609 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1610 return false;
1611
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001612 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001613 static_cast<int>(source), // Sample.
1614 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001615 return true;
1616}
1617
Alex Deymo8e18f932015-03-27 16:16:59 -07001618bool OmahaRequestAction::PersistCohortData(
1619 const string& prefs_key,
1620 const string& new_value) {
1621 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1622 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1623 return system_state_->prefs()->Delete(prefs_key);
1624 } else if (!new_value.empty()) {
1625 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1626 return system_state_->prefs()->SetString(prefs_key, new_value);
1627 }
1628 return true;
1629}
1630
Alex Deymob3fa53b2016-04-18 19:57:58 -07001631bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
1632 auto eol_attr = attrs.find(kEolAttr);
1633 if (eol_attr != attrs.end()) {
1634 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1635 eol_attr->second);
1636 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1637 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1638 }
1639 return true;
1640}
1641
David Zeuthen33bae492014-02-25 16:16:18 -08001642void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1643 // We only want to report this on "update check".
1644 if (ping_only_ || event_ != nullptr)
1645 return;
1646
1647 metrics::CheckResult result = metrics::CheckResult::kUnset;
1648 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1649 metrics::DownloadErrorCode download_error_code =
1650 metrics::DownloadErrorCode::kUnset;
1651
1652 // Regular update attempt.
1653 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001654 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001655 // OK, we parsed the response successfully but that does
1656 // necessarily mean that an update is available.
1657 if (HasOutputPipe()) {
1658 const OmahaResponse& response = GetOutputObject();
1659 if (response.update_exists) {
1660 result = metrics::CheckResult::kUpdateAvailable;
1661 reaction = metrics::CheckReaction::kUpdating;
1662 } else {
1663 result = metrics::CheckResult::kNoUpdateAvailable;
1664 }
1665 } else {
1666 result = metrics::CheckResult::kNoUpdateAvailable;
1667 }
1668 break;
1669
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001670 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
Weidong Guo421ff332017-04-17 10:08:38 -07001671 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
David Zeuthen33bae492014-02-25 16:16:18 -08001672 result = metrics::CheckResult::kUpdateAvailable;
1673 reaction = metrics::CheckReaction::kIgnored;
1674 break;
1675
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001676 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001677 result = metrics::CheckResult::kUpdateAvailable;
1678 reaction = metrics::CheckReaction::kDeferring;
1679 break;
1680
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001681 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001682 result = metrics::CheckResult::kUpdateAvailable;
1683 reaction = metrics::CheckReaction::kBackingOff;
1684 break;
1685
1686 default:
1687 // We report two flavors of errors, "Download errors" and "Parsing
1688 // error". Try to convert to the former and if that doesn't work
1689 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001690 metrics::DownloadErrorCode tmp_error =
1691 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001692 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1693 result = metrics::CheckResult::kDownloadError;
1694 download_error_code = tmp_error;
1695 } else {
1696 result = metrics::CheckResult::kParsingError;
1697 }
1698 break;
1699 }
1700
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001701 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1702 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001703}
1704
Chris Sosa77f79e82014-06-02 18:16:24 -07001705bool OmahaRequestAction::ShouldIgnoreUpdate(
Weidong Guo421ff332017-04-17 10:08:38 -07001706 ErrorCode* error, const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001707 // Note: policy decision to not update to a version we rolled back from.
1708 string rollback_version =
1709 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001710 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001711 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001712 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001713 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001714 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001715 return true;
1716 }
1717 }
1718
Weidong Guo421ff332017-04-17 10:08:38 -07001719 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001720 LOG(INFO) << "Update is not allowed over current connection.";
1721 return true;
1722 }
1723
1724 // Note: We could technically delete the UpdateFirstSeenAt state when we
1725 // return true. If we do, it'll mean a device has to restart the
1726 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1727 // turned on again. On the other hand, it also increases the chance of update
1728 // starvation if an admin turns AU on/off more frequently. We choose to err on
1729 // the side of preventing starvation at the cost of not applying scattering in
1730 // those cases.
1731 return false;
1732}
1733
Weidong Guo421ff332017-04-17 10:08:38 -07001734bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1735 const OmahaResponse& response) const {
1736 PrefsInterface* prefs = system_state_->prefs();
1737
1738 if (!prefs) {
1739 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1740 "not available.";
1741 return false;
1742 }
1743
1744 bool is_allowed;
1745
1746 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1747 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1748 is_allowed) {
1749 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1750 "set to true.";
1751 return true;
1752 }
1753
1754 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1755 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1756 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1757 "set to false or does not exist while target does not exist.";
1758 return false;
1759 }
1760
1761 std::string target_version;
1762 int64_t target_size;
1763
1764 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1765 &target_version) ||
1766 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1767 LOG(INFO) << "Disabling updates over cellular as the target version or "
1768 "size is not accessible.";
1769 return false;
1770 }
1771
1772 uint64_t total_packages_size = 0;
1773 for (const auto& package : response.packages) {
1774 total_packages_size += package.size;
1775 }
1776 if (target_version == response.version &&
1777 static_cast<uint64_t>(target_size) == total_packages_size) {
1778 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1779 "omaha response.";
1780 return true;
1781 } else {
1782 LOG(INFO) << "Disabling updates over cellular as the target does not"
1783 "match the omaha response.";
1784 return false;
1785 }
1786}
1787
1788bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1789 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001790 ConnectionType type;
1791 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001792 ConnectionManagerInterface* connection_manager =
1793 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001794 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001795 LOG(INFO) << "We could not determine our connection type. "
1796 << "Defaulting to allow updates.";
1797 return true;
1798 }
Weidong Guo421ff332017-04-17 10:08:38 -07001799
Chris Sosa77f79e82014-06-02 18:16:24 -07001800 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001801 bool is_device_policy_set =
1802 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1803 // Treats tethered connection as if it is cellular connection.
1804 bool is_over_cellular = type == ConnectionType::kCellular ||
1805 tethering == ConnectionTethering::kConfirmed;
1806
1807 if (!is_over_cellular) {
1808 // There's no need to further check user preferences as we are not over
1809 // cellular connection.
1810 if (!is_allowed)
1811 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1812 } else if (is_device_policy_set) {
1813 // There's no need to further check user preferences as the device policy
1814 // is set regarding updates over cellular.
1815 if (!is_allowed)
1816 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1817 } else {
1818 // Deivce policy is not set, so user preferences overwrite whether to
1819 // allow updates over cellular.
1820 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1821 if (!is_allowed)
1822 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1823 }
1824
Chris Sosa77f79e82014-06-02 18:16:24 -07001825 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001826 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001827 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1828 return is_allowed;
1829}
1830
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001831bool OmahaRequestAction::IsRollbackEnabled() const {
1832 if (policy_provider_->IsConsumerDevice()) {
1833 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1834 return false;
1835 }
1836
1837 if (!policy_provider_->device_policy_is_loaded()) {
1838 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1839 return true;
1840 }
1841
1842 int allowed_milestones;
1843 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1844 &allowed_milestones)) {
1845 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1846 "Defaulting to rollback enabled.";
1847 return true;
1848 }
1849
1850 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1851 return allowed_milestones > 0;
1852}
1853
1854void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
1855 bool max_rollforward_set = false;
1856 if (IsRollbackEnabled()) {
1857 // If rollback is enabled, set the max kernel key version to the current
1858 // kernel key version. This has the effect of freezing kernel key roll
1859 // forwards.
1860 //
1861 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1862 // key roll forward happens until the server side components of rollback
1863 // are implemented. Future changes will allow the Omaha server to return
1864 // the kernel key version from max_rollback_versions in the past. At that
1865 // point the max kernel key version will be set to that value, creating a
1866 // sliding window of versions that can be rolled back to.
1867 int min_kernel_version =
1868 system_state_->hardware()->GetMinKernelKeyVersion();
1869 LOG(INFO) << "Rollback is enabled. Setting max_kernel_rollforward to "
1870 << min_kernel_version;
1871 max_rollforward_set = system_state_->hardware()->SetMaxKernelKeyRollforward(
1872 min_kernel_version);
1873 } else {
1874 // For devices that are not rollback enabled (ie. consumer devices), the
1875 // max kernel key version is set to 0xfffffffe, which is logically
1876 // infinity. This maintains the previous behavior that that kernel key
1877 // versions roll forward each time they are incremented.
1878 LOG(INFO) << "Rollback is disabled. Setting max_kernel_rollforward to "
1879 << kRollforwardInfinity;
1880 max_rollforward_set = system_state_->hardware()->SetMaxKernelKeyRollforward(
1881 kRollforwardInfinity);
1882 }
1883
1884 if (!max_rollforward_set) {
1885 LOG(ERROR) << "Failed to set max_kernel_rollforward";
1886 }
1887}
1888
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001889} // namespace chromeos_update_engine