blob: 95dee51f4ff1a0c3366152781ea2829bec8c50d6 [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
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -070021#include <limits>
David Zeuthene8ed8632014-07-24 13:38:10 -040022#include <map>
rspangler@google.com49fdf182009-10-10 00:57:34 +000023#include <sstream>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070024#include <string>
Sen Jiang8cd42342018-01-31 12:06:59 -080025#include <utility>
David Zeuthene8ed8632014-07-24 13:38:10 -040026#include <vector>
rspangler@google.com49fdf182009-10-10 00:57:34 +000027
David Zeuthen8f191b22013-08-06 12:27:50 -070028#include <base/bind.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070029#include <base/logging.h>
30#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070031#include <base/strings/string_number_conversions.h>
Sen Jiang0affc2c2017-02-10 15:55:05 -080032#include <base/strings/string_split.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070033#include <base/strings/string_util.h>
34#include <base/strings/stringprintf.h>
35#include <base/time/time.h>
Sen Jiang684c9cd2017-10-17 16:26:45 -070036#include <brillo/key_value_store.h>
David Zeuthene8ed8632014-07-24 13:38:10 -040037#include <expat.h>
Alex Deymoa2591792015-11-17 00:39:40 -030038#include <metrics/metrics_library.h>
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -080039#include <policy/libpolicy.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000040
Alex Deymo39910dc2015-11-09 17:04:30 -080041#include "update_engine/common/action_pipe.h"
42#include "update_engine/common/constants.h"
43#include "update_engine/common/hardware_interface.h"
44#include "update_engine/common/hash_calculator.h"
45#include "update_engine/common/platform_constants.h"
46#include "update_engine/common/prefs_interface.h"
47#include "update_engine/common/utils.h"
Sen Jiang255e22b2016-05-20 16:15:29 -070048#include "update_engine/connection_manager_interface.h"
Tianjie Xu282aa1f2017-09-05 13:42:45 -070049#include "update_engine/metrics_reporter_interface.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080050#include "update_engine/metrics_utils.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070051#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070052#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080053#include "update_engine/payload_state_interface.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000054
Darin Petkov1cbd78f2010-07-29 12:38:34 -070055using base::Time;
56using base::TimeDelta;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -080057using chromeos_update_manager::kRollforwardInfinity;
David Zeuthene8ed8632014-07-24 13:38:10 -040058using std::map;
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -070059using std::numeric_limits;
rspangler@google.com49fdf182009-10-10 00:57:34 +000060using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040061using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000062
63namespace chromeos_update_engine {
64
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080065// List of custom pair tags that we interpret in the Omaha Response:
66static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080067static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070068static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080069// Deprecated: "IsDelta"
70static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080071static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
72static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
73// Deprecated: "ManifestSignatureRsa"
74// Deprecated: "ManifestSize"
75static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
76static const char* kTagMetadataSize = "MetadataSize";
77static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070078// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080079static const char* kTagPrompt = "Prompt";
David Zeuthen8f191b22013-08-06 12:27:50 -070080static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
81static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
David Zeuthene7f89172013-10-31 10:21:04 -070082static const char* kTagPublicKeyRsa = "PublicKeyRsa";
Sen Jiangfe284402018-03-21 14:03:50 -070083static const char* kTagPowerwash = "Powerwash";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080084
Alex Deymoac41a822015-09-15 20:52:53 -070085static const char* kOmahaUpdaterVersion = "0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +000086
Sen Jiang42fa45e2018-03-12 11:02:14 -070087// X-Goog-Update headers.
88static const char* kXGoogleUpdateInteractivity = "X-Goog-Update-Interactivity";
89static const char* kXGoogleUpdateAppId = "X-Goog-Update-AppId";
90static const char* kXGoogleUpdateUpdater = "X-Goog-Update-Updater";
Alex Deymo14ad88e2016-06-29 12:30:14 -070091
Alex Deymob3fa53b2016-04-18 19:57:58 -070092// updatecheck attributes (without the underscore prefix).
93static const char* kEolAttr = "eol";
Marton Hunyady199152d2018-05-07 19:08:48 +020094static const char* kRollback = "rollback";
95static const char* kFirmwareVersion = "firmware_version";
96static const char* kKernelVersion = "kernel_version";
Alex Deymob3fa53b2016-04-18 19:57:58 -070097
Alex Deymoac41a822015-09-15 20:52:53 -070098namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +000099
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700100// Returns an XML ping element attribute assignment with attribute
101// |name| and value |ping_days| if |ping_days| has a value that needs
102// to be sent, or an empty string otherwise.
103string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700104 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700105 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700106 return "";
107}
108
109// Returns an XML ping element if any of the elapsed days need to be
110// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700111string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700112 string ping_active = GetPingAttribute("a", ping_active_days);
113 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
114 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700115 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700116 ping_active.c_str(),
117 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700118 }
119 return "";
120}
121
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700122// Returns an XML that goes into the body of the <app> element of the Omaha
123// request based on the given parameters.
124string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700125 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700126 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700127 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700128 int ping_active_days,
129 int ping_roll_call_days,
130 PrefsInterface* prefs) {
131 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700132 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700133 if (include_ping)
134 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700135 if (!ping_only) {
Marton Hunyadyba51c3f2018-04-25 15:18:10 +0200136 app_body += " <updatecheck";
137 if (!params->target_version_prefix().empty()) {
138 app_body += base::StringPrintf(
139 " targetversionprefix=\"%s\"",
140 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
141 // Rollback requires target_version_prefix set.
142 if (params->rollback_allowed()) {
143 app_body += " rollback_allowed=\"true\"";
144 }
145 }
146 app_body += "></updatecheck>\n";
Jay Srinivasan0a708742012-03-20 11:26:12 -0700147
Darin Petkov265f2902011-05-09 15:17:40 -0700148 // If this is the first update check after a reboot following a previous
149 // update, generate an event containing the previous version number. If
150 // the previous version preference file doesn't exist the event is still
151 // generated with a previous version of 0.0.0.0 -- this is relevant for
152 // older clients or new installs. The previous version event is not sent
153 // for ping-only requests because they come before the client has
Alex Deymo87c08862015-10-30 21:56:55 -0700154 // rebooted. The previous version event is also not sent if it was already
155 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700156 string prev_version;
157 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
158 prev_version = "0.0.0.0";
159 }
Alex Deymo87c08862015-10-30 21:56:55 -0700160 // We only store a non-empty previous version value after a successful
161 // update in the previous boot. After reporting it back to the server,
162 // we clear the previous version value so it doesn't get reported again.
163 if (!prev_version.empty()) {
164 app_body += base::StringPrintf(
165 " <event eventtype=\"%d\" eventresult=\"%d\" "
166 "previousversion=\"%s\"></event>\n",
Alex Deymo9fded1e2015-11-05 12:31:19 -0800167 OmahaEvent::kTypeRebootedAfterUpdate,
168 OmahaEvent::kResultSuccess,
Alex Deymo87c08862015-10-30 21:56:55 -0700169 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
170 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
171 << "Unable to reset the previous version.";
172 }
Darin Petkov95508da2011-01-05 12:42:29 -0800173 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700174 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800175 // The error code is an optional attribute so append it only if the result
176 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700177 string error_code;
178 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700179 error_code = base::StringPrintf(" errorcode=\"%d\"",
180 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700181 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700182 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700183 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700184 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700185 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700186
187 return app_body;
188}
189
Alex Deymo8e18f932015-03-27 16:16:59 -0700190// Returns the cohort* argument to include in the <app> tag for the passed
191// |arg_name| and |prefs_key|, if any. The return value is suitable to
192// concatenate to the list of arguments and includes a space at the end.
193string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700194 const string arg_name,
195 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700196 // There's nothing wrong with not having a given cohort setting, so we check
Sen Jiang771f6482018-04-04 17:59:10 -0700197 // existence first to avoid the warning log message.
Alex Deymo8e18f932015-03-27 16:16:59 -0700198 if (!prefs->Exists(prefs_key))
199 return "";
200 string cohort_value;
201 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
202 return "";
203 // This is a sanity check to avoid sending a huge XML file back to Ohama due
204 // to a compromised stateful partition making the update check fail in low
205 // network environments envent after a reboot.
206 if (cohort_value.size() > 1024) {
207 LOG(WARNING) << "The omaha cohort setting " << arg_name
208 << " has a too big value, which must be an error or an "
209 "attacker trying to inhibit updates.";
210 return "";
211 }
212
Alex Deymob0d74eb2015-03-30 17:59:17 -0700213 string escaped_xml_value;
214 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
215 LOG(WARNING) << "The omaha cohort setting " << arg_name
216 << " is ASCII-7 invalid, ignoring it.";
217 return "";
218 }
219
Alex Deymo8e18f932015-03-27 16:16:59 -0700220 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700221 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700222}
223
Sen Jiang94a4dec2017-03-28 18:23:35 -0700224struct OmahaAppData {
225 string id;
226 string version;
Sen Jiang684c9cd2017-10-17 16:26:45 -0700227 string product_components;
Sen Jiang94a4dec2017-03-28 18:23:35 -0700228};
229
Sen Jiang684c9cd2017-10-17 16:26:45 -0700230bool IsValidComponentID(const string& id) {
231 for (char c : id) {
232 if (!isalnum(c) && c != '-' && c != '_' && c != '.')
233 return false;
234 }
235 return true;
236}
237
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700238// Returns an XML that corresponds to the entire <app> node of the Omaha
239// request based on the given parameters.
240string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700241 OmahaRequestParams* params,
Sen Jiang94a4dec2017-03-28 18:23:35 -0700242 const OmahaAppData& app_data,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700243 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700244 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700245 int ping_active_days,
246 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800247 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700248 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700249 string app_body = GetAppBody(event, params, ping_only, include_ping,
250 ping_active_days, ping_roll_call_days,
251 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700252 string app_versions;
253
Sen Jiang8cd42342018-01-31 12:06:59 -0800254 // If we are downgrading to a more stable channel and we are allowed to do
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700255 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
256 // highest-versioned payload on the destination channel.
Sen Jiang8500d3a2018-02-08 12:04:05 -0800257 if (params->ShouldPowerwash()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700258 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
259 << "on downgrading to the version in the more stable channel";
260 app_versions = "version=\"0.0.0.0\" from_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 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700263 app_versions = "version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700264 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700265 }
266
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700267 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700268 string app_channels =
269 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
270 if (params->current_channel() != download_channel) {
271 app_channels += "from_track=\"" + XmlEncodeWithDefault(
272 params->current_channel(), "") + "\" ";
273 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700274
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700275 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700276
David Zeuthen639aa362014-02-03 16:23:44 -0800277 // If install_date_days is not set (e.g. its value is -1 ), don't
278 // include the attribute.
279 string install_date_in_days_str = "";
280 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700281 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
282 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800283 }
284
Alex Deymo8e18f932015-03-27 16:16:59 -0700285 string app_cohort_args;
286 app_cohort_args += GetCohortArgXml(system_state->prefs(),
287 "cohort", kPrefsOmahaCohort);
288 app_cohort_args += GetCohortArgXml(system_state->prefs(),
289 "cohorthint", kPrefsOmahaCohortHint);
290 app_cohort_args += GetCohortArgXml(system_state->prefs(),
291 "cohortname", kPrefsOmahaCohortName);
292
Alex Deymoebf6e122017-03-10 16:12:01 -0800293 string fingerprint_arg;
294 if (!params->os_build_fingerprint().empty()) {
Sen Jiang8cd42342018-01-31 12:06:59 -0800295 fingerprint_arg = "fingerprint=\"" +
296 XmlEncodeWithDefault(params->os_build_fingerprint(), "") +
297 "\" ";
Alex Deymoebf6e122017-03-10 16:12:01 -0800298 }
299
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700300 string buildtype_arg;
301 if (!params->os_build_type().empty()) {
302 buildtype_arg = "os_build_type=\"" +
303 XmlEncodeWithDefault(params->os_build_type(), "") + "\" ";
304 }
305
Sen Jiang684c9cd2017-10-17 16:26:45 -0700306 string product_components_args;
Sen Jiang8500d3a2018-02-08 12:04:05 -0800307 if (!params->ShouldPowerwash() && !app_data.product_components.empty()) {
Sen Jiang684c9cd2017-10-17 16:26:45 -0700308 brillo::KeyValueStore store;
309 if (store.LoadFromString(app_data.product_components)) {
310 for (const string& key : store.GetKeys()) {
311 if (!IsValidComponentID(key)) {
312 LOG(ERROR) << "Invalid component id: " << key;
313 continue;
314 }
315 string version;
316 if (!store.GetString(key, &version)) {
317 LOG(ERROR) << "Failed to get version for " << key
318 << " in product_components.";
319 continue;
320 }
321 product_components_args +=
322 base::StringPrintf("_%s.version=\"%s\" ",
323 key.c_str(),
324 XmlEncodeWithDefault(version, "").c_str());
325 }
326 } else {
327 LOG(ERROR) << "Failed to parse product_components:\n"
328 << app_data.product_components;
329 }
330 }
331
332 // clang-format off
Alex Deymob0d74eb2015-03-30 17:59:17 -0700333 string app_xml = " <app "
Sen Jiang94a4dec2017-03-28 18:23:35 -0700334 "appid=\"" + XmlEncodeWithDefault(app_data.id, "") + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700335 app_cohort_args +
336 app_versions +
337 app_channels +
Sen Jiang684c9cd2017-10-17 16:26:45 -0700338 product_components_args +
Alex Deymoebf6e122017-03-10 16:12:01 -0800339 fingerprint_arg +
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700340 buildtype_arg +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700341 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
342 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
343 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
344 "delta_okay=\"" + delta_okay_str + "\" "
345 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
346 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
347 install_date_in_days_str +
348 ">\n" +
349 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700350 " </app>\n";
Sen Jiang684c9cd2017-10-17 16:26:45 -0700351 // clang-format on
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700352 return app_xml;
353}
354
355// Returns an XML that corresponds to the entire <os> node of the Omaha
356// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700357string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700358 string os_xml =" <os "
359 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
360 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
361 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
362 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700363 return os_xml;
364}
365
366// Returns an XML that corresponds to the entire Omaha request based on the
367// given parameters.
368string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700369 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700370 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700371 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700372 int ping_active_days,
373 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800374 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700375 SystemState* system_state) {
376 string os_xml = GetOsXml(params);
Sen Jiang684c9cd2017-10-17 16:26:45 -0700377 OmahaAppData product_app = {
378 .id = params->GetAppId(),
379 .version = params->app_version(),
380 .product_components = params->product_components()};
Sen Jiang94a4dec2017-03-28 18:23:35 -0700381 string app_xml = GetAppXml(event,
382 params,
383 product_app,
384 ping_only,
385 include_ping,
386 ping_active_days,
387 ping_roll_call_days,
388 install_date_in_days,
389 system_state);
390 if (!params->system_app_id().empty()) {
391 OmahaAppData system_app = {.id = params->system_app_id(),
392 .version = params->system_version()};
393 app_xml += GetAppXml(event,
394 params,
395 system_app,
396 ping_only,
397 include_ping,
398 ping_active_days,
399 ping_roll_call_days,
400 install_date_in_days,
401 system_state);
402 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700403
Alex Vakulenko75039d72014-03-25 12:36:28 -0700404 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700405 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700406
Alex Deymoac41a822015-09-15 20:52:53 -0700407 string updater_version = XmlEncodeWithDefault(
408 base::StringPrintf("%s-%s",
409 constants::kOmahaUpdaterID,
410 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700411 string request_xml =
412 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700413 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700414 "version=\"" + updater_version + "\" "
415 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700416 install_source +
417 "ismachine=\"1\">\n") +
418 os_xml +
419 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700420 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700421
422 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000423}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700424
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700425} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000426
David Zeuthene8ed8632014-07-24 13:38:10 -0400427// Struct used for holding data obtained when parsing the XML.
428struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400429 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
430
431 // Pointer to the expat XML_Parser object.
432 XML_Parser xml_parser;
433
David Zeuthene8ed8632014-07-24 13:38:10 -0400434 // This is the state of the parser as it's processing the XML.
435 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400436 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400437 string current_path;
438
439 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400440 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700441 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400442 string daystart_elapsed_days;
443 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800444
Sen Jiang81259682017-03-30 15:11:30 -0700445 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700446 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700447 vector<string> url_codebase;
448 string manifest_version;
449 map<string, string> action_postinstall_attrs;
450 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700451 string cohort;
452 string cohorthint;
453 string cohortname;
454 bool cohort_set = false;
455 bool cohorthint_set = false;
456 bool cohortname_set = false;
Sen Jiang81259682017-03-30 15:11:30 -0700457
458 struct Package {
459 string name;
460 string size;
461 string hash;
462 };
463 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800464 };
Sen Jiang81259682017-03-30 15:11:30 -0700465 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400466};
467
468namespace {
469
470// Callback function invoked by expat.
471void ParserHandlerStart(void* user_data, const XML_Char* element,
472 const XML_Char** attr) {
473 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
474
475 if (data->failed)
476 return;
477
478 data->current_path += string("/") + element;
479
480 map<string, string> attrs;
481 if (attr != nullptr) {
482 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
483 string key = attr[n];
484 string value = attr[n + 1];
485 attrs[key] = value;
486 }
487 }
488
Alex Deymo8e18f932015-03-27 16:16:59 -0700489 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700490 OmahaParserData::App app;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700491 if (attrs.find("appid") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700492 app.id = attrs["appid"];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700493 }
Alex Deymo8e18f932015-03-27 16:16:59 -0700494 if (attrs.find("cohort") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700495 app.cohort_set = true;
496 app.cohort = attrs["cohort"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700497 }
498 if (attrs.find("cohorthint") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700499 app.cohorthint_set = true;
500 app.cohorthint = attrs["cohorthint"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700501 }
502 if (attrs.find("cohortname") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700503 app.cohortname_set = true;
504 app.cohortname = attrs["cohortname"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700505 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700506 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700507 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700508 if (!data->apps.empty())
509 data->apps.back().updatecheck_status = attrs["status"];
510 if (data->updatecheck_poll_interval.empty())
511 data->updatecheck_poll_interval = attrs["PollInterval"];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700512 // Omaha sends arbitrary key-value pairs as extra attributes starting with
513 // an underscore.
514 for (const auto& attr : attrs) {
515 if (!attr.first.empty() && attr.first[0] == '_')
516 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
517 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400518 } else if (data->current_path == "/response/daystart") {
519 // Get the install-date.
520 data->daystart_elapsed_days = attrs["elapsed_days"];
521 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
522 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
523 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700524 if (!data->apps.empty())
525 data->apps.back().url_codebase.push_back(attrs["codebase"]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800526 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400527 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800528 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700529 if (!data->apps.empty())
530 data->apps.back().packages.push_back({.name = attrs["name"],
531 .size = attrs["size"],
532 .hash = attrs["hash_sha256"]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400533 } else if (data->current_path == "/response/app/updatecheck/manifest") {
534 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700535 if (!data->apps.empty())
536 data->apps.back().manifest_version = attrs[kTagVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400537 } else if (data->current_path ==
538 "/response/app/updatecheck/manifest/actions/action") {
539 // We only care about the postinstall action.
Sen Jiang81259682017-03-30 15:11:30 -0700540 if (attrs["event"] == "postinstall" && !data->apps.empty()) {
541 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400542 }
543 }
544}
545
546// Callback function invoked by expat.
547void ParserHandlerEnd(void* user_data, const XML_Char* element) {
548 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
549 if (data->failed)
550 return;
551
552 const string path_suffix = string("/") + element;
553
Alex Vakulenko0103c362016-01-20 07:56:15 -0800554 if (!base::EndsWith(data->current_path, path_suffix,
555 base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400556 LOG(ERROR) << "Unexpected end element '" << element
557 << "' with current_path='" << data->current_path << "'";
558 data->failed = true;
559 return;
560 }
561 data->current_path.resize(data->current_path.size() - path_suffix.size());
562}
563
David Zeuthenf3e28012014-08-26 18:23:52 -0400564// Callback function invoked by expat.
565//
566// This is called for entity declarations. Since Omaha is guaranteed
567// to never return any XML with entities our course of action is to
568// just stop parsing. This avoids potential resource exhaustion
569// problems AKA the "billion laughs". CVE-2013-0340.
570void ParserHandlerEntityDecl(void *user_data,
571 const XML_Char *entity_name,
572 int is_parameter_entity,
573 const XML_Char *value,
574 int value_length,
575 const XML_Char *base,
576 const XML_Char *system_id,
577 const XML_Char *public_id,
578 const XML_Char *notation_name) {
579 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
580
581 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
582 data->failed = true;
583 data->entity_decl = true;
584 XML_StopParser(data->xml_parser, false);
585}
586
David Zeuthene8ed8632014-07-24 13:38:10 -0400587} // namespace
588
Alex Deymob0d74eb2015-03-30 17:59:17 -0700589bool XmlEncode(const string& input, string* output) {
590 if (std::find_if(input.begin(), input.end(),
591 [](const char c){return c & 0x80;}) != input.end()) {
592 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
593 utils::HexDumpString(input);
594 return false;
595 }
Alex Deymocc457852015-06-18 18:35:50 -0700596 output->clear();
597 // We need at least input.size() space in the output, but the code below will
598 // handle it if we need more.
599 output->reserve(input.size());
600 for (char c : input) {
601 switch (c) {
602 case '\"':
603 output->append("&quot;");
604 break;
605 case '\'':
606 output->append("&apos;");
607 break;
608 case '&':
609 output->append("&amp;");
610 break;
611 case '<':
612 output->append("&lt;");
613 break;
614 case '>':
615 output->append("&gt;");
616 break;
617 default:
618 output->push_back(c);
619 }
620 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700621 return true;
622}
623
624string XmlEncodeWithDefault(const string& input, const string& default_value) {
625 string output;
626 if (XmlEncode(input, &output))
627 return output;
628 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000629}
630
Alex Deymoc1c17b42015-11-23 03:53:15 -0300631OmahaRequestAction::OmahaRequestAction(
632 SystemState* system_state,
633 OmahaEvent* event,
634 std::unique_ptr<HttpFetcher> http_fetcher,
635 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800636 : system_state_(system_state),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800637 params_(system_state->request_params()),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700638 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300639 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800640 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700641 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700642 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700643 ping_roll_call_days_(0) {
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800644 policy_provider_->Reload();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700645}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000646
Darin Petkov6a5b3222010-07-13 14:55:28 -0700647OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000648
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700649// Calculates the value to use for the ping days parameter.
650int OmahaRequestAction::CalculatePingDays(const string& key) {
651 int days = kNeverPinged;
652 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800653 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700654 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
655 if (days < 0) {
656 // If |days| is negative, then the system clock must have jumped
657 // back in time since the ping was sent. Mark the value so that
658 // it doesn't get sent to the server but we still update the
659 // last ping daystart preference. This way the next ping time
660 // will be correct, hopefully.
661 days = kPingTimeJump;
662 LOG(WARNING) <<
663 "System clock jumped back in time. Resetting ping daystarts.";
664 }
665 }
666 return days;
667}
668
669void OmahaRequestAction::InitPingDays() {
670 // We send pings only along with update checks, not with events.
671 if (IsEvent()) {
672 return;
673 }
674 // TODO(petkov): Figure a way to distinguish active use pings
675 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700676 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700677 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
678 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
679}
680
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700681bool OmahaRequestAction::ShouldPing() const {
682 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
683 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
684 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
685 if (powerwash_count > 0) {
686 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
687 << "powerwash_count is " << powerwash_count;
688 return false;
689 }
Amin Hassani1677e812017-06-21 13:36:36 -0700690 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
691 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
692 << "the first_active_omaha_ping_sent is true";
693 return false;
694 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700695 return true;
696 }
697 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
698}
699
David Zeuthen639aa362014-02-03 16:23:44 -0800700// static
701int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
702 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700703 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800704 return -1;
705
706 // If we have the value stored on disk, just return it.
707 int64_t stored_value;
708 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
709 // Convert and sanity-check.
710 int install_date_days = static_cast<int>(stored_value);
711 if (install_date_days >= 0)
712 return install_date_days;
713 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
714 << install_date_days << " looks suspicious.";
715 prefs->Delete(kPrefsInstallDateDays);
716 }
717
718 // Otherwise, if OOBE is not complete then do nothing and wait for
719 // ParseResponse() to call ParseInstallDate() and then
720 // PersistInstallDate() to set the kPrefsInstallDateDays state
721 // variable. Once that is done, we'll then report back in future
722 // Omaha requests. This works exactly because OOBE triggers an
723 // update check.
724 //
725 // However, if OOBE is complete and the kPrefsInstallDateDays state
726 // variable is not set, there are two possibilities
727 //
728 // 1. The update check in OOBE failed so we never got a response
729 // from Omaha (no network etc.); or
730 //
731 // 2. OOBE was done on an older version that didn't write to the
732 // kPrefsInstallDateDays state variable.
733 //
734 // In both cases, we approximate the install date by simply
735 // inspecting the timestamp of when OOBE happened.
736
737 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700738 if (!system_state->hardware()->IsOOBEEnabled() ||
739 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800740 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700741 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800742 return -1;
743 }
744
745 int num_days;
746 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
747 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
748 << "as its value '" << utils::ToString(time_of_oobe)
749 << "' looks suspicious.";
750 return -1;
751 }
752
753 // Persist this to disk, for future use.
754 if (!OmahaRequestAction::PersistInstallDate(system_state,
755 num_days,
756 kProvisionedFromOOBEMarker))
757 return -1;
758
759 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
760 << num_days << " days";
761
762 return num_days;
763}
764
Darin Petkov6a5b3222010-07-13 14:55:28 -0700765void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000766 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700767 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700768 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700769 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700770 return;
771 }
David Zeuthen639aa362014-02-03 16:23:44 -0800772
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700773 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700774 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700775 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700776 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700777 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800778 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800779 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700780 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700781
Sen Jiang42fa45e2018-03-12 11:02:14 -0700782 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700783 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
784 params_->interactive() ? "fg" : "bg");
785 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
786 http_fetcher_->SetHeader(
787 kXGoogleUpdateUpdater,
788 base::StringPrintf(
789 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
790
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800791 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
792 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700793 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700794 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700795 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000796}
797
Darin Petkov6a5b3222010-07-13 14:55:28 -0700798void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000799 http_fetcher_->TerminateTransfer();
800}
801
802// We just store the response in the buffer. Once we've received all bytes,
803// we'll look in the buffer and decide what to do.
Amin Hassani0cd9d772018-07-31 23:55:43 -0700804bool OmahaRequestAction::ReceivedBytes(HttpFetcher* fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800805 const void* bytes,
806 size_t length) {
807 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
808 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
Amin Hassani0cd9d772018-07-31 23:55:43 -0700809 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000810}
811
812namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000813
814// Parses a 64 bit base-10 int from a string and returns it. Returns 0
815// on error. If the string contains "0", that's indistinguishable from
816// error.
817off_t ParseInt(const string& str) {
818 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700819 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000820 if (rc < 1) {
821 // failure
822 return 0;
823 }
824 return ret;
825}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700826
David Zeuthene8ed8632014-07-24 13:38:10 -0400827// Parses |str| and returns |true| if, and only if, its value is "true".
828bool ParseBool(const string& str) {
829 return str == "true";
830}
831
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700832// Update the last ping day preferences based on the server daystart
833// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400834bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700835 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400836 TEST_AND_RETURN_FALSE(
837 base::StringToInt64(parser_data->daystart_elapsed_seconds,
838 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700839 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
840
841 // Remember the local time that matches the server's last midnight
842 // time.
843 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
844 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
845 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
846 return true;
847}
Sen Jiang81259682017-03-30 15:11:30 -0700848
849// Parses the package node in the given XML document and populates
850// |output_object| if valid. Returns true if we should continue the parsing.
851// False otherwise, in which case it sets any error code using |completer|.
852bool ParsePackage(OmahaParserData::App* app,
853 OmahaResponse* output_object,
854 ScopedActionCompleter* completer) {
855 if (app->updatecheck_status == "noupdate") {
856 if (!app->packages.empty()) {
857 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
858 completer->set_code(ErrorCode::kOmahaResponseInvalid);
859 return false;
860 }
861 return true;
862 }
863 if (app->packages.empty()) {
864 LOG(ERROR) << "Omaha Response has no packages";
865 completer->set_code(ErrorCode::kOmahaResponseInvalid);
866 return false;
867 }
868 if (app->url_codebase.empty()) {
869 LOG(ERROR) << "No Omaha Response URLs";
870 completer->set_code(ErrorCode::kOmahaResponseInvalid);
871 return false;
872 }
873 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
874 vector<string> metadata_sizes =
875 base::SplitString(app->action_postinstall_attrs[kTagMetadataSize],
876 ":",
877 base::TRIM_WHITESPACE,
878 base::SPLIT_WANT_ALL);
879 vector<string> metadata_signatures =
880 base::SplitString(app->action_postinstall_attrs[kTagMetadataSignatureRsa],
881 ":",
882 base::TRIM_WHITESPACE,
883 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700884 vector<string> is_delta_payloads =
885 base::SplitString(app->action_postinstall_attrs[kTagIsDeltaPayload],
886 ":",
887 base::TRIM_WHITESPACE,
888 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700889 for (size_t i = 0; i < app->packages.size(); i++) {
890 const auto& package = app->packages[i];
891 if (package.name.empty()) {
892 LOG(ERROR) << "Omaha Response has empty package name";
893 completer->set_code(ErrorCode::kOmahaResponseInvalid);
894 return false;
895 }
896 LOG(INFO) << "Found package " << package.name;
897
898 OmahaResponse::Package out_package;
899 for (const string& codebase : app->url_codebase) {
900 if (codebase.empty()) {
901 LOG(ERROR) << "Omaha Response URL has empty codebase";
902 completer->set_code(ErrorCode::kOmahaResponseInvalid);
903 return false;
904 }
905 out_package.payload_urls.push_back(codebase + package.name);
906 }
907 // Parse the payload size.
908 base::StringToUint64(package.size, &out_package.size);
909 if (out_package.size <= 0) {
910 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
911 completer->set_code(ErrorCode::kOmahaResponseInvalid);
912 return false;
913 }
914 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
915
916 if (i < metadata_sizes.size())
917 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
918 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
919 << " bytes";
920
921 if (i < metadata_signatures.size())
922 out_package.metadata_signature = metadata_signatures[i];
923 LOG(INFO) << "Payload metadata signature = "
924 << out_package.metadata_signature;
925
926 out_package.hash = package.hash;
927 if (out_package.hash.empty()) {
928 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
929 completer->set_code(ErrorCode::kOmahaResponseInvalid);
930 return false;
931 }
932 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700933
934 if (i < is_delta_payloads.size())
935 out_package.is_delta = ParseBool(is_delta_payloads[i]);
936 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
937
Sen Jiang81259682017-03-30 15:11:30 -0700938 output_object->packages.push_back(std::move(out_package));
939 }
940
941 return true;
942}
943
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700944// Parses the 2 key version strings kernel_version and firmware_version. If the
945// field is not present, or cannot be parsed the values default to 0xffff.
946void ParseRollbackVersions(OmahaParserData* parser_data,
947 OmahaResponse* output_object) {
948 utils::ParseRollbackKeyVersion(
949 parser_data->updatecheck_attrs[kFirmwareVersion],
950 &output_object->rollback_key_version.firmware_key,
951 &output_object->rollback_key_version.firmware);
952 utils::ParseRollbackKeyVersion(
953 parser_data->updatecheck_attrs[kKernelVersion],
954 &output_object->rollback_key_version.kernel_key,
955 &output_object->rollback_key_version.kernel);
956}
957
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700958} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000959
David Zeuthene8ed8632014-07-24 13:38:10 -0400960bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700961 OmahaResponse* output_object,
962 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700963 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700964 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700965 return false;
966 }
Sen Jiang81259682017-03-30 15:11:30 -0700967 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700968
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800969 // chromium-os:37289: The PollInterval is not supported by Omaha server
970 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700971 // slow down the request rate from the server-side. Note that the PollInterval
972 // is not persisted, so it has to be sent by the server on every response to
973 // guarantee that the scheduler uses this value (otherwise, if the device got
974 // rebooted after the last server-indicated value, it'll revert to the default
975 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
976 // based on the assumption that we perform an update check every hour so that
977 // the max value of 8 will roughly be equivalent to one work day. If we decide
978 // to use PollInterval permanently, we should update the
979 // max_update_checks_allowed to take PollInterval into account. Note: The
980 // parsing for PollInterval happens even before parsing of the status because
981 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400982 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700983 &output_object->poll_interval);
984
David Zeuthen639aa362014-02-03 16:23:44 -0800985 // Check for the "elapsed_days" attribute in the "daystart"
986 // element. This is the number of days since Jan 1 2007, 0:00
987 // PST. If we don't have a persisted value of the Omaha InstallDate,
988 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400989 if (ParseInstallDate(parser_data, output_object) &&
990 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800991 // Since output_object->install_date_days is never negative, the
992 // elapsed_days -> install-date calculation is reduced to simply
993 // rounding down to the nearest number divisible by 7.
994 int remainder = output_object->install_date_days % 7;
995 int install_date_days_rounded =
996 output_object->install_date_days - remainder;
997 if (PersistInstallDate(system_state_,
998 install_date_days_rounded,
999 kProvisionedFromOmahaResponse)) {
1000 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
1001 << install_date_days_rounded << " days";
1002 }
1003 }
1004
Alex Deymo00d79ac2015-06-29 15:41:49 -07001005 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -07001006 for (const auto& app : parser_data->apps) {
1007 if (app.id == params_->GetAppId()) {
1008 if (app.cohort_set)
1009 PersistCohortData(kPrefsOmahaCohort, app.cohort);
1010 if (app.cohorthint_set)
1011 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
1012 if (app.cohortname_set)
1013 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
1014 break;
1015 }
1016 }
Alex Deymo00d79ac2015-06-29 15:41:49 -07001017
Alex Deymob3fa53b2016-04-18 19:57:58 -07001018 // Parse the updatecheck attributes.
1019 PersistEolStatus(parser_data->updatecheck_attrs);
Marton Hunyady199152d2018-05-07 19:08:48 +02001020 // Rollback-related updatecheck attributes.
1021 // Defaults to false if attribute is not present.
1022 output_object->is_rollback =
1023 ParseBool(parser_data->updatecheck_attrs[kRollback]);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001024
1025 // Parses the rollback versions of the current image. If the fields do not
1026 // exist they default to 0xffff for the 4 key versions.
1027 ParseRollbackVersions(parser_data, output_object);
Alex Deymob3fa53b2016-04-18 19:57:58 -07001028
David Zeuthene8ed8632014-07-24 13:38:10 -04001029 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001030 return false;
1031
David Zeuthene8ed8632014-07-24 13:38:10 -04001032 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001033 return false;
1034
Sen Jiang0affc2c2017-02-10 15:55:05 -08001035 // Package has to be parsed after Params now because ParseParams need to make
1036 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -07001037 for (auto& app : parser_data->apps)
1038 if (!ParsePackage(&app, output_object, completer))
1039 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001040
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001041 return true;
1042}
1043
David Zeuthene8ed8632014-07-24 13:38:10 -04001044bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001045 OmahaResponse* output_object,
1046 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001047 output_object->update_exists = false;
1048 for (size_t i = 0; i < parser_data->apps.size(); i++) {
1049 const string& status = parser_data->apps[i].updatecheck_status;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001050 if (status == "noupdate") {
1051 // Don't update if any app has status="noupdate".
Sen Jiang81259682017-03-30 15:11:30 -07001052 LOG(INFO) << "No update for <app> " << i;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001053 output_object->update_exists = false;
1054 break;
Sen Jiang81259682017-03-30 15:11:30 -07001055 } else if (status == "ok") {
Sen Jiang00adf7b2017-06-26 15:57:29 -07001056 if (parser_data->apps[i].action_postinstall_attrs["noupdate"] == "true") {
1057 // noupdate="true" in postinstall attributes means it's an update to
1058 // self, only update if there's at least one app really have update.
1059 LOG(INFO) << "Update to self for <app> " << i;
1060 } else {
1061 LOG(INFO) << "Update for <app> " << i;
1062 output_object->update_exists = true;
1063 }
Sen Jiang81259682017-03-30 15:11:30 -07001064 } else {
1065 LOG(ERROR) << "Unknown Omaha response status: " << status;
1066 completer->set_code(ErrorCode::kOmahaResponseInvalid);
1067 return false;
1068 }
1069 }
1070 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001071 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001072 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001073 }
1074
Sen Jiang81259682017-03-30 15:11:30 -07001075 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001076}
1077
David Zeuthene8ed8632014-07-24 13:38:10 -04001078bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001079 OmahaResponse* output_object,
1080 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001081 map<string, string> attrs;
1082 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001083 if (app.id == params_->GetAppId()) {
1084 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -07001085 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001086 } else if (!params_->system_app_id().empty() &&
1087 app.id == params_->system_app_id()) {
1088 // this is the system app (this check is intentionally skipped if there is
1089 // no system_app_id set)
1090 output_object->system_version = app.manifest_version;
1091 }
1092 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -07001093 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001094 }
Sen Jiang81259682017-03-30 15:11:30 -07001095 }
Chris Sosa3b748432013-06-20 16:42:59 -07001096 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -07001097 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001098 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -07001099 return false;
1100 }
1101
1102 LOG(INFO) << "Received omaha response to update to version "
1103 << output_object->version;
1104
David Zeuthene8ed8632014-07-24 13:38:10 -04001105 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001106 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001107 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001108 return false;
1109 }
1110
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001111 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -04001112 output_object->more_info_url = attrs[kTagMoreInfo];
David Zeuthene8ed8632014-07-24 13:38:10 -04001113 output_object->prompt = ParseBool(attrs[kTagPrompt]);
1114 output_object->deadline = attrs[kTagDeadline];
1115 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001116 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -04001117 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001118 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -04001119 ParseBool(attrs[kTagDisableP2PForSharing]);
1120 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001121
David Zeuthene8ed8632014-07-24 13:38:10 -04001122 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -08001123 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001124 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001125
Jay Srinivasan08262882012-12-28 19:29:43 -08001126 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -04001127 ParseBool(attrs[kTagDisablePayloadBackoff]);
Sen Jiangfe284402018-03-21 14:03:50 -07001128 output_object->powerwash_required = ParseBool(attrs[kTagPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -08001129
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001130 return true;
1131}
1132
David Zeuthene8ed8632014-07-24 13:38:10 -04001133// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +00001134// and fill in the appropriate fields of the output object. Also, notifies
1135// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -07001136void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
1137 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +00001138 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001139 string current_response(response_buffer_.begin(), response_buffer_.end());
1140 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001141
Gilad Arnold74b5f552014-10-07 08:17:16 -07001142 PayloadStateInterface* const payload_state = system_state_->payload_state();
1143
Zentaro Kavanagh76af2662018-05-15 10:54:53 -07001144 // Set the max kernel key version based on whether rollback is allowed.
1145 SetMaxKernelKeyVersionForRollback();
1146
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001147 // Events are best effort transactions -- assume they always succeed.
1148 if (IsEvent()) {
1149 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001150 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001151 return;
1152 }
1153
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001154 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001155 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -07001156 int code = GetHTTPResponseCode();
1157 // Makes sure we send sane error values.
1158 if (code < 0 || code >= 1000) {
1159 code = 999;
1160 }
David Zeuthena99981f2013-04-29 13:42:47 -07001161 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001162 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +00001163 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001164 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001165
David Zeuthene8ed8632014-07-24 13:38:10 -04001166 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -04001167 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -04001168 XML_SetUserData(parser, &parser_data);
1169 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -04001170 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001171 XML_Status res = XML_Parse(
1172 parser,
1173 reinterpret_cast<const char*>(response_buffer_.data()),
1174 response_buffer_.size(),
1175 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -04001176
1177 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -07001178 LOG(ERROR) << "Omaha response not valid XML: "
1179 << XML_ErrorString(XML_GetErrorCode(parser))
1180 << " at line " << XML_GetCurrentLineNumber(parser)
1181 << " col " << XML_GetCurrentColumnNumber(parser);
Amin Hassani91f48b42018-08-06 17:47:14 -07001182 XML_ParserFree(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -04001183 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
1184 if (response_buffer_.empty()) {
1185 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
1186 } else if (parser_data.entity_decl) {
1187 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
1188 }
1189 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001190 return;
1191 }
Amin Hassani91f48b42018-08-06 17:47:14 -07001192 XML_ParserFree(parser);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001193
Alex Deymoebbe7ef2014-10-30 13:02:49 -07001194 // Update the last ping day preferences based on the server daystart response
1195 // even if we didn't send a ping. Omaha always includes the daystart in the
1196 // response, but log the error if it didn't.
1197 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
1198 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -07001199
Amin Hassani1677e812017-06-21 13:36:36 -07001200 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
1201 // we have got a response from omaha and if its value has never been set to
1202 // true before. Failure of this function should be ignored. There should be no
1203 // need to check if a=-1 has been sent because older devices have already sent
1204 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
1205 // future checks.
1206 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
Amin Hassani80f4d4c2018-05-16 13:34:00 -07001207 if (!system_state_->hardware()->SetFirstActiveOmahaPingSent()) {
1208 system_state_->metrics_reporter()->ReportInternalErrorCode(
1209 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
1210 }
Amin Hassani1677e812017-06-21 13:36:36 -07001211 }
1212
Thieu Le116fda32011-04-19 11:01:54 -07001213 if (!HasOutputPipe()) {
1214 // Just set success to whether or not the http transfer succeeded,
1215 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001216 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001217 return;
1218 }
1219
Darin Petkov6a5b3222010-07-13 14:55:28 -07001220 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001221 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001222 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001223 output_object.update_exists = true;
1224 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001225
Weidong Guo421ff332017-04-17 10:08:38 -07001226 ErrorCode error = ErrorCode::kSuccess;
1227 if (ShouldIgnoreUpdate(&error, output_object)) {
1228 // No need to change output_object.update_exists here, since the value
1229 // has been output to the pipe.
1230 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001231 return;
1232 }
1233
David Zeuthen8f191b22013-08-06 12:27:50 -07001234 // If Omaha says to disable p2p, respect that
1235 if (output_object.disable_p2p_for_downloading) {
1236 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1237 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001238 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001239 }
1240 if (output_object.disable_p2p_for_sharing) {
1241 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1242 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001243 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001244 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001245
1246 // Update the payload state with the current response. The payload state
1247 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001248 // from what's stored already. We are updating the payload state as late
1249 // as possible in this method so that if a new release gets pushed and then
1250 // got pulled back due to some issues, we don't want to clear our internal
1251 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001252 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001253
David Zeuthen8f191b22013-08-06 12:27:50 -07001254 // It could be we've already exceeded the deadline for when p2p is
1255 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001256 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001257 payload_state->P2PNewAttempt();
1258 if (!payload_state->P2PAttemptAllowed()) {
1259 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1260 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001261 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001262 }
1263 }
1264
1265 // From here on, we'll complete stuff in CompleteProcessing() so
1266 // disable |completer| since we'll create a new one in that
1267 // function.
1268 completer.set_should_complete(false);
1269
1270 // If we're allowed to use p2p for downloading we do not pay
1271 // attention to wall-clock-based waiting if the URL is indeed
1272 // available via p2p. Therefore, check if the file is available via
1273 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001274 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001275 LookupPayloadViaP2P(output_object);
1276 } else {
1277 CompleteProcessing();
1278 }
1279}
1280
1281void OmahaRequestAction::CompleteProcessing() {
1282 ScopedActionCompleter completer(processor_, this);
1283 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1284 PayloadStateInterface* payload_state = system_state_->payload_state();
1285
Alex Deymo46a9aae2016-05-04 20:20:11 -07001286 if (system_state_->hardware()->IsOOBEEnabled() &&
1287 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
Marton Hunyadyc2882062018-05-14 17:28:25 +02001288 (output_object.deadline.empty() ||
1289 payload_state->GetRollbackHappened()) &&
Kevin Cernekeec5081a82016-04-08 12:29:52 -07001290 params_->app_version() != "ForcedUpdate") {
Kevin Cernekee2494e282016-03-29 18:03:53 -07001291 output_object.update_exists = false;
1292 LOG(INFO) << "Ignoring non-critical Omaha updates until OOBE is done.";
1293 completer.set_code(ErrorCode::kNonCriticalUpdateInOOBE);
1294 return;
1295 }
1296
David Zeuthen8f191b22013-08-06 12:27:50 -07001297 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001298 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001299 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001300 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001301 return;
1302 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001303
Chris Sosa20f005c2013-09-05 13:53:08 -07001304 if (payload_state->ShouldBackoffDownload()) {
1305 output_object.update_exists = false;
1306 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1307 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001308 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001309 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001310 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001311 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001312}
1313
1314void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1315 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1316 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001317 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001318 } else {
1319 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1320 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001321 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001322 }
1323 CompleteProcessing();
1324}
1325
1326void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001327 // If the device is in the middle of an update, the state variables
1328 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1329 // tracks the offset and length of the operation currently in
1330 // progress. The offset is based from the end of the manifest which
1331 // is kPrefsManifestMetadataSize bytes long.
1332 //
1333 // To make forward progress and avoid deadlocks, we need to find a
1334 // peer that has at least the entire operation we're currently
1335 // working on. Otherwise we may end up in a situation where two
1336 // devices bounce back and forth downloading from each other,
1337 // neither making any forward progress until one of them decides to
1338 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1339 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001340 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001341 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001342 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001343 int64_t next_data_offset = 0;
1344 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001345 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001346 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1347 &manifest_metadata_size) &&
1348 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001349 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1350 &manifest_signature_size) &&
1351 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001352 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001353 &next_data_offset) &&
1354 next_data_offset != -1 &&
1355 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1356 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001357 minimum_size = manifest_metadata_size + manifest_signature_size +
1358 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001359 }
1360
Sen Jiang0affc2c2017-02-10 15:55:05 -08001361 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001362 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001363 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001364 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001365 string file_id =
1366 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001367 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001368 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1369 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001370 system_state_->p2p_manager()->LookupUrlForFile(
1371 file_id,
1372 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001373 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001374 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1375 base::Unretained(this)));
1376 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001377}
1378
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001379bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001380 if (params_->interactive()) {
1381 LOG(INFO) << "Not deferring download because update is interactive.";
1382 return false;
1383 }
1384
David Zeuthen8f191b22013-08-06 12:27:50 -07001385 // If we're using p2p to download _and_ we have a p2p URL, we never
1386 // defer the download. This is because the download will always
1387 // happen from a peer on the LAN and we've been waiting in line for
1388 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001389 const PayloadStateInterface* payload_state = system_state_->payload_state();
1390 if (payload_state->GetUsingP2PForDownloading() &&
1391 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001392 LOG(INFO) << "Download not deferred because download "
1393 << "will happen from a local peer (via p2p).";
1394 return false;
1395 }
1396
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001397 // We should defer the downloads only if we've first satisfied the
1398 // wall-clock-based-waiting period and then the update-check-based waiting
1399 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001400 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001401 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1402 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001403 return false;
1404 }
1405
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001406 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001407 case kWallClockWaitNotSatisfied:
1408 // We haven't even satisfied the first condition, passing the
1409 // wall-clock-based waiting period, so we should defer the downloads
1410 // until that happens.
1411 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1412 return true;
1413
1414 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1415 LOG(INFO) << "wall-clock-based-wait satisfied and "
1416 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001417 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001418
1419 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1420 // Wall-clock-based waiting period is satisfied, and it's determined
1421 // that we do not need the update-check-based wait. so no need to
1422 // defer downloads.
1423 LOG(INFO) << "wall-clock-based-wait satisfied and "
1424 << "update-check-based-wait is not required.";
1425 return false;
1426
1427 default:
1428 // Returning false for this default case so we err on the
1429 // side of downloading updates than deferring in case of any bugs.
1430 NOTREACHED();
1431 return false;
1432 }
1433}
1434
1435OmahaRequestAction::WallClockWaitResult
1436OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001437 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001438 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001439 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001440
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001441 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1442 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1443 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001444 // Note: This timestamp could be that of ANY update we saw in the past
1445 // (not necessarily this particular update we're considering to apply)
1446 // but never got to apply because of some reason (e.g. stop AU policy,
1447 // updates being pulled out from Omaha, changes in target version prefix,
1448 // new update being rolled out, etc.). But for the purposes of scattering
1449 // it doesn't matter which update the timestamp corresponds to. i.e.
1450 // the clock starts ticking the first time we see an update and we're
1451 // ready to apply when the random wait period is satisfied relative to
1452 // that first seen timestamp.
1453 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1454 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1455 << utils::ToString(update_first_seen_at);
1456 } else {
1457 // This seems like an unexpected error where the persisted value exists
1458 // but it's not readable for some reason. Just skip scattering in this
1459 // case to be safe.
1460 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1461 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1462 }
1463 } else {
Sen Jiang7c1171e2016-06-23 11:35:40 -07001464 update_first_seen_at = system_state_->clock()->GetWallclockTime();
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001465 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001466 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1467 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001468 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1469 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001470 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001471 // This seems like an unexpected error where the value cannot be
1472 // persisted for some reason. Just skip scattering in this
1473 // case to be safe.
1474 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1475 << utils::ToString(update_first_seen_at)
1476 << " cannot be persisted";
1477 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1478 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001479 }
1480
Sen Jiang7c1171e2016-06-23 11:35:40 -07001481 TimeDelta elapsed_time =
1482 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1483 TimeDelta max_scatter_period =
1484 TimeDelta::FromDays(output_object->max_days_to_scatter);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001485 int64_t staging_wait_time_in_days = 0;
1486 // Use staging and its default max value if staging is on.
1487 if (system_state_->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
1488 &staging_wait_time_in_days) &&
1489 staging_wait_time_in_days > 0)
1490 max_scatter_period = TimeDelta::FromDays(kMaxWaitTimeStagingInDays);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001491
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001492 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001493 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001494 << ", Time Elapsed = "
1495 << utils::FormatSecs(elapsed_time.InSeconds())
Adolfo Victoria497044c2018-07-18 07:51:42 -07001496 << ", MaxDaysToScatter = " << max_scatter_period.InDays();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001497
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001498 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001499 // The deadline is set for all rules which serve a delta update from a
1500 // previous FSI, which means this update will be applied mostly in OOBE
1501 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1502 // quickly.
1503 LOG(INFO) << "Not scattering as deadline flag is set";
1504 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1505 }
1506
1507 if (max_scatter_period.InDays() == 0) {
1508 // This means the Omaha rule creator decides that this rule
1509 // should not be scattered irrespective of the policy.
1510 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1511 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1512 }
1513
1514 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001515 // This means we've waited more than the upperbound wait in the rule
1516 // from the time we first saw a valid update available to us.
1517 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001518 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1519 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1520 }
1521
1522 // This means we are required to participate in scattering.
1523 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001524 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001525 if (remaining_wait_time.InSeconds() <= 0) {
1526 // Yes, it's our turn now.
1527 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1528
1529 // But we can't download until the update-check-count-based wait is also
1530 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001531 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001532 kWallClockWaitDoneButUpdateCheckWaitRequired :
1533 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1534 }
1535
1536 // Not our turn yet, so we have to wait until our turn to
1537 // help scatter the downloads across all clients of the enterprise.
1538 LOG(INFO) << "Update deferred for another "
1539 << utils::FormatSecs(remaining_wait_time.InSeconds())
1540 << " per policy.";
1541 return kWallClockWaitNotSatisfied;
1542}
1543
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001544bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001545 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001546
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001547 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1548 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1549 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001550 // We are unable to read the update check count from file for some reason.
1551 // So let's proceed anyway so as to not stall the update.
1552 LOG(ERROR) << "Unable to read update check count. "
1553 << "Skipping update-check-count-based-wait.";
1554 return true;
1555 }
1556 } else {
1557 // This file does not exist. This means we haven't started our update
1558 // check count down yet, so this is the right time to start the count down.
1559 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001560 params_->min_update_checks_needed(),
1561 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001562
1563 LOG(INFO) << "Randomly picked update check count value = "
1564 << update_check_count_value;
1565
1566 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001567 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1568 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001569 // We weren't able to write the update check count file for some reason.
1570 // So let's proceed anyway so as to not stall the update.
1571 LOG(ERROR) << "Unable to write update check count. "
1572 << "Skipping update-check-count-based-wait.";
1573 return true;
1574 }
1575 }
1576
1577 if (update_check_count_value == 0) {
1578 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1579 return true;
1580 }
1581
1582 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001583 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001584 // We err on the side of skipping scattering logic instead of stalling
1585 // a machine from receiving any updates in case of any unexpected state.
1586 LOG(ERROR) << "Invalid value for update check count detected. "
1587 << "Skipping update-check-count-based-wait.";
1588 return true;
1589 }
1590
1591 // Legal value, we need to wait for more update checks to happen
1592 // until this becomes 0.
1593 LOG(INFO) << "Deferring Omaha updates for another "
1594 << update_check_count_value
1595 << " update checks per policy";
1596 return false;
1597}
1598
David Zeuthen639aa362014-02-03 16:23:44 -08001599// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001600bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001601 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001602 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001603 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001604 &elapsed_days))
1605 return false;
1606
1607 if (elapsed_days < 0)
1608 return false;
1609
1610 output_object->install_date_days = elapsed_days;
1611 return true;
1612}
1613
1614// static
1615bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1616 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001617 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001618 return false;
1619
1620 return prefs->Exists(kPrefsInstallDateDays);
1621}
1622
1623// static
1624bool OmahaRequestAction::PersistInstallDate(
1625 SystemState *system_state,
1626 int install_date_days,
1627 InstallDateProvisioningSource source) {
1628 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1629
1630 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001631 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001632 return false;
1633
1634 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1635 return false;
1636
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001637 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001638 static_cast<int>(source), // Sample.
1639 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001640 return true;
1641}
1642
Alex Deymo8e18f932015-03-27 16:16:59 -07001643bool OmahaRequestAction::PersistCohortData(
1644 const string& prefs_key,
1645 const string& new_value) {
1646 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1647 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1648 return system_state_->prefs()->Delete(prefs_key);
1649 } else if (!new_value.empty()) {
1650 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1651 return system_state_->prefs()->SetString(prefs_key, new_value);
1652 }
1653 return true;
1654}
1655
Alex Deymob3fa53b2016-04-18 19:57:58 -07001656bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
1657 auto eol_attr = attrs.find(kEolAttr);
1658 if (eol_attr != attrs.end()) {
1659 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1660 eol_attr->second);
1661 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1662 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1663 }
1664 return true;
1665}
1666
David Zeuthen33bae492014-02-25 16:16:18 -08001667void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1668 // We only want to report this on "update check".
1669 if (ping_only_ || event_ != nullptr)
1670 return;
1671
1672 metrics::CheckResult result = metrics::CheckResult::kUnset;
1673 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1674 metrics::DownloadErrorCode download_error_code =
1675 metrics::DownloadErrorCode::kUnset;
1676
1677 // Regular update attempt.
1678 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001679 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001680 // OK, we parsed the response successfully but that does
1681 // necessarily mean that an update is available.
1682 if (HasOutputPipe()) {
1683 const OmahaResponse& response = GetOutputObject();
1684 if (response.update_exists) {
1685 result = metrics::CheckResult::kUpdateAvailable;
1686 reaction = metrics::CheckReaction::kUpdating;
1687 } else {
1688 result = metrics::CheckResult::kNoUpdateAvailable;
1689 }
1690 } else {
1691 result = metrics::CheckResult::kNoUpdateAvailable;
1692 }
1693 break;
1694
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001695 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
Weidong Guo421ff332017-04-17 10:08:38 -07001696 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
David Zeuthen33bae492014-02-25 16:16:18 -08001697 result = metrics::CheckResult::kUpdateAvailable;
1698 reaction = metrics::CheckReaction::kIgnored;
1699 break;
1700
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001701 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001702 result = metrics::CheckResult::kUpdateAvailable;
1703 reaction = metrics::CheckReaction::kDeferring;
1704 break;
1705
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001706 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001707 result = metrics::CheckResult::kUpdateAvailable;
1708 reaction = metrics::CheckReaction::kBackingOff;
1709 break;
1710
1711 default:
1712 // We report two flavors of errors, "Download errors" and "Parsing
1713 // error". Try to convert to the former and if that doesn't work
1714 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001715 metrics::DownloadErrorCode tmp_error =
1716 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001717 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1718 result = metrics::CheckResult::kDownloadError;
1719 download_error_code = tmp_error;
1720 } else {
1721 result = metrics::CheckResult::kParsingError;
1722 }
1723 break;
1724 }
1725
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001726 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1727 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001728}
1729
Chris Sosa77f79e82014-06-02 18:16:24 -07001730bool OmahaRequestAction::ShouldIgnoreUpdate(
Weidong Guo421ff332017-04-17 10:08:38 -07001731 ErrorCode* error, const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001732 // Note: policy decision to not update to a version we rolled back from.
1733 string rollback_version =
1734 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001735 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001736 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001737 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001738 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001739 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001740 return true;
1741 }
1742 }
1743
Weidong Guo421ff332017-04-17 10:08:38 -07001744 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001745 LOG(INFO) << "Update is not allowed over current connection.";
1746 return true;
1747 }
1748
1749 // Note: We could technically delete the UpdateFirstSeenAt state when we
1750 // return true. If we do, it'll mean a device has to restart the
1751 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1752 // turned on again. On the other hand, it also increases the chance of update
1753 // starvation if an admin turns AU on/off more frequently. We choose to err on
1754 // the side of preventing starvation at the cost of not applying scattering in
1755 // those cases.
1756 return false;
1757}
1758
Weidong Guo421ff332017-04-17 10:08:38 -07001759bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1760 const OmahaResponse& response) const {
1761 PrefsInterface* prefs = system_state_->prefs();
1762
1763 if (!prefs) {
1764 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1765 "not available.";
1766 return false;
1767 }
1768
1769 bool is_allowed;
1770
1771 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1772 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1773 is_allowed) {
1774 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1775 "set to true.";
1776 return true;
1777 }
1778
1779 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1780 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1781 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1782 "set to false or does not exist while target does not exist.";
1783 return false;
1784 }
1785
1786 std::string target_version;
1787 int64_t target_size;
1788
1789 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1790 &target_version) ||
1791 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1792 LOG(INFO) << "Disabling updates over cellular as the target version or "
1793 "size is not accessible.";
1794 return false;
1795 }
1796
1797 uint64_t total_packages_size = 0;
1798 for (const auto& package : response.packages) {
1799 total_packages_size += package.size;
1800 }
1801 if (target_version == response.version &&
1802 static_cast<uint64_t>(target_size) == total_packages_size) {
1803 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1804 "omaha response.";
1805 return true;
1806 } else {
1807 LOG(INFO) << "Disabling updates over cellular as the target does not"
1808 "match the omaha response.";
1809 return false;
1810 }
1811}
1812
1813bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1814 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001815 ConnectionType type;
1816 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001817 ConnectionManagerInterface* connection_manager =
1818 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001819 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001820 LOG(INFO) << "We could not determine our connection type. "
1821 << "Defaulting to allow updates.";
1822 return true;
1823 }
Weidong Guo421ff332017-04-17 10:08:38 -07001824
Chris Sosa77f79e82014-06-02 18:16:24 -07001825 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001826 bool is_device_policy_set =
1827 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1828 // Treats tethered connection as if it is cellular connection.
1829 bool is_over_cellular = type == ConnectionType::kCellular ||
1830 tethering == ConnectionTethering::kConfirmed;
1831
1832 if (!is_over_cellular) {
1833 // There's no need to further check user preferences as we are not over
1834 // cellular connection.
1835 if (!is_allowed)
1836 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1837 } else if (is_device_policy_set) {
1838 // There's no need to further check user preferences as the device policy
1839 // is set regarding updates over cellular.
1840 if (!is_allowed)
1841 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1842 } else {
1843 // Deivce policy is not set, so user preferences overwrite whether to
1844 // allow updates over cellular.
1845 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1846 if (!is_allowed)
1847 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1848 }
1849
Chris Sosa77f79e82014-06-02 18:16:24 -07001850 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001851 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001852 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1853 return is_allowed;
1854}
1855
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001856bool OmahaRequestAction::IsRollbackEnabled() const {
1857 if (policy_provider_->IsConsumerDevice()) {
1858 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1859 return false;
1860 }
1861
1862 if (!policy_provider_->device_policy_is_loaded()) {
1863 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1864 return true;
1865 }
1866
1867 int allowed_milestones;
1868 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1869 &allowed_milestones)) {
1870 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1871 "Defaulting to rollback enabled.";
1872 return true;
1873 }
1874
1875 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1876 return allowed_milestones > 0;
1877}
1878
1879void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001880 int max_kernel_rollforward;
1881 int min_kernel_version = system_state_->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001882 if (IsRollbackEnabled()) {
1883 // If rollback is enabled, set the max kernel key version to the current
1884 // kernel key version. This has the effect of freezing kernel key roll
1885 // forwards.
1886 //
1887 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1888 // key roll forward happens until the server side components of rollback
1889 // are implemented. Future changes will allow the Omaha server to return
1890 // the kernel key version from max_rollback_versions in the past. At that
1891 // point the max kernel key version will be set to that value, creating a
1892 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001893 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001894 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001895 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001896 } else {
1897 // For devices that are not rollback enabled (ie. consumer devices), the
1898 // max kernel key version is set to 0xfffffffe, which is logically
1899 // infinity. This maintains the previous behavior that that kernel key
1900 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001901 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001902 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001903 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001904 }
1905
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001906 bool max_rollforward_set =
1907 system_state_->hardware()->SetMaxKernelKeyRollforward(
1908 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001909 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001910 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001911 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001912 // Report metrics
1913 system_state_->metrics_reporter()->ReportKeyVersionMetrics(
1914 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001915}
1916
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001917} // namespace chromeos_update_engine