blob: 2f361e5c28d03c3d32134428569ce4dbdd0be414 [file] [log] [blame]
Mike Frysinger8155d082012-04-06 15:23:18 -04001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
rspangler@google.com49fdf182009-10-10 00:57:34 +00002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Darin Petkov6a5b3222010-07-13 14:55:28 -07005#include "update_engine/omaha_request_action.h"
Darin Petkov85ced132010-09-01 10:20:56 -07006
Andrew de los Reyes08c4e272010-04-15 14:02:17 -07007#include <inttypes.h>
Darin Petkov85ced132010-09-01 10:20:56 -07008
David Zeuthene8ed8632014-07-24 13:38:10 -04009#include <map>
rspangler@google.com49fdf182009-10-10 00:57:34 +000010#include <sstream>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070011#include <string>
David Zeuthene8ed8632014-07-24 13:38:10 -040012#include <vector>
rspangler@google.com49fdf182009-10-10 00:57:34 +000013
David Zeuthen8f191b22013-08-06 12:27:50 -070014#include <base/bind.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070015#include <base/logging.h>
16#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070017#include <base/strings/string_number_conversions.h>
18#include <base/strings/string_util.h>
19#include <base/strings/stringprintf.h>
20#include <base/time/time.h>
David Zeuthene8ed8632014-07-24 13:38:10 -040021#include <expat.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000022
23#include "update_engine/action_pipe.h"
Alex Deymof6ee0162015-07-31 12:35:22 -070024#include "update_engine/connection_manager.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070025#include "update_engine/constants.h"
J. Richard Barnette056b0ab2013-10-29 15:24:56 -070026#include "update_engine/hardware_interface.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070027#include "update_engine/omaha_hash_calculator.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070028#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070029#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080030#include "update_engine/payload_state_interface.h"
Darin Petkov1cbd78f2010-07-29 12:38:34 -070031#include "update_engine/prefs_interface.h"
Chris Sosa77f79e82014-06-02 18:16:24 -070032#include "update_engine/real_dbus_wrapper.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000033#include "update_engine/utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000034
Darin Petkov1cbd78f2010-07-29 12:38:34 -070035using base::Time;
36using base::TimeDelta;
David Zeuthene8ed8632014-07-24 13:38:10 -040037using std::map;
rspangler@google.com49fdf182009-10-10 00:57:34 +000038using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040039using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000040
41namespace chromeos_update_engine {
42
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080043// List of custom pair tags that we interpret in the Omaha Response:
44static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080045static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070046static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080047// Deprecated: "IsDelta"
48static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080049static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
50static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
51// Deprecated: "ManifestSignatureRsa"
52// Deprecated: "ManifestSize"
53static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
54static const char* kTagMetadataSize = "MetadataSize";
55static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070056// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080057static const char* kTagPrompt = "Prompt";
58static const char* kTagSha256 = "sha256";
David Zeuthen8f191b22013-08-06 12:27:50 -070059static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
60static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
David Zeuthene7f89172013-10-31 10:21:04 -070061static const char* kTagPublicKeyRsa = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080062
rspangler@google.com49fdf182009-10-10 00:57:34 +000063namespace {
64
Alex Vakulenkod2779df2014-06-16 13:19:00 -070065static const char* const kGupdateVersion = "ChromeOSUpdateEngine-0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +000066
Darin Petkov1cbd78f2010-07-29 12:38:34 -070067// Returns an XML ping element attribute assignment with attribute
68// |name| and value |ping_days| if |ping_days| has a value that needs
69// to be sent, or an empty string otherwise.
70string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -070071 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -070072 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -070073 return "";
74}
75
76// Returns an XML ping element if any of the elapsed days need to be
77// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -070078string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -070079 string ping_active = GetPingAttribute("a", ping_active_days);
80 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
81 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -070082 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -070083 ping_active.c_str(),
84 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -070085 }
86 return "";
87}
88
Jay Srinivasanae4697c2013-03-18 17:08:08 -070089// Returns an XML that goes into the body of the <app> element of the Omaha
90// request based on the given parameters.
91string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070092 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -070093 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -070094 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -070095 int ping_active_days,
96 int ping_roll_call_days,
97 PrefsInterface* prefs) {
98 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -070099 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700100 if (include_ping)
101 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700102 if (!ping_only) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700103 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700104 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700105 "></updatecheck>\n",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700106 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700107
Darin Petkov265f2902011-05-09 15:17:40 -0700108 // If this is the first update check after a reboot following a previous
109 // update, generate an event containing the previous version number. If
110 // the previous version preference file doesn't exist the event is still
111 // generated with a previous version of 0.0.0.0 -- this is relevant for
112 // older clients or new installs. The previous version event is not sent
113 // for ping-only requests because they come before the client has
114 // rebooted.
115 string prev_version;
116 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
117 prev_version = "0.0.0.0";
118 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700119
Alex Vakulenko75039d72014-03-25 12:36:28 -0700120 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700121 " <event eventtype=\"%d\" eventresult=\"%d\" "
122 "previousversion=\"%s\"></event>\n",
123 OmahaEvent::kTypeUpdateComplete,
124 OmahaEvent::kResultSuccessReboot,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700125 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700126 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
127 << "Unable to reset the previous version.";
Darin Petkov95508da2011-01-05 12:42:29 -0800128 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700129 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800130 // The error code is an optional attribute so append it only if the result
131 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700132 string error_code;
133 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700134 error_code = base::StringPrintf(" errorcode=\"%d\"",
135 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700136 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700137 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700138 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700139 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700140 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700141
142 return app_body;
143}
144
Alex Deymo8e18f932015-03-27 16:16:59 -0700145// Returns the cohort* argument to include in the <app> tag for the passed
146// |arg_name| and |prefs_key|, if any. The return value is suitable to
147// concatenate to the list of arguments and includes a space at the end.
148string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700149 const string arg_name,
150 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700151 // There's nothing wrong with not having a given cohort setting, so we check
152 // existance first to avoid the warning log message.
153 if (!prefs->Exists(prefs_key))
154 return "";
155 string cohort_value;
156 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
157 return "";
158 // This is a sanity check to avoid sending a huge XML file back to Ohama due
159 // to a compromised stateful partition making the update check fail in low
160 // network environments envent after a reboot.
161 if (cohort_value.size() > 1024) {
162 LOG(WARNING) << "The omaha cohort setting " << arg_name
163 << " has a too big value, which must be an error or an "
164 "attacker trying to inhibit updates.";
165 return "";
166 }
167
Alex Deymob0d74eb2015-03-30 17:59:17 -0700168 string escaped_xml_value;
169 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
170 LOG(WARNING) << "The omaha cohort setting " << arg_name
171 << " is ASCII-7 invalid, ignoring it.";
172 return "";
173 }
174
Alex Deymo8e18f932015-03-27 16:16:59 -0700175 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700176 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700177}
178
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700179// Returns an XML that corresponds to the entire <app> node of the Omaha
180// request based on the given parameters.
181string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700182 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700183 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700184 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700185 int ping_active_days,
186 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800187 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700188 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700189 string app_body = GetAppBody(event, params, ping_only, include_ping,
190 ping_active_days, ping_roll_call_days,
191 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700192 string app_versions;
193
194 // If we are upgrading to a more stable channel and we are allowed to do
195 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
196 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700197 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700198 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
199 << "on downgrading to the version in the more stable channel";
200 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700201 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700202 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700203 app_versions = "version=\"" +
204 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700205 }
206
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700207 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700208 string app_channels =
209 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
210 if (params->current_channel() != download_channel) {
211 app_channels += "from_track=\"" + XmlEncodeWithDefault(
212 params->current_channel(), "") + "\" ";
213 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700214
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700215 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700216
David Zeuthen639aa362014-02-03 16:23:44 -0800217 // If install_date_days is not set (e.g. its value is -1 ), don't
218 // include the attribute.
219 string install_date_in_days_str = "";
220 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700221 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
222 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800223 }
224
Alex Deymo8e18f932015-03-27 16:16:59 -0700225 string app_cohort_args;
226 app_cohort_args += GetCohortArgXml(system_state->prefs(),
227 "cohort", kPrefsOmahaCohort);
228 app_cohort_args += GetCohortArgXml(system_state->prefs(),
229 "cohorthint", kPrefsOmahaCohortHint);
230 app_cohort_args += GetCohortArgXml(system_state->prefs(),
231 "cohortname", kPrefsOmahaCohortName);
232
Alex Deymob0d74eb2015-03-30 17:59:17 -0700233 string app_xml = " <app "
234 "appid=\"" + XmlEncodeWithDefault(params->GetAppId(), "") + "\" " +
235 app_cohort_args +
236 app_versions +
237 app_channels +
238 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
239 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
240 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
241 "delta_okay=\"" + delta_okay_str + "\" "
242 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
243 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
244 install_date_in_days_str +
245 ">\n" +
246 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700247 " </app>\n";
248
249 return app_xml;
250}
251
252// Returns an XML that corresponds to the entire <os> node of the Omaha
253// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700254string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700255 string os_xml =" <os "
256 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
257 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
258 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
259 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700260 return os_xml;
261}
262
263// Returns an XML that corresponds to the entire Omaha request based on the
264// given parameters.
265string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700266 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700267 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700268 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700269 int ping_active_days,
270 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800271 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700272 SystemState* system_state) {
273 string os_xml = GetOsXml(params);
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700274 string app_xml = GetAppXml(event, params, ping_only, include_ping,
275 ping_active_days, ping_roll_call_days,
276 install_date_in_days, system_state);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700277
Alex Vakulenko75039d72014-03-25 12:36:28 -0700278 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700279 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700280
281 string request_xml =
282 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700283 "<request protocol=\"3.0\" " + (
284 "version=\"" + XmlEncodeWithDefault(kGupdateVersion, "") + "\" "
285 "updaterversion=\"" + XmlEncodeWithDefault(kGupdateVersion,
286 "") + "\" " +
287 install_source +
288 "ismachine=\"1\">\n") +
289 os_xml +
290 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700291 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700292
293 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000294}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700295
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700296} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000297
David Zeuthene8ed8632014-07-24 13:38:10 -0400298// Struct used for holding data obtained when parsing the XML.
299struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400300 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
301
302 // Pointer to the expat XML_Parser object.
303 XML_Parser xml_parser;
304
David Zeuthene8ed8632014-07-24 13:38:10 -0400305 // This is the state of the parser as it's processing the XML.
306 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400307 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400308 string current_path;
309
310 // These are the values extracted from the XML.
Alex Deymo8e18f932015-03-27 16:16:59 -0700311 string app_cohort;
312 string app_cohorthint;
313 string app_cohortname;
314 bool app_cohort_set = false;
315 bool app_cohorthint_set = false;
316 bool app_cohortname_set = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400317 string updatecheck_status;
318 string updatecheck_poll_interval;
319 string daystart_elapsed_days;
320 string daystart_elapsed_seconds;
321 vector<string> url_codebase;
322 string package_name;
323 string package_size;
324 string manifest_version;
325 map<string, string> action_postinstall_attrs;
326};
327
328namespace {
329
330// Callback function invoked by expat.
331void ParserHandlerStart(void* user_data, const XML_Char* element,
332 const XML_Char** attr) {
333 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
334
335 if (data->failed)
336 return;
337
338 data->current_path += string("/") + element;
339
340 map<string, string> attrs;
341 if (attr != nullptr) {
342 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
343 string key = attr[n];
344 string value = attr[n + 1];
345 attrs[key] = value;
346 }
347 }
348
Alex Deymo8e18f932015-03-27 16:16:59 -0700349 if (data->current_path == "/response/app") {
350 if (attrs.find("cohort") != attrs.end()) {
351 data->app_cohort_set = true;
352 data->app_cohort = attrs["cohort"];
353 }
354 if (attrs.find("cohorthint") != attrs.end()) {
355 data->app_cohorthint_set = true;
356 data->app_cohorthint = attrs["cohorthint"];
357 }
358 if (attrs.find("cohortname") != attrs.end()) {
359 data->app_cohortname_set = true;
360 data->app_cohortname = attrs["cohortname"];
361 }
362 } else if (data->current_path == "/response/app/updatecheck") {
David Zeuthene8ed8632014-07-24 13:38:10 -0400363 // There is only supposed to be a single <updatecheck> element.
364 data->updatecheck_status = attrs["status"];
365 data->updatecheck_poll_interval = attrs["PollInterval"];
366 } else if (data->current_path == "/response/daystart") {
367 // Get the install-date.
368 data->daystart_elapsed_days = attrs["elapsed_days"];
369 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
370 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
371 // Look at all <url> elements.
372 data->url_codebase.push_back(attrs["codebase"]);
373 } else if (data->package_name.empty() && data->current_path ==
374 "/response/app/updatecheck/manifest/packages/package") {
375 // Only look at the first <package>.
376 data->package_name = attrs["name"];
377 data->package_size = attrs["size"];
378 } else if (data->current_path == "/response/app/updatecheck/manifest") {
379 // Get the version.
380 data->manifest_version = attrs[kTagVersion];
381 } else if (data->current_path ==
382 "/response/app/updatecheck/manifest/actions/action") {
383 // We only care about the postinstall action.
384 if (attrs["event"] == "postinstall") {
385 data->action_postinstall_attrs = attrs;
386 }
387 }
388}
389
390// Callback function invoked by expat.
391void ParserHandlerEnd(void* user_data, const XML_Char* element) {
392 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
393 if (data->failed)
394 return;
395
396 const string path_suffix = string("/") + element;
397
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700398 if (!base::EndsWith(data->current_path, path_suffix, true)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400399 LOG(ERROR) << "Unexpected end element '" << element
400 << "' with current_path='" << data->current_path << "'";
401 data->failed = true;
402 return;
403 }
404 data->current_path.resize(data->current_path.size() - path_suffix.size());
405}
406
David Zeuthenf3e28012014-08-26 18:23:52 -0400407// Callback function invoked by expat.
408//
409// This is called for entity declarations. Since Omaha is guaranteed
410// to never return any XML with entities our course of action is to
411// just stop parsing. This avoids potential resource exhaustion
412// problems AKA the "billion laughs". CVE-2013-0340.
413void ParserHandlerEntityDecl(void *user_data,
414 const XML_Char *entity_name,
415 int is_parameter_entity,
416 const XML_Char *value,
417 int value_length,
418 const XML_Char *base,
419 const XML_Char *system_id,
420 const XML_Char *public_id,
421 const XML_Char *notation_name) {
422 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
423
424 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
425 data->failed = true;
426 data->entity_decl = true;
427 XML_StopParser(data->xml_parser, false);
428}
429
David Zeuthene8ed8632014-07-24 13:38:10 -0400430} // namespace
431
Alex Deymob0d74eb2015-03-30 17:59:17 -0700432bool XmlEncode(const string& input, string* output) {
433 if (std::find_if(input.begin(), input.end(),
434 [](const char c){return c & 0x80;}) != input.end()) {
435 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
436 utils::HexDumpString(input);
437 return false;
438 }
Alex Deymocc457852015-06-18 18:35:50 -0700439 output->clear();
440 // We need at least input.size() space in the output, but the code below will
441 // handle it if we need more.
442 output->reserve(input.size());
443 for (char c : input) {
444 switch (c) {
445 case '\"':
446 output->append("&quot;");
447 break;
448 case '\'':
449 output->append("&apos;");
450 break;
451 case '&':
452 output->append("&amp;");
453 break;
454 case '<':
455 output->append("&lt;");
456 break;
457 case '>':
458 output->append("&gt;");
459 break;
460 default:
461 output->push_back(c);
462 }
463 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700464 return true;
465}
466
467string XmlEncodeWithDefault(const string& input, const string& default_value) {
468 string output;
469 if (XmlEncode(input, &output))
470 return output;
471 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000472}
473
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800474OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700475 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700476 HttpFetcher* http_fetcher,
477 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800478 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700479 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700480 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700481 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700482 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700483 ping_roll_call_days_(0) {
484 params_ = system_state->request_params();
485}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000486
Darin Petkov6a5b3222010-07-13 14:55:28 -0700487OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000488
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700489// Calculates the value to use for the ping days parameter.
490int OmahaRequestAction::CalculatePingDays(const string& key) {
491 int days = kNeverPinged;
492 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800493 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700494 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
495 if (days < 0) {
496 // If |days| is negative, then the system clock must have jumped
497 // back in time since the ping was sent. Mark the value so that
498 // it doesn't get sent to the server but we still update the
499 // last ping daystart preference. This way the next ping time
500 // will be correct, hopefully.
501 days = kPingTimeJump;
502 LOG(WARNING) <<
503 "System clock jumped back in time. Resetting ping daystarts.";
504 }
505 }
506 return days;
507}
508
509void OmahaRequestAction::InitPingDays() {
510 // We send pings only along with update checks, not with events.
511 if (IsEvent()) {
512 return;
513 }
514 // TODO(petkov): Figure a way to distinguish active use pings
515 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700516 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700517 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
518 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
519}
520
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700521bool OmahaRequestAction::ShouldPing() const {
522 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
523 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
524 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
525 if (powerwash_count > 0) {
526 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
527 << "powerwash_count is " << powerwash_count;
528 return false;
529 }
530 return true;
531 }
532 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
533}
534
David Zeuthen639aa362014-02-03 16:23:44 -0800535// static
536int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
537 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700538 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800539 return -1;
540
541 // If we have the value stored on disk, just return it.
542 int64_t stored_value;
543 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
544 // Convert and sanity-check.
545 int install_date_days = static_cast<int>(stored_value);
546 if (install_date_days >= 0)
547 return install_date_days;
548 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
549 << install_date_days << " looks suspicious.";
550 prefs->Delete(kPrefsInstallDateDays);
551 }
552
553 // Otherwise, if OOBE is not complete then do nothing and wait for
554 // ParseResponse() to call ParseInstallDate() and then
555 // PersistInstallDate() to set the kPrefsInstallDateDays state
556 // variable. Once that is done, we'll then report back in future
557 // Omaha requests. This works exactly because OOBE triggers an
558 // update check.
559 //
560 // However, if OOBE is complete and the kPrefsInstallDateDays state
561 // variable is not set, there are two possibilities
562 //
563 // 1. The update check in OOBE failed so we never got a response
564 // from Omaha (no network etc.); or
565 //
566 // 2. OOBE was done on an older version that didn't write to the
567 // kPrefsInstallDateDays state variable.
568 //
569 // In both cases, we approximate the install date by simply
570 // inspecting the timestamp of when OOBE happened.
571
572 Time time_of_oobe;
Alex Deymobccbc382014-04-03 13:38:55 -0700573 if (!system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800574 LOG(INFO) << "Not generating Omaha InstallData as we have "
575 << "no prefs file and OOBE is not complete.";
576 return -1;
577 }
578
579 int num_days;
580 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
581 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
582 << "as its value '" << utils::ToString(time_of_oobe)
583 << "' looks suspicious.";
584 return -1;
585 }
586
587 // Persist this to disk, for future use.
588 if (!OmahaRequestAction::PersistInstallDate(system_state,
589 num_days,
590 kProvisionedFromOOBEMarker))
591 return -1;
592
593 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
594 << num_days << " days";
595
596 return num_days;
597}
598
Darin Petkov6a5b3222010-07-13 14:55:28 -0700599void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000600 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700601 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700602 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700603 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700604 return;
605 }
David Zeuthen639aa362014-02-03 16:23:44 -0800606
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700607 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700608 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700609 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700610 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700611 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800612 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800613 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700614 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700615
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800616 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
617 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700618 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700619 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700620 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000621}
622
Darin Petkov6a5b3222010-07-13 14:55:28 -0700623void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000624 http_fetcher_->TerminateTransfer();
625}
626
627// We just store the response in the buffer. Once we've received all bytes,
628// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700629void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800630 const void* bytes,
631 size_t length) {
632 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
633 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000634}
635
636namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000637
638// Parses a 64 bit base-10 int from a string and returns it. Returns 0
639// on error. If the string contains "0", that's indistinguishable from
640// error.
641off_t ParseInt(const string& str) {
642 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700643 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000644 if (rc < 1) {
645 // failure
646 return 0;
647 }
648 return ret;
649}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700650
David Zeuthene8ed8632014-07-24 13:38:10 -0400651// Parses |str| and returns |true| if, and only if, its value is "true".
652bool ParseBool(const string& str) {
653 return str == "true";
654}
655
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700656// Update the last ping day preferences based on the server daystart
657// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400658bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700659 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400660 TEST_AND_RETURN_FALSE(
661 base::StringToInt64(parser_data->daystart_elapsed_seconds,
662 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700663 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
664
665 // Remember the local time that matches the server's last midnight
666 // time.
667 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
668 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
669 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
670 return true;
671}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700672} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000673
David Zeuthene8ed8632014-07-24 13:38:10 -0400674bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700675 OmahaResponse* output_object,
676 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400677 if (parser_data->updatecheck_status.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700678 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700679 return false;
680 }
681
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800682 // chromium-os:37289: The PollInterval is not supported by Omaha server
683 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700684 // slow down the request rate from the server-side. Note that the PollInterval
685 // is not persisted, so it has to be sent by the server on every response to
686 // guarantee that the scheduler uses this value (otherwise, if the device got
687 // rebooted after the last server-indicated value, it'll revert to the default
688 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
689 // based on the assumption that we perform an update check every hour so that
690 // the max value of 8 will roughly be equivalent to one work day. If we decide
691 // to use PollInterval permanently, we should update the
692 // max_update_checks_allowed to take PollInterval into account. Note: The
693 // parsing for PollInterval happens even before parsing of the status because
694 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400695 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700696 &output_object->poll_interval);
697
David Zeuthen639aa362014-02-03 16:23:44 -0800698 // Check for the "elapsed_days" attribute in the "daystart"
699 // element. This is the number of days since Jan 1 2007, 0:00
700 // PST. If we don't have a persisted value of the Omaha InstallDate,
701 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400702 if (ParseInstallDate(parser_data, output_object) &&
703 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800704 // Since output_object->install_date_days is never negative, the
705 // elapsed_days -> install-date calculation is reduced to simply
706 // rounding down to the nearest number divisible by 7.
707 int remainder = output_object->install_date_days % 7;
708 int install_date_days_rounded =
709 output_object->install_date_days - remainder;
710 if (PersistInstallDate(system_state_,
711 install_date_days_rounded,
712 kProvisionedFromOmahaResponse)) {
713 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
714 << install_date_days_rounded << " days";
715 }
716 }
717
Alex Deymo00d79ac2015-06-29 15:41:49 -0700718 // We persist the cohorts sent by omaha even if the status is "noupdate".
719 if (parser_data->app_cohort_set)
720 PersistCohortData(kPrefsOmahaCohort, parser_data->app_cohort);
721 if (parser_data->app_cohorthint_set)
722 PersistCohortData(kPrefsOmahaCohortHint, parser_data->app_cohorthint);
723 if (parser_data->app_cohortname_set)
724 PersistCohortData(kPrefsOmahaCohortName, parser_data->app_cohortname);
725
David Zeuthene8ed8632014-07-24 13:38:10 -0400726 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700727 return false;
728
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800729 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
730 // appends the package name to the URLs populated in this method.
David Zeuthene8ed8632014-07-24 13:38:10 -0400731 if (!ParseUrls(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700732 return false;
733
David Zeuthene8ed8632014-07-24 13:38:10 -0400734 if (!ParsePackage(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700735 return false;
736
David Zeuthene8ed8632014-07-24 13:38:10 -0400737 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700738 return false;
739
740 return true;
741}
742
David Zeuthene8ed8632014-07-24 13:38:10 -0400743bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700744 OmahaResponse* output_object,
745 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400746 const string& status = parser_data->updatecheck_status;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700747 if (status == "noupdate") {
748 LOG(INFO) << "No update.";
749 output_object->update_exists = false;
750 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700751 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700752 return false;
753 }
754
755 if (status != "ok") {
756 LOG(ERROR) << "Unknown Omaha response status: " << status;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700757 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700758 return false;
759 }
760
761 return true;
762}
763
David Zeuthene8ed8632014-07-24 13:38:10 -0400764bool OmahaRequestAction::ParseUrls(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700765 OmahaResponse* output_object,
766 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400767 if (parser_data->url_codebase.empty()) {
768 LOG(ERROR) << "No Omaha Response URLs";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700769 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700770 return false;
771 }
772
David Zeuthene8ed8632014-07-24 13:38:10 -0400773 LOG(INFO) << "Found " << parser_data->url_codebase.size() << " url(s)";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800774 output_object->payload_urls.clear();
David Zeuthene8ed8632014-07-24 13:38:10 -0400775 for (const auto& codebase : parser_data->url_codebase) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800776 if (codebase.empty()) {
777 LOG(ERROR) << "Omaha Response URL has empty codebase";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700778 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800779 return false;
780 }
781 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700782 }
783
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700784 return true;
785}
786
David Zeuthene8ed8632014-07-24 13:38:10 -0400787bool OmahaRequestAction::ParsePackage(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700788 OmahaResponse* output_object,
789 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400790 if (parser_data->package_name.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700791 LOG(ERROR) << "Omaha Response has empty package name";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700792 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700793 return false;
794 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800795
796 // Append the package name to each URL in our list so that we don't
797 // propagate the urlBase vs packageName distinctions beyond this point.
798 // From now on, we only need to use payload_urls.
David Zeuthene8ed8632014-07-24 13:38:10 -0400799 for (auto& payload_url : output_object->payload_urls)
800 payload_url += parser_data->package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700801
802 // Parse the payload size.
David Zeuthene8ed8632014-07-24 13:38:10 -0400803 off_t size = ParseInt(parser_data->package_size);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700804 if (size <= 0) {
805 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700806 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700807 return false;
808 }
809 output_object->size = size;
810
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800811 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700812
813 return true;
814}
815
David Zeuthene8ed8632014-07-24 13:38:10 -0400816bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700817 OmahaResponse* output_object,
818 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400819 output_object->version = parser_data->manifest_version;
Chris Sosa3b748432013-06-20 16:42:59 -0700820 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700821 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700822 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700823 return false;
824 }
825
826 LOG(INFO) << "Received omaha response to update to version "
827 << output_object->version;
828
David Zeuthene8ed8632014-07-24 13:38:10 -0400829 map<string, string> attrs = parser_data->action_postinstall_attrs;
830 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700831 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700832 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700833 return false;
834 }
835
David Zeuthene8ed8632014-07-24 13:38:10 -0400836 output_object->hash = attrs[kTagSha256];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700837 if (output_object->hash.empty()) {
838 LOG(ERROR) << "Omaha Response has empty sha256 value";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700839 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700840 return false;
841 }
842
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800843 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -0400844 output_object->more_info_url = attrs[kTagMoreInfo];
845 output_object->metadata_size = ParseInt(attrs[kTagMetadataSize]);
846 output_object->metadata_signature = attrs[kTagMetadataSignatureRsa];
847 output_object->prompt = ParseBool(attrs[kTagPrompt]);
848 output_object->deadline = attrs[kTagDeadline];
849 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700850 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -0400851 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700852 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -0400853 ParseBool(attrs[kTagDisableP2PForSharing]);
854 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800855
David Zeuthene8ed8632014-07-24 13:38:10 -0400856 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800857 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800858 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700859
David Zeuthene8ed8632014-07-24 13:38:10 -0400860 output_object->is_delta_payload = ParseBool(attrs[kTagIsDeltaPayload]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800861
862 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -0400863 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800864
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700865 return true;
866}
867
David Zeuthene8ed8632014-07-24 13:38:10 -0400868// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000869// and fill in the appropriate fields of the output object. Also, notifies
870// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700871void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
872 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000873 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800874 string current_response(response_buffer_.begin(), response_buffer_.end());
875 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700876
Gilad Arnold74b5f552014-10-07 08:17:16 -0700877 PayloadStateInterface* const payload_state = system_state_->payload_state();
878
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700879 // Events are best effort transactions -- assume they always succeed.
880 if (IsEvent()) {
881 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800882 if (event_->result == OmahaEvent::kResultError && successful &&
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700883 system_state_->hardware()->IsOfficialBuild()) {
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800884 LOG(INFO) << "Signalling Crash Reporter.";
885 utils::ScheduleCrashReporterUpload();
886 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700887 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700888 return;
889 }
890
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700891 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700892 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700893 int code = GetHTTPResponseCode();
894 // Makes sure we send sane error values.
895 if (code < 0 || code >= 1000) {
896 code = 999;
897 }
David Zeuthena99981f2013-04-29 13:42:47 -0700898 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700899 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000900 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700901 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000902
David Zeuthene8ed8632014-07-24 13:38:10 -0400903 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400904 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400905 XML_SetUserData(parser, &parser_data);
906 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400907 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800908 XML_Status res = XML_Parse(
909 parser,
910 reinterpret_cast<const char*>(response_buffer_.data()),
911 response_buffer_.size(),
912 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400913 XML_ParserFree(parser);
914
915 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700916 LOG(ERROR) << "Omaha response not valid XML: "
917 << XML_ErrorString(XML_GetErrorCode(parser))
918 << " at line " << XML_GetCurrentLineNumber(parser)
919 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400920 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
921 if (response_buffer_.empty()) {
922 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
923 } else if (parser_data.entity_decl) {
924 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
925 }
926 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000927 return;
928 }
929
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700930 // Update the last ping day preferences based on the server daystart response
931 // even if we didn't send a ping. Omaha always includes the daystart in the
932 // response, but log the error if it didn't.
933 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
934 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700935
Thieu Le116fda32011-04-19 11:01:54 -0700936 if (!HasOutputPipe()) {
937 // Just set success to whether or not the http transfer succeeded,
938 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700939 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700940 return;
941 }
942
Darin Petkov6a5b3222010-07-13 14:55:28 -0700943 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400944 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000945 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700946 output_object.update_exists = true;
947 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000948
Chris Sosa77f79e82014-06-02 18:16:24 -0700949 if (ShouldIgnoreUpdate(output_object)) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700950 output_object.update_exists = false;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700951 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700952 return;
953 }
954
David Zeuthen8f191b22013-08-06 12:27:50 -0700955 // If Omaha says to disable p2p, respect that
956 if (output_object.disable_p2p_for_downloading) {
957 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
958 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700959 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700960 }
961 if (output_object.disable_p2p_for_sharing) {
962 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
963 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700964 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700965 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800966
967 // Update the payload state with the current response. The payload state
968 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800969 // from what's stored already. We are updating the payload state as late
970 // as possible in this method so that if a new release gets pushed and then
971 // got pulled back due to some issues, we don't want to clear our internal
972 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800973 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800974
David Zeuthen8f191b22013-08-06 12:27:50 -0700975 // It could be we've already exceeded the deadline for when p2p is
976 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700977 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -0700978 payload_state->P2PNewAttempt();
979 if (!payload_state->P2PAttemptAllowed()) {
980 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
981 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700982 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700983 }
984 }
985
986 // From here on, we'll complete stuff in CompleteProcessing() so
987 // disable |completer| since we'll create a new one in that
988 // function.
989 completer.set_should_complete(false);
990
991 // If we're allowed to use p2p for downloading we do not pay
992 // attention to wall-clock-based waiting if the URL is indeed
993 // available via p2p. Therefore, check if the file is available via
994 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -0700995 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -0700996 LookupPayloadViaP2P(output_object);
997 } else {
998 CompleteProcessing();
999 }
1000}
1001
1002void OmahaRequestAction::CompleteProcessing() {
1003 ScopedActionCompleter completer(processor_, this);
1004 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1005 PayloadStateInterface* payload_state = system_state_->payload_state();
1006
1007 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001008 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001009 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001010 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001011 return;
1012 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001013
Chris Sosa20f005c2013-09-05 13:53:08 -07001014 if (payload_state->ShouldBackoffDownload()) {
1015 output_object.update_exists = false;
1016 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1017 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001018 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001019 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001020 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001021 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001022}
1023
1024void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1025 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1026 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001027 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001028 } else {
1029 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1030 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001031 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001032 }
1033 CompleteProcessing();
1034}
1035
1036void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001037 // If the device is in the middle of an update, the state variables
1038 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1039 // tracks the offset and length of the operation currently in
1040 // progress. The offset is based from the end of the manifest which
1041 // is kPrefsManifestMetadataSize bytes long.
1042 //
1043 // To make forward progress and avoid deadlocks, we need to find a
1044 // peer that has at least the entire operation we're currently
1045 // working on. Otherwise we may end up in a situation where two
1046 // devices bounce back and forth downloading from each other,
1047 // neither making any forward progress until one of them decides to
1048 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1049 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001050 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001051 int64_t manifest_metadata_size = 0;
1052 int64_t next_data_offset = 0;
1053 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001054 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001055 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1056 &manifest_metadata_size) &&
1057 manifest_metadata_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001058 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001059 &next_data_offset) &&
1060 next_data_offset != -1 &&
1061 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1062 &next_data_length)) {
1063 minimum_size = manifest_metadata_size + next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001064 }
1065
1066 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001067 if (system_state_->p2p_manager()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001068 LOG(INFO) << "Checking if payload is available via p2p, file_id="
1069 << file_id << " minimum_size=" << minimum_size;
1070 system_state_->p2p_manager()->LookupUrlForFile(
1071 file_id,
1072 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001073 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001074 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1075 base::Unretained(this)));
1076 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001077}
1078
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001079bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001080 if (params_->interactive()) {
1081 LOG(INFO) << "Not deferring download because update is interactive.";
1082 return false;
1083 }
1084
David Zeuthen8f191b22013-08-06 12:27:50 -07001085 // If we're using p2p to download _and_ we have a p2p URL, we never
1086 // defer the download. This is because the download will always
1087 // happen from a peer on the LAN and we've been waiting in line for
1088 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001089 const PayloadStateInterface* payload_state = system_state_->payload_state();
1090 if (payload_state->GetUsingP2PForDownloading() &&
1091 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001092 LOG(INFO) << "Download not deferred because download "
1093 << "will happen from a local peer (via p2p).";
1094 return false;
1095 }
1096
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001097 // We should defer the downloads only if we've first satisfied the
1098 // wall-clock-based-waiting period and then the update-check-based waiting
1099 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001100 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001101 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1102 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001103 return false;
1104 }
1105
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001106 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001107 case kWallClockWaitNotSatisfied:
1108 // We haven't even satisfied the first condition, passing the
1109 // wall-clock-based waiting period, so we should defer the downloads
1110 // until that happens.
1111 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1112 return true;
1113
1114 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1115 LOG(INFO) << "wall-clock-based-wait satisfied and "
1116 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001117 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001118
1119 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1120 // Wall-clock-based waiting period is satisfied, and it's determined
1121 // that we do not need the update-check-based wait. so no need to
1122 // defer downloads.
1123 LOG(INFO) << "wall-clock-based-wait satisfied and "
1124 << "update-check-based-wait is not required.";
1125 return false;
1126
1127 default:
1128 // Returning false for this default case so we err on the
1129 // side of downloading updates than deferring in case of any bugs.
1130 NOTREACHED();
1131 return false;
1132 }
1133}
1134
1135OmahaRequestAction::WallClockWaitResult
1136OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001137 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001138 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001139 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001140
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001141 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1142 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1143 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001144 // Note: This timestamp could be that of ANY update we saw in the past
1145 // (not necessarily this particular update we're considering to apply)
1146 // but never got to apply because of some reason (e.g. stop AU policy,
1147 // updates being pulled out from Omaha, changes in target version prefix,
1148 // new update being rolled out, etc.). But for the purposes of scattering
1149 // it doesn't matter which update the timestamp corresponds to. i.e.
1150 // the clock starts ticking the first time we see an update and we're
1151 // ready to apply when the random wait period is satisfied relative to
1152 // that first seen timestamp.
1153 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1154 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1155 << utils::ToString(update_first_seen_at);
1156 } else {
1157 // This seems like an unexpected error where the persisted value exists
1158 // but it's not readable for some reason. Just skip scattering in this
1159 // case to be safe.
1160 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1161 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1162 }
1163 } else {
1164 update_first_seen_at = Time::Now();
1165 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001166 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1167 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001168 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1169 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001170 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001171 // This seems like an unexpected error where the value cannot be
1172 // persisted for some reason. Just skip scattering in this
1173 // case to be safe.
1174 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1175 << utils::ToString(update_first_seen_at)
1176 << " cannot be persisted";
1177 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1178 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001179 }
1180
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001181 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001182 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001183 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001184
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001185 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001186 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001187 << ", Time Elapsed = "
1188 << utils::FormatSecs(elapsed_time.InSeconds())
1189 << ", MaxDaysToScatter = "
1190 << max_scatter_period.InDays();
1191
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001192 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001193 // The deadline is set for all rules which serve a delta update from a
1194 // previous FSI, which means this update will be applied mostly in OOBE
1195 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1196 // quickly.
1197 LOG(INFO) << "Not scattering as deadline flag is set";
1198 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1199 }
1200
1201 if (max_scatter_period.InDays() == 0) {
1202 // This means the Omaha rule creator decides that this rule
1203 // should not be scattered irrespective of the policy.
1204 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1205 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1206 }
1207
1208 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001209 // This means we've waited more than the upperbound wait in the rule
1210 // from the time we first saw a valid update available to us.
1211 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001212 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1213 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1214 }
1215
1216 // This means we are required to participate in scattering.
1217 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001218 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001219 if (remaining_wait_time.InSeconds() <= 0) {
1220 // Yes, it's our turn now.
1221 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1222
1223 // But we can't download until the update-check-count-based wait is also
1224 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001225 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001226 kWallClockWaitDoneButUpdateCheckWaitRequired :
1227 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1228 }
1229
1230 // Not our turn yet, so we have to wait until our turn to
1231 // help scatter the downloads across all clients of the enterprise.
1232 LOG(INFO) << "Update deferred for another "
1233 << utils::FormatSecs(remaining_wait_time.InSeconds())
1234 << " per policy.";
1235 return kWallClockWaitNotSatisfied;
1236}
1237
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001238bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001239 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001240
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001241 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1242 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1243 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001244 // We are unable to read the update check count from file for some reason.
1245 // So let's proceed anyway so as to not stall the update.
1246 LOG(ERROR) << "Unable to read update check count. "
1247 << "Skipping update-check-count-based-wait.";
1248 return true;
1249 }
1250 } else {
1251 // This file does not exist. This means we haven't started our update
1252 // check count down yet, so this is the right time to start the count down.
1253 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001254 params_->min_update_checks_needed(),
1255 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001256
1257 LOG(INFO) << "Randomly picked update check count value = "
1258 << update_check_count_value;
1259
1260 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001261 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1262 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001263 // We weren't able to write the update check count file for some reason.
1264 // So let's proceed anyway so as to not stall the update.
1265 LOG(ERROR) << "Unable to write update check count. "
1266 << "Skipping update-check-count-based-wait.";
1267 return true;
1268 }
1269 }
1270
1271 if (update_check_count_value == 0) {
1272 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1273 return true;
1274 }
1275
1276 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001277 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001278 // We err on the side of skipping scattering logic instead of stalling
1279 // a machine from receiving any updates in case of any unexpected state.
1280 LOG(ERROR) << "Invalid value for update check count detected. "
1281 << "Skipping update-check-count-based-wait.";
1282 return true;
1283 }
1284
1285 // Legal value, we need to wait for more update checks to happen
1286 // until this becomes 0.
1287 LOG(INFO) << "Deferring Omaha updates for another "
1288 << update_check_count_value
1289 << " update checks per policy";
1290 return false;
1291}
1292
David Zeuthen639aa362014-02-03 16:23:44 -08001293// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001294bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001295 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001296 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001297 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001298 &elapsed_days))
1299 return false;
1300
1301 if (elapsed_days < 0)
1302 return false;
1303
1304 output_object->install_date_days = elapsed_days;
1305 return true;
1306}
1307
1308// static
1309bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1310 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001311 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001312 return false;
1313
1314 return prefs->Exists(kPrefsInstallDateDays);
1315}
1316
1317// static
1318bool OmahaRequestAction::PersistInstallDate(
1319 SystemState *system_state,
1320 int install_date_days,
1321 InstallDateProvisioningSource source) {
1322 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1323
1324 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001325 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001326 return false;
1327
1328 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1329 return false;
1330
1331 string metric_name = "Installer.InstallDateProvisioningSource";
1332 system_state->metrics_lib()->SendEnumToUMA(
1333 metric_name,
David Zeuthen33bae492014-02-25 16:16:18 -08001334 static_cast<int>(source), // Sample.
1335 kProvisionedMax); // Maximum.
1336
1337 metric_name = metrics::kMetricInstallDateProvisioningSource;
1338 system_state->metrics_lib()->SendEnumToUMA(
1339 metric_name,
1340 static_cast<int>(source), // Sample.
1341 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001342
1343 return true;
1344}
1345
Alex Deymo8e18f932015-03-27 16:16:59 -07001346bool OmahaRequestAction::PersistCohortData(
1347 const string& prefs_key,
1348 const string& new_value) {
1349 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1350 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1351 return system_state_->prefs()->Delete(prefs_key);
1352 } else if (!new_value.empty()) {
1353 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1354 return system_state_->prefs()->SetString(prefs_key, new_value);
1355 }
1356 return true;
1357}
1358
David Zeuthen33bae492014-02-25 16:16:18 -08001359void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1360 // We only want to report this on "update check".
1361 if (ping_only_ || event_ != nullptr)
1362 return;
1363
1364 metrics::CheckResult result = metrics::CheckResult::kUnset;
1365 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1366 metrics::DownloadErrorCode download_error_code =
1367 metrics::DownloadErrorCode::kUnset;
1368
1369 // Regular update attempt.
1370 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001371 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001372 // OK, we parsed the response successfully but that does
1373 // necessarily mean that an update is available.
1374 if (HasOutputPipe()) {
1375 const OmahaResponse& response = GetOutputObject();
1376 if (response.update_exists) {
1377 result = metrics::CheckResult::kUpdateAvailable;
1378 reaction = metrics::CheckReaction::kUpdating;
1379 } else {
1380 result = metrics::CheckResult::kNoUpdateAvailable;
1381 }
1382 } else {
1383 result = metrics::CheckResult::kNoUpdateAvailable;
1384 }
1385 break;
1386
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001387 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001388 result = metrics::CheckResult::kUpdateAvailable;
1389 reaction = metrics::CheckReaction::kIgnored;
1390 break;
1391
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001392 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001393 result = metrics::CheckResult::kUpdateAvailable;
1394 reaction = metrics::CheckReaction::kDeferring;
1395 break;
1396
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001397 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001398 result = metrics::CheckResult::kUpdateAvailable;
1399 reaction = metrics::CheckReaction::kBackingOff;
1400 break;
1401
1402 default:
1403 // We report two flavors of errors, "Download errors" and "Parsing
1404 // error". Try to convert to the former and if that doesn't work
1405 // we know it's the latter.
1406 metrics::DownloadErrorCode tmp_error = utils::GetDownloadErrorCode(code);
1407 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1408 result = metrics::CheckResult::kDownloadError;
1409 download_error_code = tmp_error;
1410 } else {
1411 result = metrics::CheckResult::kParsingError;
1412 }
1413 break;
1414 }
1415
1416 metrics::ReportUpdateCheckMetrics(system_state_,
1417 result, reaction, download_error_code);
1418}
1419
Chris Sosa77f79e82014-06-02 18:16:24 -07001420bool OmahaRequestAction::ShouldIgnoreUpdate(
1421 const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001422 // Note: policy decision to not update to a version we rolled back from.
1423 string rollback_version =
1424 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001425 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001426 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001427 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001428 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1429 return true;
1430 }
1431 }
1432
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001433 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001434 LOG(INFO) << "Update is not allowed over current connection.";
1435 return true;
1436 }
1437
1438 // Note: We could technically delete the UpdateFirstSeenAt state when we
1439 // return true. If we do, it'll mean a device has to restart the
1440 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1441 // turned on again. On the other hand, it also increases the chance of update
1442 // starvation if an admin turns AU on/off more frequently. We choose to err on
1443 // the side of preventing starvation at the cost of not applying scattering in
1444 // those cases.
1445 return false;
1446}
1447
1448bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
1449 NetworkConnectionType type;
1450 NetworkTethering tethering;
1451 RealDBusWrapper dbus_iface;
Alex Deymof6ee0162015-07-31 12:35:22 -07001452 ConnectionManagerInterface* connection_manager =
1453 system_state_->connection_manager();
Chris Sosa77f79e82014-06-02 18:16:24 -07001454 if (!connection_manager->GetConnectionProperties(&dbus_iface,
1455 &type, &tethering)) {
1456 LOG(INFO) << "We could not determine our connection type. "
1457 << "Defaulting to allow updates.";
1458 return true;
1459 }
1460 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1461 LOG(INFO) << "We are connected via "
Alex Deymof6ee0162015-07-31 12:35:22 -07001462 << ConnectionManager::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001463 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1464 return is_allowed;
1465}
1466
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001467} // namespace chromeos_update_engine