blob: 78d8d5005d27b80a476c0f655d763550a590fecf [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";
Sen Jiangfe284402018-03-21 14:03:50 -070079static const char* kTagPowerwash = "Powerwash";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080080
Alex Deymoac41a822015-09-15 20:52:53 -070081static const char* kOmahaUpdaterVersion = "0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +000082
Sen Jiang42fa45e2018-03-12 11:02:14 -070083// X-Goog-Update headers.
84static const char* kXGoogleUpdateInteractivity = "X-Goog-Update-Interactivity";
85static const char* kXGoogleUpdateAppId = "X-Goog-Update-AppId";
86static const char* kXGoogleUpdateUpdater = "X-Goog-Update-Updater";
Alex Deymo14ad88e2016-06-29 12:30:14 -070087
Alex Deymob3fa53b2016-04-18 19:57:58 -070088// updatecheck attributes (without the underscore prefix).
89static const char* kEolAttr = "eol";
90
Alex Deymoac41a822015-09-15 20:52:53 -070091namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +000092
Darin Petkov1cbd78f2010-07-29 12:38:34 -070093// Returns an XML ping element attribute assignment with attribute
94// |name| and value |ping_days| if |ping_days| has a value that needs
95// to be sent, or an empty string otherwise.
96string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -070097 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -070098 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -070099 return "";
100}
101
102// Returns an XML ping element if any of the elapsed days need to be
103// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700104string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700105 string ping_active = GetPingAttribute("a", ping_active_days);
106 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
107 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700108 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700109 ping_active.c_str(),
110 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700111 }
112 return "";
113}
114
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700115// Returns an XML that goes into the body of the <app> element of the Omaha
116// request based on the given parameters.
117string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700118 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700119 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700120 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700121 int ping_active_days,
122 int ping_roll_call_days,
123 PrefsInterface* prefs) {
124 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700125 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700126 if (include_ping)
127 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700128 if (!ping_only) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700129 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700130 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700131 "></updatecheck>\n",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700132 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700133
Darin Petkov265f2902011-05-09 15:17:40 -0700134 // If this is the first update check after a reboot following a previous
135 // update, generate an event containing the previous version number. If
136 // the previous version preference file doesn't exist the event is still
137 // generated with a previous version of 0.0.0.0 -- this is relevant for
138 // older clients or new installs. The previous version event is not sent
139 // for ping-only requests because they come before the client has
Alex Deymo87c08862015-10-30 21:56:55 -0700140 // rebooted. The previous version event is also not sent if it was already
141 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700142 string prev_version;
143 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
144 prev_version = "0.0.0.0";
145 }
Alex Deymo87c08862015-10-30 21:56:55 -0700146 // We only store a non-empty previous version value after a successful
147 // update in the previous boot. After reporting it back to the server,
148 // we clear the previous version value so it doesn't get reported again.
149 if (!prev_version.empty()) {
150 app_body += base::StringPrintf(
151 " <event eventtype=\"%d\" eventresult=\"%d\" "
152 "previousversion=\"%s\"></event>\n",
Alex Deymo9fded1e2015-11-05 12:31:19 -0800153 OmahaEvent::kTypeRebootedAfterUpdate,
154 OmahaEvent::kResultSuccess,
Alex Deymo87c08862015-10-30 21:56:55 -0700155 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
156 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
157 << "Unable to reset the previous version.";
158 }
Darin Petkov95508da2011-01-05 12:42:29 -0800159 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700160 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800161 // The error code is an optional attribute so append it only if the result
162 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700163 string error_code;
164 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700165 error_code = base::StringPrintf(" errorcode=\"%d\"",
166 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700167 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700168 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700169 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700170 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700171 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700172
173 return app_body;
174}
175
Alex Deymo8e18f932015-03-27 16:16:59 -0700176// Returns the cohort* argument to include in the <app> tag for the passed
177// |arg_name| and |prefs_key|, if any. The return value is suitable to
178// concatenate to the list of arguments and includes a space at the end.
179string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700180 const string arg_name,
181 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700182 // There's nothing wrong with not having a given cohort setting, so we check
Sen Jiang771f6482018-04-04 17:59:10 -0700183 // existence first to avoid the warning log message.
Alex Deymo8e18f932015-03-27 16:16:59 -0700184 if (!prefs->Exists(prefs_key))
185 return "";
186 string cohort_value;
187 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
188 return "";
189 // This is a sanity check to avoid sending a huge XML file back to Ohama due
190 // to a compromised stateful partition making the update check fail in low
191 // network environments envent after a reboot.
192 if (cohort_value.size() > 1024) {
193 LOG(WARNING) << "The omaha cohort setting " << arg_name
194 << " has a too big value, which must be an error or an "
195 "attacker trying to inhibit updates.";
196 return "";
197 }
198
Alex Deymob0d74eb2015-03-30 17:59:17 -0700199 string escaped_xml_value;
200 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
201 LOG(WARNING) << "The omaha cohort setting " << arg_name
202 << " is ASCII-7 invalid, ignoring it.";
203 return "";
204 }
205
Alex Deymo8e18f932015-03-27 16:16:59 -0700206 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700207 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700208}
209
Sen Jiang94a4dec2017-03-28 18:23:35 -0700210struct OmahaAppData {
211 string id;
212 string version;
Sen Jiang684c9cd2017-10-17 16:26:45 -0700213 string product_components;
Sen Jiang94a4dec2017-03-28 18:23:35 -0700214};
215
Sen Jiang684c9cd2017-10-17 16:26:45 -0700216bool IsValidComponentID(const string& id) {
217 for (char c : id) {
218 if (!isalnum(c) && c != '-' && c != '_' && c != '.')
219 return false;
220 }
221 return true;
222}
223
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700224// Returns an XML that corresponds to the entire <app> node of the Omaha
225// request based on the given parameters.
226string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700227 OmahaRequestParams* params,
Sen Jiang94a4dec2017-03-28 18:23:35 -0700228 const OmahaAppData& app_data,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700229 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700230 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700231 int ping_active_days,
232 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800233 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700234 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700235 string app_body = GetAppBody(event, params, ping_only, include_ping,
236 ping_active_days, ping_roll_call_days,
237 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700238 string app_versions;
239
Sen Jiang8cd42342018-01-31 12:06:59 -0800240 // If we are downgrading to a more stable channel and we are allowed to do
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700241 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
242 // highest-versioned payload on the destination channel.
Sen Jiang8500d3a2018-02-08 12:04:05 -0800243 if (params->ShouldPowerwash()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700244 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
245 << "on downgrading to the version in the more stable channel";
246 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700247 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700248 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700249 app_versions = "version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700250 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700251 }
252
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700253 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700254 string app_channels =
255 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
256 if (params->current_channel() != download_channel) {
257 app_channels += "from_track=\"" + XmlEncodeWithDefault(
258 params->current_channel(), "") + "\" ";
259 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700260
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700261 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700262
David Zeuthen639aa362014-02-03 16:23:44 -0800263 // If install_date_days is not set (e.g. its value is -1 ), don't
264 // include the attribute.
265 string install_date_in_days_str = "";
266 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700267 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
268 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800269 }
270
Alex Deymo8e18f932015-03-27 16:16:59 -0700271 string app_cohort_args;
272 app_cohort_args += GetCohortArgXml(system_state->prefs(),
273 "cohort", kPrefsOmahaCohort);
274 app_cohort_args += GetCohortArgXml(system_state->prefs(),
275 "cohorthint", kPrefsOmahaCohortHint);
276 app_cohort_args += GetCohortArgXml(system_state->prefs(),
277 "cohortname", kPrefsOmahaCohortName);
278
Alex Deymoebf6e122017-03-10 16:12:01 -0800279 string fingerprint_arg;
280 if (!params->os_build_fingerprint().empty()) {
Sen Jiang8cd42342018-01-31 12:06:59 -0800281 fingerprint_arg = "fingerprint=\"" +
282 XmlEncodeWithDefault(params->os_build_fingerprint(), "") +
283 "\" ";
Alex Deymoebf6e122017-03-10 16:12:01 -0800284 }
285
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700286 string buildtype_arg;
287 if (!params->os_build_type().empty()) {
288 buildtype_arg = "os_build_type=\"" +
289 XmlEncodeWithDefault(params->os_build_type(), "") + "\" ";
290 }
291
Sen Jiang684c9cd2017-10-17 16:26:45 -0700292 string product_components_args;
Sen Jiang8500d3a2018-02-08 12:04:05 -0800293 if (!params->ShouldPowerwash() && !app_data.product_components.empty()) {
Sen Jiang684c9cd2017-10-17 16:26:45 -0700294 brillo::KeyValueStore store;
295 if (store.LoadFromString(app_data.product_components)) {
296 for (const string& key : store.GetKeys()) {
297 if (!IsValidComponentID(key)) {
298 LOG(ERROR) << "Invalid component id: " << key;
299 continue;
300 }
301 string version;
302 if (!store.GetString(key, &version)) {
303 LOG(ERROR) << "Failed to get version for " << key
304 << " in product_components.";
305 continue;
306 }
307 product_components_args +=
308 base::StringPrintf("_%s.version=\"%s\" ",
309 key.c_str(),
310 XmlEncodeWithDefault(version, "").c_str());
311 }
312 } else {
313 LOG(ERROR) << "Failed to parse product_components:\n"
314 << app_data.product_components;
315 }
316 }
317
318 // clang-format off
Alex Deymob0d74eb2015-03-30 17:59:17 -0700319 string app_xml = " <app "
Sen Jiang94a4dec2017-03-28 18:23:35 -0700320 "appid=\"" + XmlEncodeWithDefault(app_data.id, "") + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700321 app_cohort_args +
322 app_versions +
323 app_channels +
Sen Jiang684c9cd2017-10-17 16:26:45 -0700324 product_components_args +
Alex Deymoebf6e122017-03-10 16:12:01 -0800325 fingerprint_arg +
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700326 buildtype_arg +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700327 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
328 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
329 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
330 "delta_okay=\"" + delta_okay_str + "\" "
331 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
332 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
333 install_date_in_days_str +
334 ">\n" +
335 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700336 " </app>\n";
Sen Jiang684c9cd2017-10-17 16:26:45 -0700337 // clang-format on
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700338 return app_xml;
339}
340
341// Returns an XML that corresponds to the entire <os> node of the Omaha
342// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700343string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700344 string os_xml =" <os "
345 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
346 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
347 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
348 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700349 return os_xml;
350}
351
352// Returns an XML that corresponds to the entire Omaha request based on the
353// given parameters.
354string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700355 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700356 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700357 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700358 int ping_active_days,
359 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800360 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700361 SystemState* system_state) {
362 string os_xml = GetOsXml(params);
Sen Jiang684c9cd2017-10-17 16:26:45 -0700363 OmahaAppData product_app = {
364 .id = params->GetAppId(),
365 .version = params->app_version(),
366 .product_components = params->product_components()};
Sen Jiang94a4dec2017-03-28 18:23:35 -0700367 string app_xml = GetAppXml(event,
368 params,
369 product_app,
370 ping_only,
371 include_ping,
372 ping_active_days,
373 ping_roll_call_days,
374 install_date_in_days,
375 system_state);
376 if (!params->system_app_id().empty()) {
377 OmahaAppData system_app = {.id = params->system_app_id(),
378 .version = params->system_version()};
379 app_xml += GetAppXml(event,
380 params,
381 system_app,
382 ping_only,
383 include_ping,
384 ping_active_days,
385 ping_roll_call_days,
386 install_date_in_days,
387 system_state);
388 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700389
Alex Vakulenko75039d72014-03-25 12:36:28 -0700390 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700391 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700392
Alex Deymoac41a822015-09-15 20:52:53 -0700393 string updater_version = XmlEncodeWithDefault(
394 base::StringPrintf("%s-%s",
395 constants::kOmahaUpdaterID,
396 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700397 string request_xml =
398 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700399 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700400 "version=\"" + updater_version + "\" "
401 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700402 install_source +
403 "ismachine=\"1\">\n") +
404 os_xml +
405 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700406 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700407
408 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000409}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700410
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700411} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000412
David Zeuthene8ed8632014-07-24 13:38:10 -0400413// Struct used for holding data obtained when parsing the XML.
414struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400415 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
416
417 // Pointer to the expat XML_Parser object.
418 XML_Parser xml_parser;
419
David Zeuthene8ed8632014-07-24 13:38:10 -0400420 // This is the state of the parser as it's processing the XML.
421 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400422 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400423 string current_path;
424
425 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400426 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700427 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400428 string daystart_elapsed_days;
429 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800430
Sen Jiang81259682017-03-30 15:11:30 -0700431 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700432 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700433 vector<string> url_codebase;
434 string manifest_version;
435 map<string, string> action_postinstall_attrs;
436 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700437 string cohort;
438 string cohorthint;
439 string cohortname;
440 bool cohort_set = false;
441 bool cohorthint_set = false;
442 bool cohortname_set = false;
Sen Jiang81259682017-03-30 15:11:30 -0700443
444 struct Package {
445 string name;
446 string size;
447 string hash;
448 };
449 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800450 };
Sen Jiang81259682017-03-30 15:11:30 -0700451 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400452};
453
454namespace {
455
456// Callback function invoked by expat.
457void ParserHandlerStart(void* user_data, const XML_Char* element,
458 const XML_Char** attr) {
459 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
460
461 if (data->failed)
462 return;
463
464 data->current_path += string("/") + element;
465
466 map<string, string> attrs;
467 if (attr != nullptr) {
468 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
469 string key = attr[n];
470 string value = attr[n + 1];
471 attrs[key] = value;
472 }
473 }
474
Alex Deymo8e18f932015-03-27 16:16:59 -0700475 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700476 OmahaParserData::App app;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700477 if (attrs.find("appid") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700478 app.id = attrs["appid"];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700479 }
Alex Deymo8e18f932015-03-27 16:16:59 -0700480 if (attrs.find("cohort") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700481 app.cohort_set = true;
482 app.cohort = attrs["cohort"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700483 }
484 if (attrs.find("cohorthint") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700485 app.cohorthint_set = true;
486 app.cohorthint = attrs["cohorthint"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700487 }
488 if (attrs.find("cohortname") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700489 app.cohortname_set = true;
490 app.cohortname = attrs["cohortname"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700491 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700492 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700493 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700494 if (!data->apps.empty())
495 data->apps.back().updatecheck_status = attrs["status"];
496 if (data->updatecheck_poll_interval.empty())
497 data->updatecheck_poll_interval = attrs["PollInterval"];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700498 // Omaha sends arbitrary key-value pairs as extra attributes starting with
499 // an underscore.
500 for (const auto& attr : attrs) {
501 if (!attr.first.empty() && attr.first[0] == '_')
502 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
503 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400504 } else if (data->current_path == "/response/daystart") {
505 // Get the install-date.
506 data->daystart_elapsed_days = attrs["elapsed_days"];
507 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
508 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
509 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700510 if (!data->apps.empty())
511 data->apps.back().url_codebase.push_back(attrs["codebase"]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800512 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400513 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800514 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700515 if (!data->apps.empty())
516 data->apps.back().packages.push_back({.name = attrs["name"],
517 .size = attrs["size"],
518 .hash = attrs["hash_sha256"]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400519 } else if (data->current_path == "/response/app/updatecheck/manifest") {
520 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700521 if (!data->apps.empty())
522 data->apps.back().manifest_version = attrs[kTagVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400523 } else if (data->current_path ==
524 "/response/app/updatecheck/manifest/actions/action") {
525 // We only care about the postinstall action.
Sen Jiang81259682017-03-30 15:11:30 -0700526 if (attrs["event"] == "postinstall" && !data->apps.empty()) {
527 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400528 }
529 }
530}
531
532// Callback function invoked by expat.
533void ParserHandlerEnd(void* user_data, const XML_Char* element) {
534 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
535 if (data->failed)
536 return;
537
538 const string path_suffix = string("/") + element;
539
Alex Vakulenko0103c362016-01-20 07:56:15 -0800540 if (!base::EndsWith(data->current_path, path_suffix,
541 base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400542 LOG(ERROR) << "Unexpected end element '" << element
543 << "' with current_path='" << data->current_path << "'";
544 data->failed = true;
545 return;
546 }
547 data->current_path.resize(data->current_path.size() - path_suffix.size());
548}
549
David Zeuthenf3e28012014-08-26 18:23:52 -0400550// Callback function invoked by expat.
551//
552// This is called for entity declarations. Since Omaha is guaranteed
553// to never return any XML with entities our course of action is to
554// just stop parsing. This avoids potential resource exhaustion
555// problems AKA the "billion laughs". CVE-2013-0340.
556void ParserHandlerEntityDecl(void *user_data,
557 const XML_Char *entity_name,
558 int is_parameter_entity,
559 const XML_Char *value,
560 int value_length,
561 const XML_Char *base,
562 const XML_Char *system_id,
563 const XML_Char *public_id,
564 const XML_Char *notation_name) {
565 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
566
567 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
568 data->failed = true;
569 data->entity_decl = true;
570 XML_StopParser(data->xml_parser, false);
571}
572
David Zeuthene8ed8632014-07-24 13:38:10 -0400573} // namespace
574
Alex Deymob0d74eb2015-03-30 17:59:17 -0700575bool XmlEncode(const string& input, string* output) {
576 if (std::find_if(input.begin(), input.end(),
577 [](const char c){return c & 0x80;}) != input.end()) {
578 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
579 utils::HexDumpString(input);
580 return false;
581 }
Alex Deymocc457852015-06-18 18:35:50 -0700582 output->clear();
583 // We need at least input.size() space in the output, but the code below will
584 // handle it if we need more.
585 output->reserve(input.size());
586 for (char c : input) {
587 switch (c) {
588 case '\"':
589 output->append("&quot;");
590 break;
591 case '\'':
592 output->append("&apos;");
593 break;
594 case '&':
595 output->append("&amp;");
596 break;
597 case '<':
598 output->append("&lt;");
599 break;
600 case '>':
601 output->append("&gt;");
602 break;
603 default:
604 output->push_back(c);
605 }
606 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700607 return true;
608}
609
610string XmlEncodeWithDefault(const string& input, const string& default_value) {
611 string output;
612 if (XmlEncode(input, &output))
613 return output;
614 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000615}
616
Alex Deymoc1c17b42015-11-23 03:53:15 -0300617OmahaRequestAction::OmahaRequestAction(
618 SystemState* system_state,
619 OmahaEvent* event,
620 std::unique_ptr<HttpFetcher> http_fetcher,
621 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800622 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700623 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300624 http_fetcher_(std::move(http_fetcher)),
Thieu Le116fda32011-04-19 11:01:54 -0700625 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700626 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700627 ping_roll_call_days_(0) {
628 params_ = system_state->request_params();
629}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000630
Darin Petkov6a5b3222010-07-13 14:55:28 -0700631OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000632
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700633// Calculates the value to use for the ping days parameter.
634int OmahaRequestAction::CalculatePingDays(const string& key) {
635 int days = kNeverPinged;
636 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800637 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700638 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
639 if (days < 0) {
640 // If |days| is negative, then the system clock must have jumped
641 // back in time since the ping was sent. Mark the value so that
642 // it doesn't get sent to the server but we still update the
643 // last ping daystart preference. This way the next ping time
644 // will be correct, hopefully.
645 days = kPingTimeJump;
646 LOG(WARNING) <<
647 "System clock jumped back in time. Resetting ping daystarts.";
648 }
649 }
650 return days;
651}
652
653void OmahaRequestAction::InitPingDays() {
654 // We send pings only along with update checks, not with events.
655 if (IsEvent()) {
656 return;
657 }
658 // TODO(petkov): Figure a way to distinguish active use pings
659 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700660 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700661 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
662 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
663}
664
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700665bool OmahaRequestAction::ShouldPing() const {
666 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
667 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
668 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
669 if (powerwash_count > 0) {
670 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
671 << "powerwash_count is " << powerwash_count;
672 return false;
673 }
Amin Hassani1677e812017-06-21 13:36:36 -0700674 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
675 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
676 << "the first_active_omaha_ping_sent is true";
677 return false;
678 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700679 return true;
680 }
681 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
682}
683
David Zeuthen639aa362014-02-03 16:23:44 -0800684// static
685int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
686 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700687 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800688 return -1;
689
690 // If we have the value stored on disk, just return it.
691 int64_t stored_value;
692 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
693 // Convert and sanity-check.
694 int install_date_days = static_cast<int>(stored_value);
695 if (install_date_days >= 0)
696 return install_date_days;
697 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
698 << install_date_days << " looks suspicious.";
699 prefs->Delete(kPrefsInstallDateDays);
700 }
701
702 // Otherwise, if OOBE is not complete then do nothing and wait for
703 // ParseResponse() to call ParseInstallDate() and then
704 // PersistInstallDate() to set the kPrefsInstallDateDays state
705 // variable. Once that is done, we'll then report back in future
706 // Omaha requests. This works exactly because OOBE triggers an
707 // update check.
708 //
709 // However, if OOBE is complete and the kPrefsInstallDateDays state
710 // variable is not set, there are two possibilities
711 //
712 // 1. The update check in OOBE failed so we never got a response
713 // from Omaha (no network etc.); or
714 //
715 // 2. OOBE was done on an older version that didn't write to the
716 // kPrefsInstallDateDays state variable.
717 //
718 // In both cases, we approximate the install date by simply
719 // inspecting the timestamp of when OOBE happened.
720
721 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700722 if (!system_state->hardware()->IsOOBEEnabled() ||
723 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800724 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700725 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800726 return -1;
727 }
728
729 int num_days;
730 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
731 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
732 << "as its value '" << utils::ToString(time_of_oobe)
733 << "' looks suspicious.";
734 return -1;
735 }
736
737 // Persist this to disk, for future use.
738 if (!OmahaRequestAction::PersistInstallDate(system_state,
739 num_days,
740 kProvisionedFromOOBEMarker))
741 return -1;
742
743 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
744 << num_days << " days";
745
746 return num_days;
747}
748
Darin Petkov6a5b3222010-07-13 14:55:28 -0700749void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000750 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700751 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700752 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700753 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700754 return;
755 }
David Zeuthen639aa362014-02-03 16:23:44 -0800756
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700757 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700758 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700759 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700760 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700761 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800762 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800763 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700764 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700765
Sen Jiang42fa45e2018-03-12 11:02:14 -0700766 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700767 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
768 params_->interactive() ? "fg" : "bg");
769 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
770 http_fetcher_->SetHeader(
771 kXGoogleUpdateUpdater,
772 base::StringPrintf(
773 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
774
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800775 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
776 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700777 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700778 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700779 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000780}
781
Darin Petkov6a5b3222010-07-13 14:55:28 -0700782void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000783 http_fetcher_->TerminateTransfer();
784}
785
786// We just store the response in the buffer. Once we've received all bytes,
787// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700788void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800789 const void* bytes,
790 size_t length) {
791 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
792 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000793}
794
795namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000796
797// Parses a 64 bit base-10 int from a string and returns it. Returns 0
798// on error. If the string contains "0", that's indistinguishable from
799// error.
800off_t ParseInt(const string& str) {
801 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700802 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000803 if (rc < 1) {
804 // failure
805 return 0;
806 }
807 return ret;
808}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700809
David Zeuthene8ed8632014-07-24 13:38:10 -0400810// Parses |str| and returns |true| if, and only if, its value is "true".
811bool ParseBool(const string& str) {
812 return str == "true";
813}
814
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700815// Update the last ping day preferences based on the server daystart
816// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400817bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700818 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400819 TEST_AND_RETURN_FALSE(
820 base::StringToInt64(parser_data->daystart_elapsed_seconds,
821 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700822 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
823
824 // Remember the local time that matches the server's last midnight
825 // time.
826 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
827 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
828 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
829 return true;
830}
Sen Jiang81259682017-03-30 15:11:30 -0700831
832// Parses the package node in the given XML document and populates
833// |output_object| if valid. Returns true if we should continue the parsing.
834// False otherwise, in which case it sets any error code using |completer|.
835bool ParsePackage(OmahaParserData::App* app,
836 OmahaResponse* output_object,
837 ScopedActionCompleter* completer) {
838 if (app->updatecheck_status == "noupdate") {
839 if (!app->packages.empty()) {
840 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
841 completer->set_code(ErrorCode::kOmahaResponseInvalid);
842 return false;
843 }
844 return true;
845 }
846 if (app->packages.empty()) {
847 LOG(ERROR) << "Omaha Response has no packages";
848 completer->set_code(ErrorCode::kOmahaResponseInvalid);
849 return false;
850 }
851 if (app->url_codebase.empty()) {
852 LOG(ERROR) << "No Omaha Response URLs";
853 completer->set_code(ErrorCode::kOmahaResponseInvalid);
854 return false;
855 }
856 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
857 vector<string> metadata_sizes =
858 base::SplitString(app->action_postinstall_attrs[kTagMetadataSize],
859 ":",
860 base::TRIM_WHITESPACE,
861 base::SPLIT_WANT_ALL);
862 vector<string> metadata_signatures =
863 base::SplitString(app->action_postinstall_attrs[kTagMetadataSignatureRsa],
864 ":",
865 base::TRIM_WHITESPACE,
866 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700867 vector<string> is_delta_payloads =
868 base::SplitString(app->action_postinstall_attrs[kTagIsDeltaPayload],
869 ":",
870 base::TRIM_WHITESPACE,
871 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700872 for (size_t i = 0; i < app->packages.size(); i++) {
873 const auto& package = app->packages[i];
874 if (package.name.empty()) {
875 LOG(ERROR) << "Omaha Response has empty package name";
876 completer->set_code(ErrorCode::kOmahaResponseInvalid);
877 return false;
878 }
879 LOG(INFO) << "Found package " << package.name;
880
881 OmahaResponse::Package out_package;
882 for (const string& codebase : app->url_codebase) {
883 if (codebase.empty()) {
884 LOG(ERROR) << "Omaha Response URL has empty codebase";
885 completer->set_code(ErrorCode::kOmahaResponseInvalid);
886 return false;
887 }
888 out_package.payload_urls.push_back(codebase + package.name);
889 }
890 // Parse the payload size.
891 base::StringToUint64(package.size, &out_package.size);
892 if (out_package.size <= 0) {
893 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
894 completer->set_code(ErrorCode::kOmahaResponseInvalid);
895 return false;
896 }
897 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
898
899 if (i < metadata_sizes.size())
900 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
901 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
902 << " bytes";
903
904 if (i < metadata_signatures.size())
905 out_package.metadata_signature = metadata_signatures[i];
906 LOG(INFO) << "Payload metadata signature = "
907 << out_package.metadata_signature;
908
909 out_package.hash = package.hash;
910 if (out_package.hash.empty()) {
911 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
912 completer->set_code(ErrorCode::kOmahaResponseInvalid);
913 return false;
914 }
915 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700916
917 if (i < is_delta_payloads.size())
918 out_package.is_delta = ParseBool(is_delta_payloads[i]);
919 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
920
Sen Jiang81259682017-03-30 15:11:30 -0700921 output_object->packages.push_back(std::move(out_package));
922 }
923
924 return true;
925}
926
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700927} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000928
David Zeuthene8ed8632014-07-24 13:38:10 -0400929bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700930 OmahaResponse* output_object,
931 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700932 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700933 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700934 return false;
935 }
Sen Jiang81259682017-03-30 15:11:30 -0700936 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700937
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800938 // chromium-os:37289: The PollInterval is not supported by Omaha server
939 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700940 // slow down the request rate from the server-side. Note that the PollInterval
941 // is not persisted, so it has to be sent by the server on every response to
942 // guarantee that the scheduler uses this value (otherwise, if the device got
943 // rebooted after the last server-indicated value, it'll revert to the default
944 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
945 // based on the assumption that we perform an update check every hour so that
946 // the max value of 8 will roughly be equivalent to one work day. If we decide
947 // to use PollInterval permanently, we should update the
948 // max_update_checks_allowed to take PollInterval into account. Note: The
949 // parsing for PollInterval happens even before parsing of the status because
950 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400951 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700952 &output_object->poll_interval);
953
David Zeuthen639aa362014-02-03 16:23:44 -0800954 // Check for the "elapsed_days" attribute in the "daystart"
955 // element. This is the number of days since Jan 1 2007, 0:00
956 // PST. If we don't have a persisted value of the Omaha InstallDate,
957 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400958 if (ParseInstallDate(parser_data, output_object) &&
959 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800960 // Since output_object->install_date_days is never negative, the
961 // elapsed_days -> install-date calculation is reduced to simply
962 // rounding down to the nearest number divisible by 7.
963 int remainder = output_object->install_date_days % 7;
964 int install_date_days_rounded =
965 output_object->install_date_days - remainder;
966 if (PersistInstallDate(system_state_,
967 install_date_days_rounded,
968 kProvisionedFromOmahaResponse)) {
969 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
970 << install_date_days_rounded << " days";
971 }
972 }
973
Alex Deymo00d79ac2015-06-29 15:41:49 -0700974 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -0700975 for (const auto& app : parser_data->apps) {
976 if (app.id == params_->GetAppId()) {
977 if (app.cohort_set)
978 PersistCohortData(kPrefsOmahaCohort, app.cohort);
979 if (app.cohorthint_set)
980 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
981 if (app.cohortname_set)
982 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
983 break;
984 }
985 }
Alex Deymo00d79ac2015-06-29 15:41:49 -0700986
Alex Deymob3fa53b2016-04-18 19:57:58 -0700987 // Parse the updatecheck attributes.
988 PersistEolStatus(parser_data->updatecheck_attrs);
989
David Zeuthene8ed8632014-07-24 13:38:10 -0400990 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700991 return false;
992
David Zeuthene8ed8632014-07-24 13:38:10 -0400993 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700994 return false;
995
Sen Jiang0affc2c2017-02-10 15:55:05 -0800996 // Package has to be parsed after Params now because ParseParams need to make
997 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -0700998 for (auto& app : parser_data->apps)
999 if (!ParsePackage(&app, output_object, completer))
1000 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001001
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001002 return true;
1003}
1004
David Zeuthene8ed8632014-07-24 13:38:10 -04001005bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001006 OmahaResponse* output_object,
1007 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001008 output_object->update_exists = false;
1009 for (size_t i = 0; i < parser_data->apps.size(); i++) {
1010 const string& status = parser_data->apps[i].updatecheck_status;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001011 if (status == "noupdate") {
1012 // Don't update if any app has status="noupdate".
Sen Jiang81259682017-03-30 15:11:30 -07001013 LOG(INFO) << "No update for <app> " << i;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001014 output_object->update_exists = false;
1015 break;
Sen Jiang81259682017-03-30 15:11:30 -07001016 } else if (status == "ok") {
Sen Jiang00adf7b2017-06-26 15:57:29 -07001017 if (parser_data->apps[i].action_postinstall_attrs["noupdate"] == "true") {
1018 // noupdate="true" in postinstall attributes means it's an update to
1019 // self, only update if there's at least one app really have update.
1020 LOG(INFO) << "Update to self for <app> " << i;
1021 } else {
1022 LOG(INFO) << "Update for <app> " << i;
1023 output_object->update_exists = true;
1024 }
Sen Jiang81259682017-03-30 15:11:30 -07001025 } else {
1026 LOG(ERROR) << "Unknown Omaha response status: " << status;
1027 completer->set_code(ErrorCode::kOmahaResponseInvalid);
1028 return false;
1029 }
1030 }
1031 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001032 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001033 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001034 }
1035
Sen Jiang81259682017-03-30 15:11:30 -07001036 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001037}
1038
David Zeuthene8ed8632014-07-24 13:38:10 -04001039bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001040 OmahaResponse* output_object,
1041 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001042 map<string, string> attrs;
1043 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001044 if (app.id == params_->GetAppId()) {
1045 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -07001046 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001047 } else if (!params_->system_app_id().empty() &&
1048 app.id == params_->system_app_id()) {
1049 // this is the system app (this check is intentionally skipped if there is
1050 // no system_app_id set)
1051 output_object->system_version = app.manifest_version;
1052 }
1053 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -07001054 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001055 }
Sen Jiang81259682017-03-30 15:11:30 -07001056 }
Chris Sosa3b748432013-06-20 16:42:59 -07001057 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -07001058 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001059 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -07001060 return false;
1061 }
1062
1063 LOG(INFO) << "Received omaha response to update to version "
1064 << output_object->version;
1065
David Zeuthene8ed8632014-07-24 13:38:10 -04001066 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001067 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001068 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001069 return false;
1070 }
1071
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001072 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -04001073 output_object->more_info_url = attrs[kTagMoreInfo];
David Zeuthene8ed8632014-07-24 13:38:10 -04001074 output_object->prompt = ParseBool(attrs[kTagPrompt]);
1075 output_object->deadline = attrs[kTagDeadline];
1076 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001077 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -04001078 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001079 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -04001080 ParseBool(attrs[kTagDisableP2PForSharing]);
1081 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001082
David Zeuthene8ed8632014-07-24 13:38:10 -04001083 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -08001084 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001085 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001086
Jay Srinivasan08262882012-12-28 19:29:43 -08001087 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -04001088 ParseBool(attrs[kTagDisablePayloadBackoff]);
Sen Jiangfe284402018-03-21 14:03:50 -07001089 output_object->powerwash_required = ParseBool(attrs[kTagPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -08001090
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001091 return true;
1092}
1093
David Zeuthene8ed8632014-07-24 13:38:10 -04001094// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +00001095// and fill in the appropriate fields of the output object. Also, notifies
1096// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -07001097void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
1098 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +00001099 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001100 string current_response(response_buffer_.begin(), response_buffer_.end());
1101 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001102
Gilad Arnold74b5f552014-10-07 08:17:16 -07001103 PayloadStateInterface* const payload_state = system_state_->payload_state();
1104
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001105 // Events are best effort transactions -- assume they always succeed.
1106 if (IsEvent()) {
1107 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001108 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001109 return;
1110 }
1111
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001112 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001113 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -07001114 int code = GetHTTPResponseCode();
1115 // Makes sure we send sane error values.
1116 if (code < 0 || code >= 1000) {
1117 code = 999;
1118 }
David Zeuthena99981f2013-04-29 13:42:47 -07001119 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001120 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +00001121 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001122 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001123
David Zeuthene8ed8632014-07-24 13:38:10 -04001124 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -04001125 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -04001126 XML_SetUserData(parser, &parser_data);
1127 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -04001128 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001129 XML_Status res = XML_Parse(
1130 parser,
1131 reinterpret_cast<const char*>(response_buffer_.data()),
1132 response_buffer_.size(),
1133 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -04001134 XML_ParserFree(parser);
1135
1136 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -07001137 LOG(ERROR) << "Omaha response not valid XML: "
1138 << XML_ErrorString(XML_GetErrorCode(parser))
1139 << " at line " << XML_GetCurrentLineNumber(parser)
1140 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -04001141 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
1142 if (response_buffer_.empty()) {
1143 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
1144 } else if (parser_data.entity_decl) {
1145 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
1146 }
1147 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001148 return;
1149 }
1150
Alex Deymoebbe7ef2014-10-30 13:02:49 -07001151 // Update the last ping day preferences based on the server daystart response
1152 // even if we didn't send a ping. Omaha always includes the daystart in the
1153 // response, but log the error if it didn't.
1154 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
1155 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -07001156
Amin Hassani1677e812017-06-21 13:36:36 -07001157 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
1158 // we have got a response from omaha and if its value has never been set to
1159 // true before. Failure of this function should be ignored. There should be no
1160 // need to check if a=-1 has been sent because older devices have already sent
1161 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
1162 // future checks.
1163 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
1164 system_state_->hardware()->SetFirstActiveOmahaPingSent();
1165 }
1166
Thieu Le116fda32011-04-19 11:01:54 -07001167 if (!HasOutputPipe()) {
1168 // Just set success to whether or not the http transfer succeeded,
1169 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001170 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001171 return;
1172 }
1173
Darin Petkov6a5b3222010-07-13 14:55:28 -07001174 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001175 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001176 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001177 output_object.update_exists = true;
1178 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001179
Tao Bao5688d162017-06-06 13:09:06 -07001180 if (ShouldIgnoreUpdate(output_object)) {
1181 output_object.update_exists = false;
1182 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001183 return;
1184 }
1185
David Zeuthen8f191b22013-08-06 12:27:50 -07001186 // If Omaha says to disable p2p, respect that
1187 if (output_object.disable_p2p_for_downloading) {
1188 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1189 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001190 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001191 }
1192 if (output_object.disable_p2p_for_sharing) {
1193 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1194 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001195 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001196 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001197
1198 // Update the payload state with the current response. The payload state
1199 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001200 // from what's stored already. We are updating the payload state as late
1201 // as possible in this method so that if a new release gets pushed and then
1202 // got pulled back due to some issues, we don't want to clear our internal
1203 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001204 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001205
David Zeuthen8f191b22013-08-06 12:27:50 -07001206 // It could be we've already exceeded the deadline for when p2p is
1207 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001208 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001209 payload_state->P2PNewAttempt();
1210 if (!payload_state->P2PAttemptAllowed()) {
1211 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1212 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001213 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001214 }
1215 }
1216
1217 // From here on, we'll complete stuff in CompleteProcessing() so
1218 // disable |completer| since we'll create a new one in that
1219 // function.
1220 completer.set_should_complete(false);
1221
1222 // If we're allowed to use p2p for downloading we do not pay
1223 // attention to wall-clock-based waiting if the URL is indeed
1224 // available via p2p. Therefore, check if the file is available via
1225 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001226 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001227 LookupPayloadViaP2P(output_object);
1228 } else {
1229 CompleteProcessing();
1230 }
1231}
1232
1233void OmahaRequestAction::CompleteProcessing() {
1234 ScopedActionCompleter completer(processor_, this);
1235 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1236 PayloadStateInterface* payload_state = system_state_->payload_state();
1237
Alex Deymo46a9aae2016-05-04 20:20:11 -07001238 if (system_state_->hardware()->IsOOBEEnabled() &&
1239 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
Kevin Cernekeec5081a82016-04-08 12:29:52 -07001240 output_object.deadline.empty() &&
1241 params_->app_version() != "ForcedUpdate") {
Kevin Cernekee2494e282016-03-29 18:03:53 -07001242 output_object.update_exists = false;
1243 LOG(INFO) << "Ignoring non-critical Omaha updates until OOBE is done.";
1244 completer.set_code(ErrorCode::kNonCriticalUpdateInOOBE);
1245 return;
1246 }
1247
David Zeuthen8f191b22013-08-06 12:27:50 -07001248 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001249 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001250 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001251 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001252 return;
1253 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001254
Chris Sosa20f005c2013-09-05 13:53:08 -07001255 if (payload_state->ShouldBackoffDownload()) {
1256 output_object.update_exists = false;
1257 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1258 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001259 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001260 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001261 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001262 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001263}
1264
1265void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1266 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1267 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001268 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001269 } else {
1270 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1271 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001272 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001273 }
1274 CompleteProcessing();
1275}
1276
1277void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001278 // If the device is in the middle of an update, the state variables
1279 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1280 // tracks the offset and length of the operation currently in
1281 // progress. The offset is based from the end of the manifest which
1282 // is kPrefsManifestMetadataSize bytes long.
1283 //
1284 // To make forward progress and avoid deadlocks, we need to find a
1285 // peer that has at least the entire operation we're currently
1286 // working on. Otherwise we may end up in a situation where two
1287 // devices bounce back and forth downloading from each other,
1288 // neither making any forward progress until one of them decides to
1289 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1290 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001291 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001292 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001293 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001294 int64_t next_data_offset = 0;
1295 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001296 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001297 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1298 &manifest_metadata_size) &&
1299 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001300 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1301 &manifest_signature_size) &&
1302 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001303 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001304 &next_data_offset) &&
1305 next_data_offset != -1 &&
1306 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1307 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001308 minimum_size = manifest_metadata_size + manifest_signature_size +
1309 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001310 }
1311
Sen Jiang0affc2c2017-02-10 15:55:05 -08001312 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001313 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001314 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001315 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001316 string file_id =
1317 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001318 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001319 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1320 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001321 system_state_->p2p_manager()->LookupUrlForFile(
1322 file_id,
1323 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001324 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001325 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1326 base::Unretained(this)));
1327 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001328}
1329
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001330bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001331 if (params_->interactive()) {
1332 LOG(INFO) << "Not deferring download because update is interactive.";
1333 return false;
1334 }
1335
David Zeuthen8f191b22013-08-06 12:27:50 -07001336 // If we're using p2p to download _and_ we have a p2p URL, we never
1337 // defer the download. This is because the download will always
1338 // happen from a peer on the LAN and we've been waiting in line for
1339 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001340 const PayloadStateInterface* payload_state = system_state_->payload_state();
1341 if (payload_state->GetUsingP2PForDownloading() &&
1342 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001343 LOG(INFO) << "Download not deferred because download "
1344 << "will happen from a local peer (via p2p).";
1345 return false;
1346 }
1347
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001348 // We should defer the downloads only if we've first satisfied the
1349 // wall-clock-based-waiting period and then the update-check-based waiting
1350 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001351 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001352 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1353 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001354 return false;
1355 }
1356
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001357 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001358 case kWallClockWaitNotSatisfied:
1359 // We haven't even satisfied the first condition, passing the
1360 // wall-clock-based waiting period, so we should defer the downloads
1361 // until that happens.
1362 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1363 return true;
1364
1365 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1366 LOG(INFO) << "wall-clock-based-wait satisfied and "
1367 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001368 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001369
1370 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1371 // Wall-clock-based waiting period is satisfied, and it's determined
1372 // that we do not need the update-check-based wait. so no need to
1373 // defer downloads.
1374 LOG(INFO) << "wall-clock-based-wait satisfied and "
1375 << "update-check-based-wait is not required.";
1376 return false;
1377
1378 default:
1379 // Returning false for this default case so we err on the
1380 // side of downloading updates than deferring in case of any bugs.
1381 NOTREACHED();
1382 return false;
1383 }
1384}
1385
1386OmahaRequestAction::WallClockWaitResult
1387OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001388 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001389 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001390 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001391
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001392 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1393 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1394 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001395 // Note: This timestamp could be that of ANY update we saw in the past
1396 // (not necessarily this particular update we're considering to apply)
1397 // but never got to apply because of some reason (e.g. stop AU policy,
1398 // updates being pulled out from Omaha, changes in target version prefix,
1399 // new update being rolled out, etc.). But for the purposes of scattering
1400 // it doesn't matter which update the timestamp corresponds to. i.e.
1401 // the clock starts ticking the first time we see an update and we're
1402 // ready to apply when the random wait period is satisfied relative to
1403 // that first seen timestamp.
1404 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1405 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1406 << utils::ToString(update_first_seen_at);
1407 } else {
1408 // This seems like an unexpected error where the persisted value exists
1409 // but it's not readable for some reason. Just skip scattering in this
1410 // case to be safe.
1411 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1412 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1413 }
1414 } else {
Sen Jiang7c1171e2016-06-23 11:35:40 -07001415 update_first_seen_at = system_state_->clock()->GetWallclockTime();
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001416 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001417 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1418 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001419 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1420 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001421 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001422 // This seems like an unexpected error where the value cannot be
1423 // persisted for some reason. Just skip scattering in this
1424 // case to be safe.
1425 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1426 << utils::ToString(update_first_seen_at)
1427 << " cannot be persisted";
1428 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1429 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001430 }
1431
Sen Jiang7c1171e2016-06-23 11:35:40 -07001432 TimeDelta elapsed_time =
1433 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1434 TimeDelta max_scatter_period =
1435 TimeDelta::FromDays(output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001436
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001437 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001438 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001439 << ", Time Elapsed = "
1440 << utils::FormatSecs(elapsed_time.InSeconds())
1441 << ", MaxDaysToScatter = "
1442 << max_scatter_period.InDays();
1443
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001444 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001445 // The deadline is set for all rules which serve a delta update from a
1446 // previous FSI, which means this update will be applied mostly in OOBE
1447 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1448 // quickly.
1449 LOG(INFO) << "Not scattering as deadline flag is set";
1450 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1451 }
1452
1453 if (max_scatter_period.InDays() == 0) {
1454 // This means the Omaha rule creator decides that this rule
1455 // should not be scattered irrespective of the policy.
1456 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1457 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1458 }
1459
1460 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001461 // This means we've waited more than the upperbound wait in the rule
1462 // from the time we first saw a valid update available to us.
1463 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001464 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1465 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1466 }
1467
1468 // This means we are required to participate in scattering.
1469 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001470 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001471 if (remaining_wait_time.InSeconds() <= 0) {
1472 // Yes, it's our turn now.
1473 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1474
1475 // But we can't download until the update-check-count-based wait is also
1476 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001477 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001478 kWallClockWaitDoneButUpdateCheckWaitRequired :
1479 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1480 }
1481
1482 // Not our turn yet, so we have to wait until our turn to
1483 // help scatter the downloads across all clients of the enterprise.
1484 LOG(INFO) << "Update deferred for another "
1485 << utils::FormatSecs(remaining_wait_time.InSeconds())
1486 << " per policy.";
1487 return kWallClockWaitNotSatisfied;
1488}
1489
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001490bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001491 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001492
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001493 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1494 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1495 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001496 // We are unable to read the update check count from file for some reason.
1497 // So let's proceed anyway so as to not stall the update.
1498 LOG(ERROR) << "Unable to read update check count. "
1499 << "Skipping update-check-count-based-wait.";
1500 return true;
1501 }
1502 } else {
1503 // This file does not exist. This means we haven't started our update
1504 // check count down yet, so this is the right time to start the count down.
1505 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001506 params_->min_update_checks_needed(),
1507 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001508
1509 LOG(INFO) << "Randomly picked update check count value = "
1510 << update_check_count_value;
1511
1512 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001513 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1514 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001515 // We weren't able to write the update check count file for some reason.
1516 // So let's proceed anyway so as to not stall the update.
1517 LOG(ERROR) << "Unable to write update check count. "
1518 << "Skipping update-check-count-based-wait.";
1519 return true;
1520 }
1521 }
1522
1523 if (update_check_count_value == 0) {
1524 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1525 return true;
1526 }
1527
1528 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001529 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001530 // We err on the side of skipping scattering logic instead of stalling
1531 // a machine from receiving any updates in case of any unexpected state.
1532 LOG(ERROR) << "Invalid value for update check count detected. "
1533 << "Skipping update-check-count-based-wait.";
1534 return true;
1535 }
1536
1537 // Legal value, we need to wait for more update checks to happen
1538 // until this becomes 0.
1539 LOG(INFO) << "Deferring Omaha updates for another "
1540 << update_check_count_value
1541 << " update checks per policy";
1542 return false;
1543}
1544
David Zeuthen639aa362014-02-03 16:23:44 -08001545// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001546bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001547 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001548 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001549 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001550 &elapsed_days))
1551 return false;
1552
1553 if (elapsed_days < 0)
1554 return false;
1555
1556 output_object->install_date_days = elapsed_days;
1557 return true;
1558}
1559
1560// static
1561bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1562 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001563 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001564 return false;
1565
1566 return prefs->Exists(kPrefsInstallDateDays);
1567}
1568
1569// static
1570bool OmahaRequestAction::PersistInstallDate(
1571 SystemState *system_state,
1572 int install_date_days,
1573 InstallDateProvisioningSource source) {
1574 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1575
1576 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001577 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001578 return false;
1579
1580 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1581 return false;
1582
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001583 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001584 static_cast<int>(source), // Sample.
1585 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001586 return true;
1587}
1588
Alex Deymo8e18f932015-03-27 16:16:59 -07001589bool OmahaRequestAction::PersistCohortData(
1590 const string& prefs_key,
1591 const string& new_value) {
1592 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1593 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1594 return system_state_->prefs()->Delete(prefs_key);
1595 } else if (!new_value.empty()) {
1596 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1597 return system_state_->prefs()->SetString(prefs_key, new_value);
1598 }
1599 return true;
1600}
1601
Alex Deymob3fa53b2016-04-18 19:57:58 -07001602bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
1603 auto eol_attr = attrs.find(kEolAttr);
1604 if (eol_attr != attrs.end()) {
1605 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1606 eol_attr->second);
1607 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1608 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1609 }
1610 return true;
1611}
1612
David Zeuthen33bae492014-02-25 16:16:18 -08001613void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1614 // We only want to report this on "update check".
1615 if (ping_only_ || event_ != nullptr)
1616 return;
1617
1618 metrics::CheckResult result = metrics::CheckResult::kUnset;
1619 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1620 metrics::DownloadErrorCode download_error_code =
1621 metrics::DownloadErrorCode::kUnset;
1622
1623 // Regular update attempt.
1624 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001625 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001626 // OK, we parsed the response successfully but that does
1627 // necessarily mean that an update is available.
1628 if (HasOutputPipe()) {
1629 const OmahaResponse& response = GetOutputObject();
1630 if (response.update_exists) {
1631 result = metrics::CheckResult::kUpdateAvailable;
1632 reaction = metrics::CheckReaction::kUpdating;
1633 } else {
1634 result = metrics::CheckResult::kNoUpdateAvailable;
1635 }
1636 } else {
1637 result = metrics::CheckResult::kNoUpdateAvailable;
1638 }
1639 break;
1640
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001641 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001642 result = metrics::CheckResult::kUpdateAvailable;
1643 reaction = metrics::CheckReaction::kIgnored;
1644 break;
1645
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001646 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001647 result = metrics::CheckResult::kUpdateAvailable;
1648 reaction = metrics::CheckReaction::kDeferring;
1649 break;
1650
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001651 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001652 result = metrics::CheckResult::kUpdateAvailable;
1653 reaction = metrics::CheckReaction::kBackingOff;
1654 break;
1655
1656 default:
1657 // We report two flavors of errors, "Download errors" and "Parsing
1658 // error". Try to convert to the former and if that doesn't work
1659 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001660 metrics::DownloadErrorCode tmp_error =
1661 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001662 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1663 result = metrics::CheckResult::kDownloadError;
1664 download_error_code = tmp_error;
1665 } else {
1666 result = metrics::CheckResult::kParsingError;
1667 }
1668 break;
1669 }
1670
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001671 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1672 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001673}
1674
Chris Sosa77f79e82014-06-02 18:16:24 -07001675bool OmahaRequestAction::ShouldIgnoreUpdate(
Tao Bao5688d162017-06-06 13:09:06 -07001676 const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001677 // Note: policy decision to not update to a version we rolled back from.
1678 string rollback_version =
1679 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001680 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001681 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001682 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001683 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1684 return true;
1685 }
1686 }
1687
Tao Bao5688d162017-06-06 13:09:06 -07001688 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001689 LOG(INFO) << "Update is not allowed over current connection.";
1690 return true;
1691 }
1692
1693 // Note: We could technically delete the UpdateFirstSeenAt state when we
1694 // return true. If we do, it'll mean a device has to restart the
1695 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1696 // turned on again. On the other hand, it also increases the chance of update
1697 // starvation if an admin turns AU on/off more frequently. We choose to err on
1698 // the side of preventing starvation at the cost of not applying scattering in
1699 // those cases.
1700 return false;
1701}
1702
Tao Bao5688d162017-06-06 13:09:06 -07001703bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001704 ConnectionType type;
1705 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001706 ConnectionManagerInterface* connection_manager =
1707 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001708 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001709 LOG(INFO) << "We could not determine our connection type. "
1710 << "Defaulting to allow updates.";
1711 return true;
1712 }
1713 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1714 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001715 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001716 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1717 return is_allowed;
1718}
1719
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001720} // namespace chromeos_update_engine