blob: 3502048542dbde09ed12f26e4660fe70041cd4f6 [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.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700804void 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);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000809}
810
811namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000812
813// Parses a 64 bit base-10 int from a string and returns it. Returns 0
814// on error. If the string contains "0", that's indistinguishable from
815// error.
816off_t ParseInt(const string& str) {
817 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700818 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000819 if (rc < 1) {
820 // failure
821 return 0;
822 }
823 return ret;
824}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700825
David Zeuthene8ed8632014-07-24 13:38:10 -0400826// Parses |str| and returns |true| if, and only if, its value is "true".
827bool ParseBool(const string& str) {
828 return str == "true";
829}
830
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700831// Update the last ping day preferences based on the server daystart
832// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400833bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700834 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400835 TEST_AND_RETURN_FALSE(
836 base::StringToInt64(parser_data->daystart_elapsed_seconds,
837 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700838 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
839
840 // Remember the local time that matches the server's last midnight
841 // time.
842 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
843 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
844 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
845 return true;
846}
Sen Jiang81259682017-03-30 15:11:30 -0700847
848// Parses the package node in the given XML document and populates
849// |output_object| if valid. Returns true if we should continue the parsing.
850// False otherwise, in which case it sets any error code using |completer|.
851bool ParsePackage(OmahaParserData::App* app,
852 OmahaResponse* output_object,
853 ScopedActionCompleter* completer) {
854 if (app->updatecheck_status == "noupdate") {
855 if (!app->packages.empty()) {
856 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
857 completer->set_code(ErrorCode::kOmahaResponseInvalid);
858 return false;
859 }
860 return true;
861 }
862 if (app->packages.empty()) {
863 LOG(ERROR) << "Omaha Response has no packages";
864 completer->set_code(ErrorCode::kOmahaResponseInvalid);
865 return false;
866 }
867 if (app->url_codebase.empty()) {
868 LOG(ERROR) << "No Omaha Response URLs";
869 completer->set_code(ErrorCode::kOmahaResponseInvalid);
870 return false;
871 }
872 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
873 vector<string> metadata_sizes =
874 base::SplitString(app->action_postinstall_attrs[kTagMetadataSize],
875 ":",
876 base::TRIM_WHITESPACE,
877 base::SPLIT_WANT_ALL);
878 vector<string> metadata_signatures =
879 base::SplitString(app->action_postinstall_attrs[kTagMetadataSignatureRsa],
880 ":",
881 base::TRIM_WHITESPACE,
882 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700883 vector<string> is_delta_payloads =
884 base::SplitString(app->action_postinstall_attrs[kTagIsDeltaPayload],
885 ":",
886 base::TRIM_WHITESPACE,
887 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700888 for (size_t i = 0; i < app->packages.size(); i++) {
889 const auto& package = app->packages[i];
890 if (package.name.empty()) {
891 LOG(ERROR) << "Omaha Response has empty package name";
892 completer->set_code(ErrorCode::kOmahaResponseInvalid);
893 return false;
894 }
895 LOG(INFO) << "Found package " << package.name;
896
897 OmahaResponse::Package out_package;
898 for (const string& codebase : app->url_codebase) {
899 if (codebase.empty()) {
900 LOG(ERROR) << "Omaha Response URL has empty codebase";
901 completer->set_code(ErrorCode::kOmahaResponseInvalid);
902 return false;
903 }
904 out_package.payload_urls.push_back(codebase + package.name);
905 }
906 // Parse the payload size.
907 base::StringToUint64(package.size, &out_package.size);
908 if (out_package.size <= 0) {
909 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
910 completer->set_code(ErrorCode::kOmahaResponseInvalid);
911 return false;
912 }
913 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
914
915 if (i < metadata_sizes.size())
916 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
917 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
918 << " bytes";
919
920 if (i < metadata_signatures.size())
921 out_package.metadata_signature = metadata_signatures[i];
922 LOG(INFO) << "Payload metadata signature = "
923 << out_package.metadata_signature;
924
925 out_package.hash = package.hash;
926 if (out_package.hash.empty()) {
927 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
928 completer->set_code(ErrorCode::kOmahaResponseInvalid);
929 return false;
930 }
931 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700932
933 if (i < is_delta_payloads.size())
934 out_package.is_delta = ParseBool(is_delta_payloads[i]);
935 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
936
Sen Jiang81259682017-03-30 15:11:30 -0700937 output_object->packages.push_back(std::move(out_package));
938 }
939
940 return true;
941}
942
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700943// Parses the 2 key version strings kernel_version and firmware_version. If the
944// field is not present, or cannot be parsed the values default to 0xffff.
945void ParseRollbackVersions(OmahaParserData* parser_data,
946 OmahaResponse* output_object) {
947 utils::ParseRollbackKeyVersion(
948 parser_data->updatecheck_attrs[kFirmwareVersion],
949 &output_object->rollback_key_version.firmware_key,
950 &output_object->rollback_key_version.firmware);
951 utils::ParseRollbackKeyVersion(
952 parser_data->updatecheck_attrs[kKernelVersion],
953 &output_object->rollback_key_version.kernel_key,
954 &output_object->rollback_key_version.kernel);
955}
956
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700957} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000958
David Zeuthene8ed8632014-07-24 13:38:10 -0400959bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700960 OmahaResponse* output_object,
961 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700962 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700963 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700964 return false;
965 }
Sen Jiang81259682017-03-30 15:11:30 -0700966 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700967
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800968 // chromium-os:37289: The PollInterval is not supported by Omaha server
969 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700970 // slow down the request rate from the server-side. Note that the PollInterval
971 // is not persisted, so it has to be sent by the server on every response to
972 // guarantee that the scheduler uses this value (otherwise, if the device got
973 // rebooted after the last server-indicated value, it'll revert to the default
974 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
975 // based on the assumption that we perform an update check every hour so that
976 // the max value of 8 will roughly be equivalent to one work day. If we decide
977 // to use PollInterval permanently, we should update the
978 // max_update_checks_allowed to take PollInterval into account. Note: The
979 // parsing for PollInterval happens even before parsing of the status because
980 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400981 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700982 &output_object->poll_interval);
983
David Zeuthen639aa362014-02-03 16:23:44 -0800984 // Check for the "elapsed_days" attribute in the "daystart"
985 // element. This is the number of days since Jan 1 2007, 0:00
986 // PST. If we don't have a persisted value of the Omaha InstallDate,
987 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400988 if (ParseInstallDate(parser_data, output_object) &&
989 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800990 // Since output_object->install_date_days is never negative, the
991 // elapsed_days -> install-date calculation is reduced to simply
992 // rounding down to the nearest number divisible by 7.
993 int remainder = output_object->install_date_days % 7;
994 int install_date_days_rounded =
995 output_object->install_date_days - remainder;
996 if (PersistInstallDate(system_state_,
997 install_date_days_rounded,
998 kProvisionedFromOmahaResponse)) {
999 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
1000 << install_date_days_rounded << " days";
1001 }
1002 }
1003
Alex Deymo00d79ac2015-06-29 15:41:49 -07001004 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -07001005 for (const auto& app : parser_data->apps) {
1006 if (app.id == params_->GetAppId()) {
1007 if (app.cohort_set)
1008 PersistCohortData(kPrefsOmahaCohort, app.cohort);
1009 if (app.cohorthint_set)
1010 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
1011 if (app.cohortname_set)
1012 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
1013 break;
1014 }
1015 }
Alex Deymo00d79ac2015-06-29 15:41:49 -07001016
Alex Deymob3fa53b2016-04-18 19:57:58 -07001017 // Parse the updatecheck attributes.
1018 PersistEolStatus(parser_data->updatecheck_attrs);
Marton Hunyady199152d2018-05-07 19:08:48 +02001019 // Rollback-related updatecheck attributes.
1020 // Defaults to false if attribute is not present.
1021 output_object->is_rollback =
1022 ParseBool(parser_data->updatecheck_attrs[kRollback]);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001023
1024 // Parses the rollback versions of the current image. If the fields do not
1025 // exist they default to 0xffff for the 4 key versions.
1026 ParseRollbackVersions(parser_data, output_object);
Alex Deymob3fa53b2016-04-18 19:57:58 -07001027
David Zeuthene8ed8632014-07-24 13:38:10 -04001028 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001029 return false;
1030
David Zeuthene8ed8632014-07-24 13:38:10 -04001031 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001032 return false;
1033
Sen Jiang0affc2c2017-02-10 15:55:05 -08001034 // Package has to be parsed after Params now because ParseParams need to make
1035 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -07001036 for (auto& app : parser_data->apps)
1037 if (!ParsePackage(&app, output_object, completer))
1038 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001039
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001040 return true;
1041}
1042
David Zeuthene8ed8632014-07-24 13:38:10 -04001043bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001044 OmahaResponse* output_object,
1045 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001046 output_object->update_exists = false;
1047 for (size_t i = 0; i < parser_data->apps.size(); i++) {
1048 const string& status = parser_data->apps[i].updatecheck_status;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001049 if (status == "noupdate") {
1050 // Don't update if any app has status="noupdate".
Sen Jiang81259682017-03-30 15:11:30 -07001051 LOG(INFO) << "No update for <app> " << i;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001052 output_object->update_exists = false;
1053 break;
Sen Jiang81259682017-03-30 15:11:30 -07001054 } else if (status == "ok") {
Sen Jiang00adf7b2017-06-26 15:57:29 -07001055 if (parser_data->apps[i].action_postinstall_attrs["noupdate"] == "true") {
1056 // noupdate="true" in postinstall attributes means it's an update to
1057 // self, only update if there's at least one app really have update.
1058 LOG(INFO) << "Update to self for <app> " << i;
1059 } else {
1060 LOG(INFO) << "Update for <app> " << i;
1061 output_object->update_exists = true;
1062 }
Sen Jiang81259682017-03-30 15:11:30 -07001063 } else {
1064 LOG(ERROR) << "Unknown Omaha response status: " << status;
1065 completer->set_code(ErrorCode::kOmahaResponseInvalid);
1066 return false;
1067 }
1068 }
1069 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001070 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001071 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001072 }
1073
Sen Jiang81259682017-03-30 15:11:30 -07001074 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001075}
1076
David Zeuthene8ed8632014-07-24 13:38:10 -04001077bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001078 OmahaResponse* output_object,
1079 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001080 map<string, string> attrs;
1081 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001082 if (app.id == params_->GetAppId()) {
1083 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -07001084 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001085 } else if (!params_->system_app_id().empty() &&
1086 app.id == params_->system_app_id()) {
1087 // this is the system app (this check is intentionally skipped if there is
1088 // no system_app_id set)
1089 output_object->system_version = app.manifest_version;
1090 }
1091 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -07001092 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001093 }
Sen Jiang81259682017-03-30 15:11:30 -07001094 }
Chris Sosa3b748432013-06-20 16:42:59 -07001095 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -07001096 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001097 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -07001098 return false;
1099 }
1100
1101 LOG(INFO) << "Received omaha response to update to version "
1102 << output_object->version;
1103
David Zeuthene8ed8632014-07-24 13:38:10 -04001104 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001105 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001106 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001107 return false;
1108 }
1109
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001110 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -04001111 output_object->more_info_url = attrs[kTagMoreInfo];
David Zeuthene8ed8632014-07-24 13:38:10 -04001112 output_object->prompt = ParseBool(attrs[kTagPrompt]);
1113 output_object->deadline = attrs[kTagDeadline];
1114 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001115 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -04001116 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001117 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -04001118 ParseBool(attrs[kTagDisableP2PForSharing]);
1119 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001120
David Zeuthene8ed8632014-07-24 13:38:10 -04001121 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -08001122 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001123 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001124
Jay Srinivasan08262882012-12-28 19:29:43 -08001125 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -04001126 ParseBool(attrs[kTagDisablePayloadBackoff]);
Sen Jiangfe284402018-03-21 14:03:50 -07001127 output_object->powerwash_required = ParseBool(attrs[kTagPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -08001128
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001129 return true;
1130}
1131
David Zeuthene8ed8632014-07-24 13:38:10 -04001132// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +00001133// and fill in the appropriate fields of the output object. Also, notifies
1134// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -07001135void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
1136 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +00001137 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001138 string current_response(response_buffer_.begin(), response_buffer_.end());
1139 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001140
Gilad Arnold74b5f552014-10-07 08:17:16 -07001141 PayloadStateInterface* const payload_state = system_state_->payload_state();
1142
Zentaro Kavanagh76af2662018-05-15 10:54:53 -07001143 // Set the max kernel key version based on whether rollback is allowed.
1144 SetMaxKernelKeyVersionForRollback();
1145
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001146 // Events are best effort transactions -- assume they always succeed.
1147 if (IsEvent()) {
1148 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001149 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001150 return;
1151 }
1152
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001153 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001154 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -07001155 int code = GetHTTPResponseCode();
1156 // Makes sure we send sane error values.
1157 if (code < 0 || code >= 1000) {
1158 code = 999;
1159 }
David Zeuthena99981f2013-04-29 13:42:47 -07001160 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001161 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +00001162 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001163 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001164
David Zeuthene8ed8632014-07-24 13:38:10 -04001165 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -04001166 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -04001167 XML_SetUserData(parser, &parser_data);
1168 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -04001169 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001170 XML_Status res = XML_Parse(
1171 parser,
1172 reinterpret_cast<const char*>(response_buffer_.data()),
1173 response_buffer_.size(),
1174 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -04001175 XML_ParserFree(parser);
1176
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);
David Zeuthenf3e28012014-08-26 18:23:52 -04001182 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
1183 if (response_buffer_.empty()) {
1184 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
1185 } else if (parser_data.entity_decl) {
1186 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
1187 }
1188 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001189 return;
1190 }
1191
Alex Deymoebbe7ef2014-10-30 13:02:49 -07001192 // Update the last ping day preferences based on the server daystart response
1193 // even if we didn't send a ping. Omaha always includes the daystart in the
1194 // response, but log the error if it didn't.
1195 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
1196 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -07001197
Amin Hassani1677e812017-06-21 13:36:36 -07001198 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
1199 // we have got a response from omaha and if its value has never been set to
1200 // true before. Failure of this function should be ignored. There should be no
1201 // need to check if a=-1 has been sent because older devices have already sent
1202 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
1203 // future checks.
1204 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
Amin Hassani80f4d4c2018-05-16 13:34:00 -07001205 if (!system_state_->hardware()->SetFirstActiveOmahaPingSent()) {
1206 system_state_->metrics_reporter()->ReportInternalErrorCode(
1207 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
1208 }
Amin Hassani1677e812017-06-21 13:36:36 -07001209 }
1210
Thieu Le116fda32011-04-19 11:01:54 -07001211 if (!HasOutputPipe()) {
1212 // Just set success to whether or not the http transfer succeeded,
1213 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001214 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001215 return;
1216 }
1217
Darin Petkov6a5b3222010-07-13 14:55:28 -07001218 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001219 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001220 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001221 output_object.update_exists = true;
1222 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001223
Weidong Guo421ff332017-04-17 10:08:38 -07001224 ErrorCode error = ErrorCode::kSuccess;
1225 if (ShouldIgnoreUpdate(&error, output_object)) {
1226 // No need to change output_object.update_exists here, since the value
1227 // has been output to the pipe.
1228 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001229 return;
1230 }
1231
David Zeuthen8f191b22013-08-06 12:27:50 -07001232 // If Omaha says to disable p2p, respect that
1233 if (output_object.disable_p2p_for_downloading) {
1234 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1235 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001236 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001237 }
1238 if (output_object.disable_p2p_for_sharing) {
1239 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1240 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001241 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001242 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001243
1244 // Update the payload state with the current response. The payload state
1245 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001246 // from what's stored already. We are updating the payload state as late
1247 // as possible in this method so that if a new release gets pushed and then
1248 // got pulled back due to some issues, we don't want to clear our internal
1249 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001250 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001251
David Zeuthen8f191b22013-08-06 12:27:50 -07001252 // It could be we've already exceeded the deadline for when p2p is
1253 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001254 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001255 payload_state->P2PNewAttempt();
1256 if (!payload_state->P2PAttemptAllowed()) {
1257 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1258 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001259 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001260 }
1261 }
1262
1263 // From here on, we'll complete stuff in CompleteProcessing() so
1264 // disable |completer| since we'll create a new one in that
1265 // function.
1266 completer.set_should_complete(false);
1267
1268 // If we're allowed to use p2p for downloading we do not pay
1269 // attention to wall-clock-based waiting if the URL is indeed
1270 // available via p2p. Therefore, check if the file is available via
1271 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001272 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001273 LookupPayloadViaP2P(output_object);
1274 } else {
1275 CompleteProcessing();
1276 }
1277}
1278
1279void OmahaRequestAction::CompleteProcessing() {
1280 ScopedActionCompleter completer(processor_, this);
1281 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1282 PayloadStateInterface* payload_state = system_state_->payload_state();
1283
Alex Deymo46a9aae2016-05-04 20:20:11 -07001284 if (system_state_->hardware()->IsOOBEEnabled() &&
1285 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
Marton Hunyadyc2882062018-05-14 17:28:25 +02001286 (output_object.deadline.empty() ||
1287 payload_state->GetRollbackHappened()) &&
Kevin Cernekeec5081a82016-04-08 12:29:52 -07001288 params_->app_version() != "ForcedUpdate") {
Kevin Cernekee2494e282016-03-29 18:03:53 -07001289 output_object.update_exists = false;
1290 LOG(INFO) << "Ignoring non-critical Omaha updates until OOBE is done.";
1291 completer.set_code(ErrorCode::kNonCriticalUpdateInOOBE);
1292 return;
1293 }
1294
David Zeuthen8f191b22013-08-06 12:27:50 -07001295 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001296 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001297 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001298 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001299 return;
1300 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001301
Chris Sosa20f005c2013-09-05 13:53:08 -07001302 if (payload_state->ShouldBackoffDownload()) {
1303 output_object.update_exists = false;
1304 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1305 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001306 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001307 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001308 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001309 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001310}
1311
1312void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1313 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1314 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001315 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001316 } else {
1317 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1318 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001319 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001320 }
1321 CompleteProcessing();
1322}
1323
1324void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001325 // If the device is in the middle of an update, the state variables
1326 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1327 // tracks the offset and length of the operation currently in
1328 // progress. The offset is based from the end of the manifest which
1329 // is kPrefsManifestMetadataSize bytes long.
1330 //
1331 // To make forward progress and avoid deadlocks, we need to find a
1332 // peer that has at least the entire operation we're currently
1333 // working on. Otherwise we may end up in a situation where two
1334 // devices bounce back and forth downloading from each other,
1335 // neither making any forward progress until one of them decides to
1336 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1337 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001338 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001339 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001340 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001341 int64_t next_data_offset = 0;
1342 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001343 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001344 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1345 &manifest_metadata_size) &&
1346 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001347 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1348 &manifest_signature_size) &&
1349 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001350 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001351 &next_data_offset) &&
1352 next_data_offset != -1 &&
1353 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1354 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001355 minimum_size = manifest_metadata_size + manifest_signature_size +
1356 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001357 }
1358
Sen Jiang0affc2c2017-02-10 15:55:05 -08001359 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001360 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001361 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001362 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001363 string file_id =
1364 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001365 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001366 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1367 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001368 system_state_->p2p_manager()->LookupUrlForFile(
1369 file_id,
1370 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001371 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001372 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1373 base::Unretained(this)));
1374 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001375}
1376
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001377bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001378 if (params_->interactive()) {
1379 LOG(INFO) << "Not deferring download because update is interactive.";
1380 return false;
1381 }
1382
David Zeuthen8f191b22013-08-06 12:27:50 -07001383 // If we're using p2p to download _and_ we have a p2p URL, we never
1384 // defer the download. This is because the download will always
1385 // happen from a peer on the LAN and we've been waiting in line for
1386 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001387 const PayloadStateInterface* payload_state = system_state_->payload_state();
1388 if (payload_state->GetUsingP2PForDownloading() &&
1389 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001390 LOG(INFO) << "Download not deferred because download "
1391 << "will happen from a local peer (via p2p).";
1392 return false;
1393 }
1394
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001395 // We should defer the downloads only if we've first satisfied the
1396 // wall-clock-based-waiting period and then the update-check-based waiting
1397 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001398 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001399 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1400 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001401 return false;
1402 }
1403
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001404 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001405 case kWallClockWaitNotSatisfied:
1406 // We haven't even satisfied the first condition, passing the
1407 // wall-clock-based waiting period, so we should defer the downloads
1408 // until that happens.
1409 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1410 return true;
1411
1412 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1413 LOG(INFO) << "wall-clock-based-wait satisfied and "
1414 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001415 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001416
1417 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1418 // Wall-clock-based waiting period is satisfied, and it's determined
1419 // that we do not need the update-check-based wait. so no need to
1420 // defer downloads.
1421 LOG(INFO) << "wall-clock-based-wait satisfied and "
1422 << "update-check-based-wait is not required.";
1423 return false;
1424
1425 default:
1426 // Returning false for this default case so we err on the
1427 // side of downloading updates than deferring in case of any bugs.
1428 NOTREACHED();
1429 return false;
1430 }
1431}
1432
1433OmahaRequestAction::WallClockWaitResult
1434OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001435 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001436 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001437 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001438
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001439 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1440 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1441 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001442 // Note: This timestamp could be that of ANY update we saw in the past
1443 // (not necessarily this particular update we're considering to apply)
1444 // but never got to apply because of some reason (e.g. stop AU policy,
1445 // updates being pulled out from Omaha, changes in target version prefix,
1446 // new update being rolled out, etc.). But for the purposes of scattering
1447 // it doesn't matter which update the timestamp corresponds to. i.e.
1448 // the clock starts ticking the first time we see an update and we're
1449 // ready to apply when the random wait period is satisfied relative to
1450 // that first seen timestamp.
1451 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1452 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1453 << utils::ToString(update_first_seen_at);
1454 } else {
1455 // This seems like an unexpected error where the persisted value exists
1456 // but it's not readable for some reason. Just skip scattering in this
1457 // case to be safe.
1458 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1459 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1460 }
1461 } else {
Sen Jiang7c1171e2016-06-23 11:35:40 -07001462 update_first_seen_at = system_state_->clock()->GetWallclockTime();
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001463 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001464 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1465 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001466 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1467 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001468 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001469 // This seems like an unexpected error where the value cannot be
1470 // persisted for some reason. Just skip scattering in this
1471 // case to be safe.
1472 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1473 << utils::ToString(update_first_seen_at)
1474 << " cannot be persisted";
1475 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1476 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001477 }
1478
Sen Jiang7c1171e2016-06-23 11:35:40 -07001479 TimeDelta elapsed_time =
1480 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1481 TimeDelta max_scatter_period =
1482 TimeDelta::FromDays(output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001483
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001484 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001485 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001486 << ", Time Elapsed = "
1487 << utils::FormatSecs(elapsed_time.InSeconds())
1488 << ", MaxDaysToScatter = "
1489 << max_scatter_period.InDays();
1490
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001491 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001492 // The deadline is set for all rules which serve a delta update from a
1493 // previous FSI, which means this update will be applied mostly in OOBE
1494 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1495 // quickly.
1496 LOG(INFO) << "Not scattering as deadline flag is set";
1497 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1498 }
1499
1500 if (max_scatter_period.InDays() == 0) {
1501 // This means the Omaha rule creator decides that this rule
1502 // should not be scattered irrespective of the policy.
1503 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1504 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1505 }
1506
1507 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001508 // This means we've waited more than the upperbound wait in the rule
1509 // from the time we first saw a valid update available to us.
1510 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001511 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1512 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1513 }
1514
1515 // This means we are required to participate in scattering.
1516 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001517 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001518 if (remaining_wait_time.InSeconds() <= 0) {
1519 // Yes, it's our turn now.
1520 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1521
1522 // But we can't download until the update-check-count-based wait is also
1523 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001524 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001525 kWallClockWaitDoneButUpdateCheckWaitRequired :
1526 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1527 }
1528
1529 // Not our turn yet, so we have to wait until our turn to
1530 // help scatter the downloads across all clients of the enterprise.
1531 LOG(INFO) << "Update deferred for another "
1532 << utils::FormatSecs(remaining_wait_time.InSeconds())
1533 << " per policy.";
1534 return kWallClockWaitNotSatisfied;
1535}
1536
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001537bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001538 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001539
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001540 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1541 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1542 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001543 // We are unable to read the update check count from file for some reason.
1544 // So let's proceed anyway so as to not stall the update.
1545 LOG(ERROR) << "Unable to read update check count. "
1546 << "Skipping update-check-count-based-wait.";
1547 return true;
1548 }
1549 } else {
1550 // This file does not exist. This means we haven't started our update
1551 // check count down yet, so this is the right time to start the count down.
1552 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001553 params_->min_update_checks_needed(),
1554 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001555
1556 LOG(INFO) << "Randomly picked update check count value = "
1557 << update_check_count_value;
1558
1559 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001560 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1561 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001562 // We weren't able to write the update check count file for some reason.
1563 // So let's proceed anyway so as to not stall the update.
1564 LOG(ERROR) << "Unable to write update check count. "
1565 << "Skipping update-check-count-based-wait.";
1566 return true;
1567 }
1568 }
1569
1570 if (update_check_count_value == 0) {
1571 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1572 return true;
1573 }
1574
1575 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001576 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001577 // We err on the side of skipping scattering logic instead of stalling
1578 // a machine from receiving any updates in case of any unexpected state.
1579 LOG(ERROR) << "Invalid value for update check count detected. "
1580 << "Skipping update-check-count-based-wait.";
1581 return true;
1582 }
1583
1584 // Legal value, we need to wait for more update checks to happen
1585 // until this becomes 0.
1586 LOG(INFO) << "Deferring Omaha updates for another "
1587 << update_check_count_value
1588 << " update checks per policy";
1589 return false;
1590}
1591
David Zeuthen639aa362014-02-03 16:23:44 -08001592// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001593bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001594 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001595 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001596 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001597 &elapsed_days))
1598 return false;
1599
1600 if (elapsed_days < 0)
1601 return false;
1602
1603 output_object->install_date_days = elapsed_days;
1604 return true;
1605}
1606
1607// static
1608bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1609 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001610 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001611 return false;
1612
1613 return prefs->Exists(kPrefsInstallDateDays);
1614}
1615
1616// static
1617bool OmahaRequestAction::PersistInstallDate(
1618 SystemState *system_state,
1619 int install_date_days,
1620 InstallDateProvisioningSource source) {
1621 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1622
1623 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001624 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001625 return false;
1626
1627 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1628 return false;
1629
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001630 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001631 static_cast<int>(source), // Sample.
1632 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001633 return true;
1634}
1635
Alex Deymo8e18f932015-03-27 16:16:59 -07001636bool OmahaRequestAction::PersistCohortData(
1637 const string& prefs_key,
1638 const string& new_value) {
1639 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1640 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1641 return system_state_->prefs()->Delete(prefs_key);
1642 } else if (!new_value.empty()) {
1643 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1644 return system_state_->prefs()->SetString(prefs_key, new_value);
1645 }
1646 return true;
1647}
1648
Alex Deymob3fa53b2016-04-18 19:57:58 -07001649bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
1650 auto eol_attr = attrs.find(kEolAttr);
1651 if (eol_attr != attrs.end()) {
1652 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1653 eol_attr->second);
1654 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1655 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1656 }
1657 return true;
1658}
1659
David Zeuthen33bae492014-02-25 16:16:18 -08001660void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1661 // We only want to report this on "update check".
1662 if (ping_only_ || event_ != nullptr)
1663 return;
1664
1665 metrics::CheckResult result = metrics::CheckResult::kUnset;
1666 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1667 metrics::DownloadErrorCode download_error_code =
1668 metrics::DownloadErrorCode::kUnset;
1669
1670 // Regular update attempt.
1671 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001672 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001673 // OK, we parsed the response successfully but that does
1674 // necessarily mean that an update is available.
1675 if (HasOutputPipe()) {
1676 const OmahaResponse& response = GetOutputObject();
1677 if (response.update_exists) {
1678 result = metrics::CheckResult::kUpdateAvailable;
1679 reaction = metrics::CheckReaction::kUpdating;
1680 } else {
1681 result = metrics::CheckResult::kNoUpdateAvailable;
1682 }
1683 } else {
1684 result = metrics::CheckResult::kNoUpdateAvailable;
1685 }
1686 break;
1687
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001688 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
Weidong Guo421ff332017-04-17 10:08:38 -07001689 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
David Zeuthen33bae492014-02-25 16:16:18 -08001690 result = metrics::CheckResult::kUpdateAvailable;
1691 reaction = metrics::CheckReaction::kIgnored;
1692 break;
1693
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001694 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001695 result = metrics::CheckResult::kUpdateAvailable;
1696 reaction = metrics::CheckReaction::kDeferring;
1697 break;
1698
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001699 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001700 result = metrics::CheckResult::kUpdateAvailable;
1701 reaction = metrics::CheckReaction::kBackingOff;
1702 break;
1703
1704 default:
1705 // We report two flavors of errors, "Download errors" and "Parsing
1706 // error". Try to convert to the former and if that doesn't work
1707 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001708 metrics::DownloadErrorCode tmp_error =
1709 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001710 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1711 result = metrics::CheckResult::kDownloadError;
1712 download_error_code = tmp_error;
1713 } else {
1714 result = metrics::CheckResult::kParsingError;
1715 }
1716 break;
1717 }
1718
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001719 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1720 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001721}
1722
Chris Sosa77f79e82014-06-02 18:16:24 -07001723bool OmahaRequestAction::ShouldIgnoreUpdate(
Weidong Guo421ff332017-04-17 10:08:38 -07001724 ErrorCode* error, const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001725 // Note: policy decision to not update to a version we rolled back from.
1726 string rollback_version =
1727 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001728 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001729 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001730 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001731 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001732 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001733 return true;
1734 }
1735 }
1736
Weidong Guo421ff332017-04-17 10:08:38 -07001737 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001738 LOG(INFO) << "Update is not allowed over current connection.";
1739 return true;
1740 }
1741
1742 // Note: We could technically delete the UpdateFirstSeenAt state when we
1743 // return true. If we do, it'll mean a device has to restart the
1744 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1745 // turned on again. On the other hand, it also increases the chance of update
1746 // starvation if an admin turns AU on/off more frequently. We choose to err on
1747 // the side of preventing starvation at the cost of not applying scattering in
1748 // those cases.
1749 return false;
1750}
1751
Weidong Guo421ff332017-04-17 10:08:38 -07001752bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1753 const OmahaResponse& response) const {
1754 PrefsInterface* prefs = system_state_->prefs();
1755
1756 if (!prefs) {
1757 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1758 "not available.";
1759 return false;
1760 }
1761
1762 bool is_allowed;
1763
1764 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1765 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1766 is_allowed) {
1767 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1768 "set to true.";
1769 return true;
1770 }
1771
1772 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1773 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1774 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1775 "set to false or does not exist while target does not exist.";
1776 return false;
1777 }
1778
1779 std::string target_version;
1780 int64_t target_size;
1781
1782 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1783 &target_version) ||
1784 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1785 LOG(INFO) << "Disabling updates over cellular as the target version or "
1786 "size is not accessible.";
1787 return false;
1788 }
1789
1790 uint64_t total_packages_size = 0;
1791 for (const auto& package : response.packages) {
1792 total_packages_size += package.size;
1793 }
1794 if (target_version == response.version &&
1795 static_cast<uint64_t>(target_size) == total_packages_size) {
1796 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1797 "omaha response.";
1798 return true;
1799 } else {
1800 LOG(INFO) << "Disabling updates over cellular as the target does not"
1801 "match the omaha response.";
1802 return false;
1803 }
1804}
1805
1806bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1807 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001808 ConnectionType type;
1809 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001810 ConnectionManagerInterface* connection_manager =
1811 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001812 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001813 LOG(INFO) << "We could not determine our connection type. "
1814 << "Defaulting to allow updates.";
1815 return true;
1816 }
Weidong Guo421ff332017-04-17 10:08:38 -07001817
Chris Sosa77f79e82014-06-02 18:16:24 -07001818 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001819 bool is_device_policy_set =
1820 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1821 // Treats tethered connection as if it is cellular connection.
1822 bool is_over_cellular = type == ConnectionType::kCellular ||
1823 tethering == ConnectionTethering::kConfirmed;
1824
1825 if (!is_over_cellular) {
1826 // There's no need to further check user preferences as we are not over
1827 // cellular connection.
1828 if (!is_allowed)
1829 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1830 } else if (is_device_policy_set) {
1831 // There's no need to further check user preferences as the device policy
1832 // is set regarding updates over cellular.
1833 if (!is_allowed)
1834 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1835 } else {
1836 // Deivce policy is not set, so user preferences overwrite whether to
1837 // allow updates over cellular.
1838 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1839 if (!is_allowed)
1840 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1841 }
1842
Chris Sosa77f79e82014-06-02 18:16:24 -07001843 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001844 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001845 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1846 return is_allowed;
1847}
1848
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001849bool OmahaRequestAction::IsRollbackEnabled() const {
1850 if (policy_provider_->IsConsumerDevice()) {
1851 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1852 return false;
1853 }
1854
1855 if (!policy_provider_->device_policy_is_loaded()) {
1856 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1857 return true;
1858 }
1859
1860 int allowed_milestones;
1861 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1862 &allowed_milestones)) {
1863 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1864 "Defaulting to rollback enabled.";
1865 return true;
1866 }
1867
1868 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1869 return allowed_milestones > 0;
1870}
1871
1872void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001873 int max_kernel_rollforward;
1874 int min_kernel_version = system_state_->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001875 if (IsRollbackEnabled()) {
1876 // If rollback is enabled, set the max kernel key version to the current
1877 // kernel key version. This has the effect of freezing kernel key roll
1878 // forwards.
1879 //
1880 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1881 // key roll forward happens until the server side components of rollback
1882 // are implemented. Future changes will allow the Omaha server to return
1883 // the kernel key version from max_rollback_versions in the past. At that
1884 // point the max kernel key version will be set to that value, creating a
1885 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001886 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001887 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001888 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001889 } else {
1890 // For devices that are not rollback enabled (ie. consumer devices), the
1891 // max kernel key version is set to 0xfffffffe, which is logically
1892 // infinity. This maintains the previous behavior that that kernel key
1893 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001894 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001895 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001896 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001897 }
1898
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001899 bool max_rollforward_set =
1900 system_state_->hardware()->SetMaxKernelKeyRollforward(
1901 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001902 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001903 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001904 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001905 // Report metrics
1906 system_state_->metrics_reporter()->ReportKeyVersionMetrics(
1907 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001908}
1909
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001910} // namespace chromeos_update_engine