blob: 1becb8ee331c3b9f4195944c2f87a04c2c58dca3 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
rspangler@google.com49fdf182009-10-10 00:57:34 +000016
Darin Petkov6a5b3222010-07-13 14:55:28 -070017#include "update_engine/omaha_request_action.h"
Darin Petkov85ced132010-09-01 10:20:56 -070018
Andrew de los Reyes08c4e272010-04-15 14:02:17 -070019#include <inttypes.h>
Darin Petkov85ced132010-09-01 10:20:56 -070020
David Zeuthene8ed8632014-07-24 13:38:10 -040021#include <map>
rspangler@google.com49fdf182009-10-10 00:57:34 +000022#include <sstream>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070023#include <string>
Sen Jiang8cd42342018-01-31 12:06:59 -080024#include <utility>
David Zeuthene8ed8632014-07-24 13:38:10 -040025#include <vector>
rspangler@google.com49fdf182009-10-10 00:57:34 +000026
David Zeuthen8f191b22013-08-06 12:27:50 -070027#include <base/bind.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070028#include <base/logging.h>
29#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070030#include <base/strings/string_number_conversions.h>
Sen Jiang0affc2c2017-02-10 15:55:05 -080031#include <base/strings/string_split.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070032#include <base/strings/string_util.h>
33#include <base/strings/stringprintf.h>
34#include <base/time/time.h>
Sen Jiang684c9cd2017-10-17 16:26:45 -070035#include <brillo/key_value_store.h>
David Zeuthene8ed8632014-07-24 13:38:10 -040036#include <expat.h>
Alex Deymoa2591792015-11-17 00:39:40 -030037#include <metrics/metrics_library.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000038
Alex Deymo39910dc2015-11-09 17:04:30 -080039#include "update_engine/common/action_pipe.h"
40#include "update_engine/common/constants.h"
41#include "update_engine/common/hardware_interface.h"
42#include "update_engine/common/hash_calculator.h"
43#include "update_engine/common/platform_constants.h"
44#include "update_engine/common/prefs_interface.h"
45#include "update_engine/common/utils.h"
Sen Jiang255e22b2016-05-20 16:15:29 -070046#include "update_engine/connection_manager_interface.h"
Tianjie Xu282aa1f2017-09-05 13:42:45 -070047#include "update_engine/metrics_reporter_interface.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080048#include "update_engine/metrics_utils.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070049#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070050#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080051#include "update_engine/payload_state_interface.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000052
Darin Petkov1cbd78f2010-07-29 12:38:34 -070053using base::Time;
54using base::TimeDelta;
David Zeuthene8ed8632014-07-24 13:38:10 -040055using std::map;
rspangler@google.com49fdf182009-10-10 00:57:34 +000056using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040057using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000058
59namespace chromeos_update_engine {
60
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080061// List of custom pair tags that we interpret in the Omaha Response:
62static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080063static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070064static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080065// Deprecated: "IsDelta"
66static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080067static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
68static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
69// Deprecated: "ManifestSignatureRsa"
70// Deprecated: "ManifestSize"
71static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
72static const char* kTagMetadataSize = "MetadataSize";
73static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070074// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080075static const char* kTagPrompt = "Prompt";
David Zeuthen8f191b22013-08-06 12:27:50 -070076static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
77static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
David Zeuthene7f89172013-10-31 10:21:04 -070078static const char* kTagPublicKeyRsa = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080079
Alex Deymoac41a822015-09-15 20:52:53 -070080static const char* kOmahaUpdaterVersion = "0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +000081
Sen Jiang42fa45e2018-03-12 11:02:14 -070082// X-Goog-Update headers.
83static const char* kXGoogleUpdateInteractivity = "X-Goog-Update-Interactivity";
84static const char* kXGoogleUpdateAppId = "X-Goog-Update-AppId";
85static const char* kXGoogleUpdateUpdater = "X-Goog-Update-Updater";
Alex Deymo14ad88e2016-06-29 12:30:14 -070086
Alex Deymob3fa53b2016-04-18 19:57:58 -070087// updatecheck attributes (without the underscore prefix).
88static const char* kEolAttr = "eol";
89
Alex Deymoac41a822015-09-15 20:52:53 -070090namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +000091
Darin Petkov1cbd78f2010-07-29 12:38:34 -070092// Returns an XML ping element attribute assignment with attribute
93// |name| and value |ping_days| if |ping_days| has a value that needs
94// to be sent, or an empty string otherwise.
95string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -070096 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -070097 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -070098 return "";
99}
100
101// Returns an XML ping element if any of the elapsed days need to be
102// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700103string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700104 string ping_active = GetPingAttribute("a", ping_active_days);
105 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
106 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700107 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700108 ping_active.c_str(),
109 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700110 }
111 return "";
112}
113
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700114// Returns an XML that goes into the body of the <app> element of the Omaha
115// request based on the given parameters.
116string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700117 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700118 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700119 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700120 int ping_active_days,
121 int ping_roll_call_days,
122 PrefsInterface* prefs) {
123 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700124 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700125 if (include_ping)
126 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700127 if (!ping_only) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700128 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700129 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700130 "></updatecheck>\n",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700131 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700132
Darin Petkov265f2902011-05-09 15:17:40 -0700133 // If this is the first update check after a reboot following a previous
134 // update, generate an event containing the previous version number. If
135 // the previous version preference file doesn't exist the event is still
136 // generated with a previous version of 0.0.0.0 -- this is relevant for
137 // older clients or new installs. The previous version event is not sent
138 // for ping-only requests because they come before the client has
Alex Deymo87c08862015-10-30 21:56:55 -0700139 // rebooted. The previous version event is also not sent if it was already
140 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700141 string prev_version;
142 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
143 prev_version = "0.0.0.0";
144 }
Alex Deymo87c08862015-10-30 21:56:55 -0700145 // We only store a non-empty previous version value after a successful
146 // update in the previous boot. After reporting it back to the server,
147 // we clear the previous version value so it doesn't get reported again.
148 if (!prev_version.empty()) {
149 app_body += base::StringPrintf(
150 " <event eventtype=\"%d\" eventresult=\"%d\" "
151 "previousversion=\"%s\"></event>\n",
Alex Deymo9fded1e2015-11-05 12:31:19 -0800152 OmahaEvent::kTypeRebootedAfterUpdate,
153 OmahaEvent::kResultSuccess,
Alex Deymo87c08862015-10-30 21:56:55 -0700154 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
155 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
156 << "Unable to reset the previous version.";
157 }
Darin Petkov95508da2011-01-05 12:42:29 -0800158 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700159 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800160 // The error code is an optional attribute so append it only if the result
161 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700162 string error_code;
163 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700164 error_code = base::StringPrintf(" errorcode=\"%d\"",
165 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700166 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700167 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700168 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700169 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700170 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700171
172 return app_body;
173}
174
Alex Deymo8e18f932015-03-27 16:16:59 -0700175// Returns the cohort* argument to include in the <app> tag for the passed
176// |arg_name| and |prefs_key|, if any. The return value is suitable to
177// concatenate to the list of arguments and includes a space at the end.
178string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700179 const string arg_name,
180 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700181 // There's nothing wrong with not having a given cohort setting, so we check
182 // existance first to avoid the warning log message.
183 if (!prefs->Exists(prefs_key))
184 return "";
185 string cohort_value;
186 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
187 return "";
188 // This is a sanity check to avoid sending a huge XML file back to Ohama due
189 // to a compromised stateful partition making the update check fail in low
190 // network environments envent after a reboot.
191 if (cohort_value.size() > 1024) {
192 LOG(WARNING) << "The omaha cohort setting " << arg_name
193 << " has a too big value, which must be an error or an "
194 "attacker trying to inhibit updates.";
195 return "";
196 }
197
Alex Deymob0d74eb2015-03-30 17:59:17 -0700198 string escaped_xml_value;
199 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
200 LOG(WARNING) << "The omaha cohort setting " << arg_name
201 << " is ASCII-7 invalid, ignoring it.";
202 return "";
203 }
204
Alex Deymo8e18f932015-03-27 16:16:59 -0700205 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700206 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700207}
208
Sen Jiang94a4dec2017-03-28 18:23:35 -0700209struct OmahaAppData {
210 string id;
211 string version;
Sen Jiang684c9cd2017-10-17 16:26:45 -0700212 string product_components;
Sen Jiang94a4dec2017-03-28 18:23:35 -0700213};
214
Sen Jiang684c9cd2017-10-17 16:26:45 -0700215bool IsValidComponentID(const string& id) {
216 for (char c : id) {
217 if (!isalnum(c) && c != '-' && c != '_' && c != '.')
218 return false;
219 }
220 return true;
221}
222
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700223// Returns an XML that corresponds to the entire <app> node of the Omaha
224// request based on the given parameters.
225string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700226 OmahaRequestParams* params,
Sen Jiang94a4dec2017-03-28 18:23:35 -0700227 const OmahaAppData& app_data,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700228 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700229 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700230 int ping_active_days,
231 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800232 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700233 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700234 string app_body = GetAppBody(event, params, ping_only, include_ping,
235 ping_active_days, ping_roll_call_days,
236 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700237 string app_versions;
238
Sen Jiang8cd42342018-01-31 12:06:59 -0800239 // If we are downgrading to a more stable channel and we are allowed to do
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700240 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
241 // highest-versioned payload on the destination channel.
Sen Jiang8500d3a2018-02-08 12:04:05 -0800242 if (params->ShouldPowerwash()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700243 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
244 << "on downgrading to the version in the more stable channel";
245 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700246 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700247 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700248 app_versions = "version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700249 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700250 }
251
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700252 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700253 string app_channels =
254 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
255 if (params->current_channel() != download_channel) {
256 app_channels += "from_track=\"" + XmlEncodeWithDefault(
257 params->current_channel(), "") + "\" ";
258 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700259
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700260 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700261
David Zeuthen639aa362014-02-03 16:23:44 -0800262 // If install_date_days is not set (e.g. its value is -1 ), don't
263 // include the attribute.
264 string install_date_in_days_str = "";
265 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700266 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
267 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800268 }
269
Alex Deymo8e18f932015-03-27 16:16:59 -0700270 string app_cohort_args;
271 app_cohort_args += GetCohortArgXml(system_state->prefs(),
272 "cohort", kPrefsOmahaCohort);
273 app_cohort_args += GetCohortArgXml(system_state->prefs(),
274 "cohorthint", kPrefsOmahaCohortHint);
275 app_cohort_args += GetCohortArgXml(system_state->prefs(),
276 "cohortname", kPrefsOmahaCohortName);
277
Alex Deymoebf6e122017-03-10 16:12:01 -0800278 string fingerprint_arg;
279 if (!params->os_build_fingerprint().empty()) {
Sen Jiang8cd42342018-01-31 12:06:59 -0800280 fingerprint_arg = "fingerprint=\"" +
281 XmlEncodeWithDefault(params->os_build_fingerprint(), "") +
282 "\" ";
Alex Deymoebf6e122017-03-10 16:12:01 -0800283 }
284
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700285 string buildtype_arg;
286 if (!params->os_build_type().empty()) {
287 buildtype_arg = "os_build_type=\"" +
288 XmlEncodeWithDefault(params->os_build_type(), "") + "\" ";
289 }
290
Sen Jiang684c9cd2017-10-17 16:26:45 -0700291 string product_components_args;
Sen Jiang8500d3a2018-02-08 12:04:05 -0800292 if (!params->ShouldPowerwash() && !app_data.product_components.empty()) {
Sen Jiang684c9cd2017-10-17 16:26:45 -0700293 brillo::KeyValueStore store;
294 if (store.LoadFromString(app_data.product_components)) {
295 for (const string& key : store.GetKeys()) {
296 if (!IsValidComponentID(key)) {
297 LOG(ERROR) << "Invalid component id: " << key;
298 continue;
299 }
300 string version;
301 if (!store.GetString(key, &version)) {
302 LOG(ERROR) << "Failed to get version for " << key
303 << " in product_components.";
304 continue;
305 }
306 product_components_args +=
307 base::StringPrintf("_%s.version=\"%s\" ",
308 key.c_str(),
309 XmlEncodeWithDefault(version, "").c_str());
310 }
311 } else {
312 LOG(ERROR) << "Failed to parse product_components:\n"
313 << app_data.product_components;
314 }
315 }
316
317 // clang-format off
Alex Deymob0d74eb2015-03-30 17:59:17 -0700318 string app_xml = " <app "
Sen Jiang94a4dec2017-03-28 18:23:35 -0700319 "appid=\"" + XmlEncodeWithDefault(app_data.id, "") + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700320 app_cohort_args +
321 app_versions +
322 app_channels +
Sen Jiang684c9cd2017-10-17 16:26:45 -0700323 product_components_args +
Alex Deymoebf6e122017-03-10 16:12:01 -0800324 fingerprint_arg +
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700325 buildtype_arg +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700326 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
327 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
328 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
329 "delta_okay=\"" + delta_okay_str + "\" "
330 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
331 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
332 install_date_in_days_str +
333 ">\n" +
334 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700335 " </app>\n";
Sen Jiang684c9cd2017-10-17 16:26:45 -0700336 // clang-format on
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700337 return app_xml;
338}
339
340// Returns an XML that corresponds to the entire <os> node of the Omaha
341// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700342string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700343 string os_xml =" <os "
344 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
345 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
346 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
347 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700348 return os_xml;
349}
350
351// Returns an XML that corresponds to the entire Omaha request based on the
352// given parameters.
353string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700354 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700355 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700356 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700357 int ping_active_days,
358 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800359 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700360 SystemState* system_state) {
361 string os_xml = GetOsXml(params);
Sen Jiang684c9cd2017-10-17 16:26:45 -0700362 OmahaAppData product_app = {
363 .id = params->GetAppId(),
364 .version = params->app_version(),
365 .product_components = params->product_components()};
Sen Jiang94a4dec2017-03-28 18:23:35 -0700366 string app_xml = GetAppXml(event,
367 params,
368 product_app,
369 ping_only,
370 include_ping,
371 ping_active_days,
372 ping_roll_call_days,
373 install_date_in_days,
374 system_state);
375 if (!params->system_app_id().empty()) {
376 OmahaAppData system_app = {.id = params->system_app_id(),
377 .version = params->system_version()};
378 app_xml += GetAppXml(event,
379 params,
380 system_app,
381 ping_only,
382 include_ping,
383 ping_active_days,
384 ping_roll_call_days,
385 install_date_in_days,
386 system_state);
387 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700388
Alex Vakulenko75039d72014-03-25 12:36:28 -0700389 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700390 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700391
Alex Deymoac41a822015-09-15 20:52:53 -0700392 string updater_version = XmlEncodeWithDefault(
393 base::StringPrintf("%s-%s",
394 constants::kOmahaUpdaterID,
395 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700396 string request_xml =
397 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700398 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700399 "version=\"" + updater_version + "\" "
400 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700401 install_source +
402 "ismachine=\"1\">\n") +
403 os_xml +
404 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700405 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700406
407 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000408}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700409
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700410} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000411
David Zeuthene8ed8632014-07-24 13:38:10 -0400412// Struct used for holding data obtained when parsing the XML.
413struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400414 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
415
416 // Pointer to the expat XML_Parser object.
417 XML_Parser xml_parser;
418
David Zeuthene8ed8632014-07-24 13:38:10 -0400419 // This is the state of the parser as it's processing the XML.
420 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400421 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400422 string current_path;
423
424 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400425 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700426 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400427 string daystart_elapsed_days;
428 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800429
Sen Jiang81259682017-03-30 15:11:30 -0700430 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700431 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700432 vector<string> url_codebase;
433 string manifest_version;
434 map<string, string> action_postinstall_attrs;
435 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700436 string cohort;
437 string cohorthint;
438 string cohortname;
439 bool cohort_set = false;
440 bool cohorthint_set = false;
441 bool cohortname_set = false;
Sen Jiang81259682017-03-30 15:11:30 -0700442
443 struct Package {
444 string name;
445 string size;
446 string hash;
447 };
448 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800449 };
Sen Jiang81259682017-03-30 15:11:30 -0700450 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400451};
452
453namespace {
454
455// Callback function invoked by expat.
456void ParserHandlerStart(void* user_data, const XML_Char* element,
457 const XML_Char** attr) {
458 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
459
460 if (data->failed)
461 return;
462
463 data->current_path += string("/") + element;
464
465 map<string, string> attrs;
466 if (attr != nullptr) {
467 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
468 string key = attr[n];
469 string value = attr[n + 1];
470 attrs[key] = value;
471 }
472 }
473
Alex Deymo8e18f932015-03-27 16:16:59 -0700474 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700475 OmahaParserData::App app;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700476 if (attrs.find("appid") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700477 app.id = attrs["appid"];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700478 }
Alex Deymo8e18f932015-03-27 16:16:59 -0700479 if (attrs.find("cohort") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700480 app.cohort_set = true;
481 app.cohort = attrs["cohort"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700482 }
483 if (attrs.find("cohorthint") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700484 app.cohorthint_set = true;
485 app.cohorthint = attrs["cohorthint"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700486 }
487 if (attrs.find("cohortname") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700488 app.cohortname_set = true;
489 app.cohortname = attrs["cohortname"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700490 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700491 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700492 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700493 if (!data->apps.empty())
494 data->apps.back().updatecheck_status = attrs["status"];
495 if (data->updatecheck_poll_interval.empty())
496 data->updatecheck_poll_interval = attrs["PollInterval"];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700497 // Omaha sends arbitrary key-value pairs as extra attributes starting with
498 // an underscore.
499 for (const auto& attr : attrs) {
500 if (!attr.first.empty() && attr.first[0] == '_')
501 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
502 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400503 } else if (data->current_path == "/response/daystart") {
504 // Get the install-date.
505 data->daystart_elapsed_days = attrs["elapsed_days"];
506 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
507 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
508 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700509 if (!data->apps.empty())
510 data->apps.back().url_codebase.push_back(attrs["codebase"]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800511 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400512 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800513 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700514 if (!data->apps.empty())
515 data->apps.back().packages.push_back({.name = attrs["name"],
516 .size = attrs["size"],
517 .hash = attrs["hash_sha256"]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400518 } else if (data->current_path == "/response/app/updatecheck/manifest") {
519 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700520 if (!data->apps.empty())
521 data->apps.back().manifest_version = attrs[kTagVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400522 } else if (data->current_path ==
523 "/response/app/updatecheck/manifest/actions/action") {
524 // We only care about the postinstall action.
Sen Jiang81259682017-03-30 15:11:30 -0700525 if (attrs["event"] == "postinstall" && !data->apps.empty()) {
526 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400527 }
528 }
529}
530
531// Callback function invoked by expat.
532void ParserHandlerEnd(void* user_data, const XML_Char* element) {
533 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
534 if (data->failed)
535 return;
536
537 const string path_suffix = string("/") + element;
538
Alex Vakulenko0103c362016-01-20 07:56:15 -0800539 if (!base::EndsWith(data->current_path, path_suffix,
540 base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400541 LOG(ERROR) << "Unexpected end element '" << element
542 << "' with current_path='" << data->current_path << "'";
543 data->failed = true;
544 return;
545 }
546 data->current_path.resize(data->current_path.size() - path_suffix.size());
547}
548
David Zeuthenf3e28012014-08-26 18:23:52 -0400549// Callback function invoked by expat.
550//
551// This is called for entity declarations. Since Omaha is guaranteed
552// to never return any XML with entities our course of action is to
553// just stop parsing. This avoids potential resource exhaustion
554// problems AKA the "billion laughs". CVE-2013-0340.
555void ParserHandlerEntityDecl(void *user_data,
556 const XML_Char *entity_name,
557 int is_parameter_entity,
558 const XML_Char *value,
559 int value_length,
560 const XML_Char *base,
561 const XML_Char *system_id,
562 const XML_Char *public_id,
563 const XML_Char *notation_name) {
564 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
565
566 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
567 data->failed = true;
568 data->entity_decl = true;
569 XML_StopParser(data->xml_parser, false);
570}
571
David Zeuthene8ed8632014-07-24 13:38:10 -0400572} // namespace
573
Alex Deymob0d74eb2015-03-30 17:59:17 -0700574bool XmlEncode(const string& input, string* output) {
575 if (std::find_if(input.begin(), input.end(),
576 [](const char c){return c & 0x80;}) != input.end()) {
577 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
578 utils::HexDumpString(input);
579 return false;
580 }
Alex Deymocc457852015-06-18 18:35:50 -0700581 output->clear();
582 // We need at least input.size() space in the output, but the code below will
583 // handle it if we need more.
584 output->reserve(input.size());
585 for (char c : input) {
586 switch (c) {
587 case '\"':
588 output->append("&quot;");
589 break;
590 case '\'':
591 output->append("&apos;");
592 break;
593 case '&':
594 output->append("&amp;");
595 break;
596 case '<':
597 output->append("&lt;");
598 break;
599 case '>':
600 output->append("&gt;");
601 break;
602 default:
603 output->push_back(c);
604 }
605 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700606 return true;
607}
608
609string XmlEncodeWithDefault(const string& input, const string& default_value) {
610 string output;
611 if (XmlEncode(input, &output))
612 return output;
613 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000614}
615
Alex Deymoc1c17b42015-11-23 03:53:15 -0300616OmahaRequestAction::OmahaRequestAction(
617 SystemState* system_state,
618 OmahaEvent* event,
619 std::unique_ptr<HttpFetcher> http_fetcher,
620 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800621 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700622 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300623 http_fetcher_(std::move(http_fetcher)),
Thieu Le116fda32011-04-19 11:01:54 -0700624 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700625 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700626 ping_roll_call_days_(0) {
627 params_ = system_state->request_params();
628}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000629
Darin Petkov6a5b3222010-07-13 14:55:28 -0700630OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000631
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700632// Calculates the value to use for the ping days parameter.
633int OmahaRequestAction::CalculatePingDays(const string& key) {
634 int days = kNeverPinged;
635 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800636 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700637 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
638 if (days < 0) {
639 // If |days| is negative, then the system clock must have jumped
640 // back in time since the ping was sent. Mark the value so that
641 // it doesn't get sent to the server but we still update the
642 // last ping daystart preference. This way the next ping time
643 // will be correct, hopefully.
644 days = kPingTimeJump;
645 LOG(WARNING) <<
646 "System clock jumped back in time. Resetting ping daystarts.";
647 }
648 }
649 return days;
650}
651
652void OmahaRequestAction::InitPingDays() {
653 // We send pings only along with update checks, not with events.
654 if (IsEvent()) {
655 return;
656 }
657 // TODO(petkov): Figure a way to distinguish active use pings
658 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700659 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700660 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
661 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
662}
663
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700664bool OmahaRequestAction::ShouldPing() const {
665 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
666 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
667 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
668 if (powerwash_count > 0) {
669 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
670 << "powerwash_count is " << powerwash_count;
671 return false;
672 }
Amin Hassani1677e812017-06-21 13:36:36 -0700673 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
674 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
675 << "the first_active_omaha_ping_sent is true";
676 return false;
677 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700678 return true;
679 }
680 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
681}
682
David Zeuthen639aa362014-02-03 16:23:44 -0800683// static
684int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
685 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700686 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800687 return -1;
688
689 // If we have the value stored on disk, just return it.
690 int64_t stored_value;
691 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
692 // Convert and sanity-check.
693 int install_date_days = static_cast<int>(stored_value);
694 if (install_date_days >= 0)
695 return install_date_days;
696 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
697 << install_date_days << " looks suspicious.";
698 prefs->Delete(kPrefsInstallDateDays);
699 }
700
701 // Otherwise, if OOBE is not complete then do nothing and wait for
702 // ParseResponse() to call ParseInstallDate() and then
703 // PersistInstallDate() to set the kPrefsInstallDateDays state
704 // variable. Once that is done, we'll then report back in future
705 // Omaha requests. This works exactly because OOBE triggers an
706 // update check.
707 //
708 // However, if OOBE is complete and the kPrefsInstallDateDays state
709 // variable is not set, there are two possibilities
710 //
711 // 1. The update check in OOBE failed so we never got a response
712 // from Omaha (no network etc.); or
713 //
714 // 2. OOBE was done on an older version that didn't write to the
715 // kPrefsInstallDateDays state variable.
716 //
717 // In both cases, we approximate the install date by simply
718 // inspecting the timestamp of when OOBE happened.
719
720 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700721 if (!system_state->hardware()->IsOOBEEnabled() ||
722 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800723 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700724 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800725 return -1;
726 }
727
728 int num_days;
729 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
730 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
731 << "as its value '" << utils::ToString(time_of_oobe)
732 << "' looks suspicious.";
733 return -1;
734 }
735
736 // Persist this to disk, for future use.
737 if (!OmahaRequestAction::PersistInstallDate(system_state,
738 num_days,
739 kProvisionedFromOOBEMarker))
740 return -1;
741
742 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
743 << num_days << " days";
744
745 return num_days;
746}
747
Darin Petkov6a5b3222010-07-13 14:55:28 -0700748void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000749 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700750 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700751 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700752 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700753 return;
754 }
David Zeuthen639aa362014-02-03 16:23:44 -0800755
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700756 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700757 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700758 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700759 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700760 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800761 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800762 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700763 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700764
Sen Jiang42fa45e2018-03-12 11:02:14 -0700765 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700766 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
767 params_->interactive() ? "fg" : "bg");
768 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
769 http_fetcher_->SetHeader(
770 kXGoogleUpdateUpdater,
771 base::StringPrintf(
772 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
773
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800774 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
775 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700776 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700777 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700778 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000779}
780
Darin Petkov6a5b3222010-07-13 14:55:28 -0700781void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000782 http_fetcher_->TerminateTransfer();
783}
784
785// We just store the response in the buffer. Once we've received all bytes,
786// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700787void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800788 const void* bytes,
789 size_t length) {
790 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
791 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000792}
793
794namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000795
796// Parses a 64 bit base-10 int from a string and returns it. Returns 0
797// on error. If the string contains "0", that's indistinguishable from
798// error.
799off_t ParseInt(const string& str) {
800 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700801 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000802 if (rc < 1) {
803 // failure
804 return 0;
805 }
806 return ret;
807}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700808
David Zeuthene8ed8632014-07-24 13:38:10 -0400809// Parses |str| and returns |true| if, and only if, its value is "true".
810bool ParseBool(const string& str) {
811 return str == "true";
812}
813
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700814// Update the last ping day preferences based on the server daystart
815// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400816bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700817 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400818 TEST_AND_RETURN_FALSE(
819 base::StringToInt64(parser_data->daystart_elapsed_seconds,
820 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700821 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
822
823 // Remember the local time that matches the server's last midnight
824 // time.
825 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
826 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
827 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
828 return true;
829}
Sen Jiang81259682017-03-30 15:11:30 -0700830
831// Parses the package node in the given XML document and populates
832// |output_object| if valid. Returns true if we should continue the parsing.
833// False otherwise, in which case it sets any error code using |completer|.
834bool ParsePackage(OmahaParserData::App* app,
835 OmahaResponse* output_object,
836 ScopedActionCompleter* completer) {
837 if (app->updatecheck_status == "noupdate") {
838 if (!app->packages.empty()) {
839 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
840 completer->set_code(ErrorCode::kOmahaResponseInvalid);
841 return false;
842 }
843 return true;
844 }
845 if (app->packages.empty()) {
846 LOG(ERROR) << "Omaha Response has no packages";
847 completer->set_code(ErrorCode::kOmahaResponseInvalid);
848 return false;
849 }
850 if (app->url_codebase.empty()) {
851 LOG(ERROR) << "No Omaha Response URLs";
852 completer->set_code(ErrorCode::kOmahaResponseInvalid);
853 return false;
854 }
855 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
856 vector<string> metadata_sizes =
857 base::SplitString(app->action_postinstall_attrs[kTagMetadataSize],
858 ":",
859 base::TRIM_WHITESPACE,
860 base::SPLIT_WANT_ALL);
861 vector<string> metadata_signatures =
862 base::SplitString(app->action_postinstall_attrs[kTagMetadataSignatureRsa],
863 ":",
864 base::TRIM_WHITESPACE,
865 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700866 vector<string> is_delta_payloads =
867 base::SplitString(app->action_postinstall_attrs[kTagIsDeltaPayload],
868 ":",
869 base::TRIM_WHITESPACE,
870 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700871 for (size_t i = 0; i < app->packages.size(); i++) {
872 const auto& package = app->packages[i];
873 if (package.name.empty()) {
874 LOG(ERROR) << "Omaha Response has empty package name";
875 completer->set_code(ErrorCode::kOmahaResponseInvalid);
876 return false;
877 }
878 LOG(INFO) << "Found package " << package.name;
879
880 OmahaResponse::Package out_package;
881 for (const string& codebase : app->url_codebase) {
882 if (codebase.empty()) {
883 LOG(ERROR) << "Omaha Response URL has empty codebase";
884 completer->set_code(ErrorCode::kOmahaResponseInvalid);
885 return false;
886 }
887 out_package.payload_urls.push_back(codebase + package.name);
888 }
889 // Parse the payload size.
890 base::StringToUint64(package.size, &out_package.size);
891 if (out_package.size <= 0) {
892 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
893 completer->set_code(ErrorCode::kOmahaResponseInvalid);
894 return false;
895 }
896 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
897
898 if (i < metadata_sizes.size())
899 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
900 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
901 << " bytes";
902
903 if (i < metadata_signatures.size())
904 out_package.metadata_signature = metadata_signatures[i];
905 LOG(INFO) << "Payload metadata signature = "
906 << out_package.metadata_signature;
907
908 out_package.hash = package.hash;
909 if (out_package.hash.empty()) {
910 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
911 completer->set_code(ErrorCode::kOmahaResponseInvalid);
912 return false;
913 }
914 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700915
916 if (i < is_delta_payloads.size())
917 out_package.is_delta = ParseBool(is_delta_payloads[i]);
918 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
919
Sen Jiang81259682017-03-30 15:11:30 -0700920 output_object->packages.push_back(std::move(out_package));
921 }
922
923 return true;
924}
925
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700926} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000927
David Zeuthene8ed8632014-07-24 13:38:10 -0400928bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700929 OmahaResponse* output_object,
930 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700931 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700932 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700933 return false;
934 }
Sen Jiang81259682017-03-30 15:11:30 -0700935 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700936
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800937 // chromium-os:37289: The PollInterval is not supported by Omaha server
938 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700939 // slow down the request rate from the server-side. Note that the PollInterval
940 // is not persisted, so it has to be sent by the server on every response to
941 // guarantee that the scheduler uses this value (otherwise, if the device got
942 // rebooted after the last server-indicated value, it'll revert to the default
943 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
944 // based on the assumption that we perform an update check every hour so that
945 // the max value of 8 will roughly be equivalent to one work day. If we decide
946 // to use PollInterval permanently, we should update the
947 // max_update_checks_allowed to take PollInterval into account. Note: The
948 // parsing for PollInterval happens even before parsing of the status because
949 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400950 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700951 &output_object->poll_interval);
952
David Zeuthen639aa362014-02-03 16:23:44 -0800953 // Check for the "elapsed_days" attribute in the "daystart"
954 // element. This is the number of days since Jan 1 2007, 0:00
955 // PST. If we don't have a persisted value of the Omaha InstallDate,
956 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400957 if (ParseInstallDate(parser_data, output_object) &&
958 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800959 // Since output_object->install_date_days is never negative, the
960 // elapsed_days -> install-date calculation is reduced to simply
961 // rounding down to the nearest number divisible by 7.
962 int remainder = output_object->install_date_days % 7;
963 int install_date_days_rounded =
964 output_object->install_date_days - remainder;
965 if (PersistInstallDate(system_state_,
966 install_date_days_rounded,
967 kProvisionedFromOmahaResponse)) {
968 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
969 << install_date_days_rounded << " days";
970 }
971 }
972
Alex Deymo00d79ac2015-06-29 15:41:49 -0700973 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -0700974 for (const auto& app : parser_data->apps) {
975 if (app.id == params_->GetAppId()) {
976 if (app.cohort_set)
977 PersistCohortData(kPrefsOmahaCohort, app.cohort);
978 if (app.cohorthint_set)
979 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
980 if (app.cohortname_set)
981 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
982 break;
983 }
984 }
Alex Deymo00d79ac2015-06-29 15:41:49 -0700985
Alex Deymob3fa53b2016-04-18 19:57:58 -0700986 // Parse the updatecheck attributes.
987 PersistEolStatus(parser_data->updatecheck_attrs);
988
David Zeuthene8ed8632014-07-24 13:38:10 -0400989 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700990 return false;
991
David Zeuthene8ed8632014-07-24 13:38:10 -0400992 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700993 return false;
994
Sen Jiang0affc2c2017-02-10 15:55:05 -0800995 // Package has to be parsed after Params now because ParseParams need to make
996 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -0700997 for (auto& app : parser_data->apps)
998 if (!ParsePackage(&app, output_object, completer))
999 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001000
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001001 return true;
1002}
1003
David Zeuthene8ed8632014-07-24 13:38:10 -04001004bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001005 OmahaResponse* output_object,
1006 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001007 output_object->update_exists = false;
1008 for (size_t i = 0; i < parser_data->apps.size(); i++) {
1009 const string& status = parser_data->apps[i].updatecheck_status;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001010 if (status == "noupdate") {
1011 // Don't update if any app has status="noupdate".
Sen Jiang81259682017-03-30 15:11:30 -07001012 LOG(INFO) << "No update for <app> " << i;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001013 output_object->update_exists = false;
1014 break;
Sen Jiang81259682017-03-30 15:11:30 -07001015 } else if (status == "ok") {
Sen Jiang00adf7b2017-06-26 15:57:29 -07001016 if (parser_data->apps[i].action_postinstall_attrs["noupdate"] == "true") {
1017 // noupdate="true" in postinstall attributes means it's an update to
1018 // self, only update if there's at least one app really have update.
1019 LOG(INFO) << "Update to self for <app> " << i;
1020 } else {
1021 LOG(INFO) << "Update for <app> " << i;
1022 output_object->update_exists = true;
1023 }
Sen Jiang81259682017-03-30 15:11:30 -07001024 } else {
1025 LOG(ERROR) << "Unknown Omaha response status: " << status;
1026 completer->set_code(ErrorCode::kOmahaResponseInvalid);
1027 return false;
1028 }
1029 }
1030 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001031 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001032 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001033 }
1034
Sen Jiang81259682017-03-30 15:11:30 -07001035 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001036}
1037
David Zeuthene8ed8632014-07-24 13:38:10 -04001038bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001039 OmahaResponse* output_object,
1040 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001041 map<string, string> attrs;
1042 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001043 if (app.id == params_->GetAppId()) {
1044 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -07001045 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001046 } else if (!params_->system_app_id().empty() &&
1047 app.id == params_->system_app_id()) {
1048 // this is the system app (this check is intentionally skipped if there is
1049 // no system_app_id set)
1050 output_object->system_version = app.manifest_version;
1051 }
1052 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -07001053 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001054 }
Sen Jiang81259682017-03-30 15:11:30 -07001055 }
Chris Sosa3b748432013-06-20 16:42:59 -07001056 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -07001057 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001058 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -07001059 return false;
1060 }
1061
1062 LOG(INFO) << "Received omaha response to update to version "
1063 << output_object->version;
1064
David Zeuthene8ed8632014-07-24 13:38:10 -04001065 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001066 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001067 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001068 return false;
1069 }
1070
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001071 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -04001072 output_object->more_info_url = attrs[kTagMoreInfo];
David Zeuthene8ed8632014-07-24 13:38:10 -04001073 output_object->prompt = ParseBool(attrs[kTagPrompt]);
1074 output_object->deadline = attrs[kTagDeadline];
1075 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001076 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -04001077 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001078 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -04001079 ParseBool(attrs[kTagDisableP2PForSharing]);
1080 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001081
David Zeuthene8ed8632014-07-24 13:38:10 -04001082 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -08001083 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001084 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001085
Jay Srinivasan08262882012-12-28 19:29:43 -08001086 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -04001087 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -08001088
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001089 return true;
1090}
1091
David Zeuthene8ed8632014-07-24 13:38:10 -04001092// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +00001093// and fill in the appropriate fields of the output object. Also, notifies
1094// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -07001095void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
1096 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +00001097 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001098 string current_response(response_buffer_.begin(), response_buffer_.end());
1099 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001100
Gilad Arnold74b5f552014-10-07 08:17:16 -07001101 PayloadStateInterface* const payload_state = system_state_->payload_state();
1102
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001103 // Events are best effort transactions -- assume they always succeed.
1104 if (IsEvent()) {
1105 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001106 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001107 return;
1108 }
1109
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001110 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001111 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -07001112 int code = GetHTTPResponseCode();
1113 // Makes sure we send sane error values.
1114 if (code < 0 || code >= 1000) {
1115 code = 999;
1116 }
David Zeuthena99981f2013-04-29 13:42:47 -07001117 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001118 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +00001119 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001120 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001121
David Zeuthene8ed8632014-07-24 13:38:10 -04001122 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -04001123 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -04001124 XML_SetUserData(parser, &parser_data);
1125 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -04001126 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001127 XML_Status res = XML_Parse(
1128 parser,
1129 reinterpret_cast<const char*>(response_buffer_.data()),
1130 response_buffer_.size(),
1131 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -04001132 XML_ParserFree(parser);
1133
1134 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -07001135 LOG(ERROR) << "Omaha response not valid XML: "
1136 << XML_ErrorString(XML_GetErrorCode(parser))
1137 << " at line " << XML_GetCurrentLineNumber(parser)
1138 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -04001139 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
1140 if (response_buffer_.empty()) {
1141 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
1142 } else if (parser_data.entity_decl) {
1143 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
1144 }
1145 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001146 return;
1147 }
1148
Alex Deymoebbe7ef2014-10-30 13:02:49 -07001149 // Update the last ping day preferences based on the server daystart response
1150 // even if we didn't send a ping. Omaha always includes the daystart in the
1151 // response, but log the error if it didn't.
1152 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
1153 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -07001154
Amin Hassani1677e812017-06-21 13:36:36 -07001155 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
1156 // we have got a response from omaha and if its value has never been set to
1157 // true before. Failure of this function should be ignored. There should be no
1158 // need to check if a=-1 has been sent because older devices have already sent
1159 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
1160 // future checks.
1161 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
1162 system_state_->hardware()->SetFirstActiveOmahaPingSent();
1163 }
1164
Thieu Le116fda32011-04-19 11:01:54 -07001165 if (!HasOutputPipe()) {
1166 // Just set success to whether or not the http transfer succeeded,
1167 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001168 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001169 return;
1170 }
1171
Darin Petkov6a5b3222010-07-13 14:55:28 -07001172 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001173 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001174 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001175 output_object.update_exists = true;
1176 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001177
Tao Bao5688d162017-06-06 13:09:06 -07001178 if (ShouldIgnoreUpdate(output_object)) {
1179 output_object.update_exists = false;
1180 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001181 return;
1182 }
1183
David Zeuthen8f191b22013-08-06 12:27:50 -07001184 // If Omaha says to disable p2p, respect that
1185 if (output_object.disable_p2p_for_downloading) {
1186 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1187 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001188 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001189 }
1190 if (output_object.disable_p2p_for_sharing) {
1191 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1192 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001193 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001194 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001195
1196 // Update the payload state with the current response. The payload state
1197 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001198 // from what's stored already. We are updating the payload state as late
1199 // as possible in this method so that if a new release gets pushed and then
1200 // got pulled back due to some issues, we don't want to clear our internal
1201 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001202 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001203
David Zeuthen8f191b22013-08-06 12:27:50 -07001204 // It could be we've already exceeded the deadline for when p2p is
1205 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001206 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001207 payload_state->P2PNewAttempt();
1208 if (!payload_state->P2PAttemptAllowed()) {
1209 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1210 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001211 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001212 }
1213 }
1214
1215 // From here on, we'll complete stuff in CompleteProcessing() so
1216 // disable |completer| since we'll create a new one in that
1217 // function.
1218 completer.set_should_complete(false);
1219
1220 // If we're allowed to use p2p for downloading we do not pay
1221 // attention to wall-clock-based waiting if the URL is indeed
1222 // available via p2p. Therefore, check if the file is available via
1223 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001224 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001225 LookupPayloadViaP2P(output_object);
1226 } else {
1227 CompleteProcessing();
1228 }
1229}
1230
1231void OmahaRequestAction::CompleteProcessing() {
1232 ScopedActionCompleter completer(processor_, this);
1233 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1234 PayloadStateInterface* payload_state = system_state_->payload_state();
1235
Alex Deymo46a9aae2016-05-04 20:20:11 -07001236 if (system_state_->hardware()->IsOOBEEnabled() &&
1237 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
Kevin Cernekeec5081a82016-04-08 12:29:52 -07001238 output_object.deadline.empty() &&
1239 params_->app_version() != "ForcedUpdate") {
Kevin Cernekee2494e282016-03-29 18:03:53 -07001240 output_object.update_exists = false;
1241 LOG(INFO) << "Ignoring non-critical Omaha updates until OOBE is done.";
1242 completer.set_code(ErrorCode::kNonCriticalUpdateInOOBE);
1243 return;
1244 }
1245
David Zeuthen8f191b22013-08-06 12:27:50 -07001246 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001247 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001248 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001249 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001250 return;
1251 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001252
Chris Sosa20f005c2013-09-05 13:53:08 -07001253 if (payload_state->ShouldBackoffDownload()) {
1254 output_object.update_exists = false;
1255 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1256 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001257 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001258 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001259 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001260 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001261}
1262
1263void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1264 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1265 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001266 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001267 } else {
1268 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1269 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001270 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001271 }
1272 CompleteProcessing();
1273}
1274
1275void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001276 // If the device is in the middle of an update, the state variables
1277 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1278 // tracks the offset and length of the operation currently in
1279 // progress. The offset is based from the end of the manifest which
1280 // is kPrefsManifestMetadataSize bytes long.
1281 //
1282 // To make forward progress and avoid deadlocks, we need to find a
1283 // peer that has at least the entire operation we're currently
1284 // working on. Otherwise we may end up in a situation where two
1285 // devices bounce back and forth downloading from each other,
1286 // neither making any forward progress until one of them decides to
1287 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1288 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001289 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001290 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001291 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001292 int64_t next_data_offset = 0;
1293 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001294 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001295 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1296 &manifest_metadata_size) &&
1297 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001298 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1299 &manifest_signature_size) &&
1300 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001301 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001302 &next_data_offset) &&
1303 next_data_offset != -1 &&
1304 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1305 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001306 minimum_size = manifest_metadata_size + manifest_signature_size +
1307 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001308 }
1309
Sen Jiang0affc2c2017-02-10 15:55:05 -08001310 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001311 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001312 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001313 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001314 string file_id =
1315 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001316 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001317 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1318 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001319 system_state_->p2p_manager()->LookupUrlForFile(
1320 file_id,
1321 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001322 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001323 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1324 base::Unretained(this)));
1325 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001326}
1327
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001328bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001329 if (params_->interactive()) {
1330 LOG(INFO) << "Not deferring download because update is interactive.";
1331 return false;
1332 }
1333
David Zeuthen8f191b22013-08-06 12:27:50 -07001334 // If we're using p2p to download _and_ we have a p2p URL, we never
1335 // defer the download. This is because the download will always
1336 // happen from a peer on the LAN and we've been waiting in line for
1337 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001338 const PayloadStateInterface* payload_state = system_state_->payload_state();
1339 if (payload_state->GetUsingP2PForDownloading() &&
1340 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001341 LOG(INFO) << "Download not deferred because download "
1342 << "will happen from a local peer (via p2p).";
1343 return false;
1344 }
1345
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001346 // We should defer the downloads only if we've first satisfied the
1347 // wall-clock-based-waiting period and then the update-check-based waiting
1348 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001349 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001350 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1351 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001352 return false;
1353 }
1354
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001355 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001356 case kWallClockWaitNotSatisfied:
1357 // We haven't even satisfied the first condition, passing the
1358 // wall-clock-based waiting period, so we should defer the downloads
1359 // until that happens.
1360 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1361 return true;
1362
1363 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1364 LOG(INFO) << "wall-clock-based-wait satisfied and "
1365 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001366 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001367
1368 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1369 // Wall-clock-based waiting period is satisfied, and it's determined
1370 // that we do not need the update-check-based wait. so no need to
1371 // defer downloads.
1372 LOG(INFO) << "wall-clock-based-wait satisfied and "
1373 << "update-check-based-wait is not required.";
1374 return false;
1375
1376 default:
1377 // Returning false for this default case so we err on the
1378 // side of downloading updates than deferring in case of any bugs.
1379 NOTREACHED();
1380 return false;
1381 }
1382}
1383
1384OmahaRequestAction::WallClockWaitResult
1385OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001386 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001387 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001388 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001389
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001390 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1391 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1392 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001393 // Note: This timestamp could be that of ANY update we saw in the past
1394 // (not necessarily this particular update we're considering to apply)
1395 // but never got to apply because of some reason (e.g. stop AU policy,
1396 // updates being pulled out from Omaha, changes in target version prefix,
1397 // new update being rolled out, etc.). But for the purposes of scattering
1398 // it doesn't matter which update the timestamp corresponds to. i.e.
1399 // the clock starts ticking the first time we see an update and we're
1400 // ready to apply when the random wait period is satisfied relative to
1401 // that first seen timestamp.
1402 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1403 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1404 << utils::ToString(update_first_seen_at);
1405 } else {
1406 // This seems like an unexpected error where the persisted value exists
1407 // but it's not readable for some reason. Just skip scattering in this
1408 // case to be safe.
1409 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1410 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1411 }
1412 } else {
Sen Jiang7c1171e2016-06-23 11:35:40 -07001413 update_first_seen_at = system_state_->clock()->GetWallclockTime();
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001414 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001415 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1416 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001417 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1418 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001419 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001420 // This seems like an unexpected error where the value cannot be
1421 // persisted for some reason. Just skip scattering in this
1422 // case to be safe.
1423 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1424 << utils::ToString(update_first_seen_at)
1425 << " cannot be persisted";
1426 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1427 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001428 }
1429
Sen Jiang7c1171e2016-06-23 11:35:40 -07001430 TimeDelta elapsed_time =
1431 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1432 TimeDelta max_scatter_period =
1433 TimeDelta::FromDays(output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001434
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001435 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001436 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001437 << ", Time Elapsed = "
1438 << utils::FormatSecs(elapsed_time.InSeconds())
1439 << ", MaxDaysToScatter = "
1440 << max_scatter_period.InDays();
1441
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001442 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001443 // The deadline is set for all rules which serve a delta update from a
1444 // previous FSI, which means this update will be applied mostly in OOBE
1445 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1446 // quickly.
1447 LOG(INFO) << "Not scattering as deadline flag is set";
1448 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1449 }
1450
1451 if (max_scatter_period.InDays() == 0) {
1452 // This means the Omaha rule creator decides that this rule
1453 // should not be scattered irrespective of the policy.
1454 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1455 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1456 }
1457
1458 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001459 // This means we've waited more than the upperbound wait in the rule
1460 // from the time we first saw a valid update available to us.
1461 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001462 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1463 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1464 }
1465
1466 // This means we are required to participate in scattering.
1467 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001468 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001469 if (remaining_wait_time.InSeconds() <= 0) {
1470 // Yes, it's our turn now.
1471 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1472
1473 // But we can't download until the update-check-count-based wait is also
1474 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001475 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001476 kWallClockWaitDoneButUpdateCheckWaitRequired :
1477 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1478 }
1479
1480 // Not our turn yet, so we have to wait until our turn to
1481 // help scatter the downloads across all clients of the enterprise.
1482 LOG(INFO) << "Update deferred for another "
1483 << utils::FormatSecs(remaining_wait_time.InSeconds())
1484 << " per policy.";
1485 return kWallClockWaitNotSatisfied;
1486}
1487
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001488bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001489 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001490
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001491 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1492 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1493 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001494 // We are unable to read the update check count from file for some reason.
1495 // So let's proceed anyway so as to not stall the update.
1496 LOG(ERROR) << "Unable to read update check count. "
1497 << "Skipping update-check-count-based-wait.";
1498 return true;
1499 }
1500 } else {
1501 // This file does not exist. This means we haven't started our update
1502 // check count down yet, so this is the right time to start the count down.
1503 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001504 params_->min_update_checks_needed(),
1505 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001506
1507 LOG(INFO) << "Randomly picked update check count value = "
1508 << update_check_count_value;
1509
1510 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001511 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1512 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001513 // We weren't able to write the update check count file for some reason.
1514 // So let's proceed anyway so as to not stall the update.
1515 LOG(ERROR) << "Unable to write update check count. "
1516 << "Skipping update-check-count-based-wait.";
1517 return true;
1518 }
1519 }
1520
1521 if (update_check_count_value == 0) {
1522 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1523 return true;
1524 }
1525
1526 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001527 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001528 // We err on the side of skipping scattering logic instead of stalling
1529 // a machine from receiving any updates in case of any unexpected state.
1530 LOG(ERROR) << "Invalid value for update check count detected. "
1531 << "Skipping update-check-count-based-wait.";
1532 return true;
1533 }
1534
1535 // Legal value, we need to wait for more update checks to happen
1536 // until this becomes 0.
1537 LOG(INFO) << "Deferring Omaha updates for another "
1538 << update_check_count_value
1539 << " update checks per policy";
1540 return false;
1541}
1542
David Zeuthen639aa362014-02-03 16:23:44 -08001543// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001544bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001545 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001546 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001547 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001548 &elapsed_days))
1549 return false;
1550
1551 if (elapsed_days < 0)
1552 return false;
1553
1554 output_object->install_date_days = elapsed_days;
1555 return true;
1556}
1557
1558// static
1559bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1560 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001561 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001562 return false;
1563
1564 return prefs->Exists(kPrefsInstallDateDays);
1565}
1566
1567// static
1568bool OmahaRequestAction::PersistInstallDate(
1569 SystemState *system_state,
1570 int install_date_days,
1571 InstallDateProvisioningSource source) {
1572 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1573
1574 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001575 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001576 return false;
1577
1578 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1579 return false;
1580
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001581 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001582 static_cast<int>(source), // Sample.
1583 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001584 return true;
1585}
1586
Alex Deymo8e18f932015-03-27 16:16:59 -07001587bool OmahaRequestAction::PersistCohortData(
1588 const string& prefs_key,
1589 const string& new_value) {
1590 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1591 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1592 return system_state_->prefs()->Delete(prefs_key);
1593 } else if (!new_value.empty()) {
1594 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1595 return system_state_->prefs()->SetString(prefs_key, new_value);
1596 }
1597 return true;
1598}
1599
Alex Deymob3fa53b2016-04-18 19:57:58 -07001600bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
1601 auto eol_attr = attrs.find(kEolAttr);
1602 if (eol_attr != attrs.end()) {
1603 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1604 eol_attr->second);
1605 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1606 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1607 }
1608 return true;
1609}
1610
David Zeuthen33bae492014-02-25 16:16:18 -08001611void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1612 // We only want to report this on "update check".
1613 if (ping_only_ || event_ != nullptr)
1614 return;
1615
1616 metrics::CheckResult result = metrics::CheckResult::kUnset;
1617 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1618 metrics::DownloadErrorCode download_error_code =
1619 metrics::DownloadErrorCode::kUnset;
1620
1621 // Regular update attempt.
1622 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001623 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001624 // OK, we parsed the response successfully but that does
1625 // necessarily mean that an update is available.
1626 if (HasOutputPipe()) {
1627 const OmahaResponse& response = GetOutputObject();
1628 if (response.update_exists) {
1629 result = metrics::CheckResult::kUpdateAvailable;
1630 reaction = metrics::CheckReaction::kUpdating;
1631 } else {
1632 result = metrics::CheckResult::kNoUpdateAvailable;
1633 }
1634 } else {
1635 result = metrics::CheckResult::kNoUpdateAvailable;
1636 }
1637 break;
1638
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001639 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001640 result = metrics::CheckResult::kUpdateAvailable;
1641 reaction = metrics::CheckReaction::kIgnored;
1642 break;
1643
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001644 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001645 result = metrics::CheckResult::kUpdateAvailable;
1646 reaction = metrics::CheckReaction::kDeferring;
1647 break;
1648
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001649 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001650 result = metrics::CheckResult::kUpdateAvailable;
1651 reaction = metrics::CheckReaction::kBackingOff;
1652 break;
1653
1654 default:
1655 // We report two flavors of errors, "Download errors" and "Parsing
1656 // error". Try to convert to the former and if that doesn't work
1657 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001658 metrics::DownloadErrorCode tmp_error =
1659 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001660 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1661 result = metrics::CheckResult::kDownloadError;
1662 download_error_code = tmp_error;
1663 } else {
1664 result = metrics::CheckResult::kParsingError;
1665 }
1666 break;
1667 }
1668
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001669 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1670 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001671}
1672
Chris Sosa77f79e82014-06-02 18:16:24 -07001673bool OmahaRequestAction::ShouldIgnoreUpdate(
Tao Bao5688d162017-06-06 13:09:06 -07001674 const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001675 // Note: policy decision to not update to a version we rolled back from.
1676 string rollback_version =
1677 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001678 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001679 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001680 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001681 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1682 return true;
1683 }
1684 }
1685
Tao Bao5688d162017-06-06 13:09:06 -07001686 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001687 LOG(INFO) << "Update is not allowed over current connection.";
1688 return true;
1689 }
1690
1691 // Note: We could technically delete the UpdateFirstSeenAt state when we
1692 // return true. If we do, it'll mean a device has to restart the
1693 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1694 // turned on again. On the other hand, it also increases the chance of update
1695 // starvation if an admin turns AU on/off more frequently. We choose to err on
1696 // the side of preventing starvation at the cost of not applying scattering in
1697 // those cases.
1698 return false;
1699}
1700
Tao Bao5688d162017-06-06 13:09:06 -07001701bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001702 ConnectionType type;
1703 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001704 ConnectionManagerInterface* connection_manager =
1705 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001706 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001707 LOG(INFO) << "We could not determine our connection type. "
1708 << "Defaulting to allow updates.";
1709 return true;
1710 }
1711 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1712 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001713 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001714 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1715 return is_allowed;
1716}
1717
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001718} // namespace chromeos_update_engine