blob: 9a0e3b21ca0e8e066e707c05913bfedf2ed7be1d [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"
Jay Srinivasand29695d2013-04-08 15:08:05 -070024#include "update_engine/constants.h"
J. Richard Barnette056b0ab2013-10-29 15:24:56 -070025#include "update_engine/hardware_interface.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070026#include "update_engine/omaha_hash_calculator.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070027#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070028#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080029#include "update_engine/payload_state_interface.h"
Darin Petkov1cbd78f2010-07-29 12:38:34 -070030#include "update_engine/prefs_interface.h"
Chris Sosa77f79e82014-06-02 18:16:24 -070031#include "update_engine/real_dbus_wrapper.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000032#include "update_engine/utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000033
Darin Petkov1cbd78f2010-07-29 12:38:34 -070034using base::Time;
35using base::TimeDelta;
David Zeuthene8ed8632014-07-24 13:38:10 -040036using std::map;
rspangler@google.com49fdf182009-10-10 00:57:34 +000037using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040038using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000039
40namespace chromeos_update_engine {
41
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080042// List of custom pair tags that we interpret in the Omaha Response:
43static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080044static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070045static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080046// Deprecated: "IsDelta"
47static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080048static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
49static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
50// Deprecated: "ManifestSignatureRsa"
51// Deprecated: "ManifestSize"
52static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
53static const char* kTagMetadataSize = "MetadataSize";
54static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070055// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080056static const char* kTagPrompt = "Prompt";
57static const char* kTagSha256 = "sha256";
David Zeuthen8f191b22013-08-06 12:27:50 -070058static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
59static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
David Zeuthene7f89172013-10-31 10:21:04 -070060static const char* kTagPublicKeyRsa = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080061
rspangler@google.com49fdf182009-10-10 00:57:34 +000062namespace {
63
Alex Vakulenkod2779df2014-06-16 13:19:00 -070064static const char* const kGupdateVersion = "ChromeOSUpdateEngine-0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +000065
Darin Petkov1cbd78f2010-07-29 12:38:34 -070066// Returns an XML ping element attribute assignment with attribute
67// |name| and value |ping_days| if |ping_days| has a value that needs
68// to be sent, or an empty string otherwise.
69string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -070070 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -070071 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -070072 return "";
73}
74
75// Returns an XML ping element if any of the elapsed days need to be
76// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -070077string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -070078 string ping_active = GetPingAttribute("a", ping_active_days);
79 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
80 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -070081 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -070082 ping_active.c_str(),
83 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -070084 }
85 return "";
86}
87
Jay Srinivasanae4697c2013-03-18 17:08:08 -070088// Returns an XML that goes into the body of the <app> element of the Omaha
89// request based on the given parameters.
90string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070091 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -070092 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -070093 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -070094 int ping_active_days,
95 int ping_roll_call_days,
96 PrefsInterface* prefs) {
97 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -070098 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -070099 if (include_ping)
100 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700101 if (!ping_only) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700102 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700103 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700104 "></updatecheck>\n",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700105 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700106
Darin Petkov265f2902011-05-09 15:17:40 -0700107 // If this is the first update check after a reboot following a previous
108 // update, generate an event containing the previous version number. If
109 // the previous version preference file doesn't exist the event is still
110 // generated with a previous version of 0.0.0.0 -- this is relevant for
111 // older clients or new installs. The previous version event is not sent
112 // for ping-only requests because they come before the client has
113 // rebooted.
114 string prev_version;
115 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
116 prev_version = "0.0.0.0";
117 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700118
Alex Vakulenko75039d72014-03-25 12:36:28 -0700119 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700120 " <event eventtype=\"%d\" eventresult=\"%d\" "
121 "previousversion=\"%s\"></event>\n",
122 OmahaEvent::kTypeUpdateComplete,
123 OmahaEvent::kResultSuccessReboot,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700124 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700125 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
126 << "Unable to reset the previous version.";
Darin Petkov95508da2011-01-05 12:42:29 -0800127 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700128 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800129 // The error code is an optional attribute so append it only if the result
130 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700131 string error_code;
132 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700133 error_code = base::StringPrintf(" errorcode=\"%d\"",
134 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700135 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700136 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700137 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700138 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700139 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700140
141 return app_body;
142}
143
Alex Deymo8e18f932015-03-27 16:16:59 -0700144// Returns the cohort* argument to include in the <app> tag for the passed
145// |arg_name| and |prefs_key|, if any. The return value is suitable to
146// concatenate to the list of arguments and includes a space at the end.
147string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700148 const string arg_name,
149 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700150 // There's nothing wrong with not having a given cohort setting, so we check
151 // existance first to avoid the warning log message.
152 if (!prefs->Exists(prefs_key))
153 return "";
154 string cohort_value;
155 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
156 return "";
157 // This is a sanity check to avoid sending a huge XML file back to Ohama due
158 // to a compromised stateful partition making the update check fail in low
159 // network environments envent after a reboot.
160 if (cohort_value.size() > 1024) {
161 LOG(WARNING) << "The omaha cohort setting " << arg_name
162 << " has a too big value, which must be an error or an "
163 "attacker trying to inhibit updates.";
164 return "";
165 }
166
Alex Deymob0d74eb2015-03-30 17:59:17 -0700167 string escaped_xml_value;
168 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
169 LOG(WARNING) << "The omaha cohort setting " << arg_name
170 << " is ASCII-7 invalid, ignoring it.";
171 return "";
172 }
173
Alex Deymo8e18f932015-03-27 16:16:59 -0700174 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700175 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700176}
177
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700178// Returns an XML that corresponds to the entire <app> node of the Omaha
179// request based on the given parameters.
180string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700181 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700182 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700183 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700184 int ping_active_days,
185 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800186 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700187 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700188 string app_body = GetAppBody(event, params, ping_only, include_ping,
189 ping_active_days, ping_roll_call_days,
190 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700191 string app_versions;
192
193 // If we are upgrading to a more stable channel and we are allowed to do
194 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
195 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700196 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700197 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
198 << "on downgrading to the version in the more stable channel";
199 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700200 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700201 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700202 app_versions = "version=\"" +
203 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700204 }
205
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700206 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700207 string app_channels =
208 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
209 if (params->current_channel() != download_channel) {
210 app_channels += "from_track=\"" + XmlEncodeWithDefault(
211 params->current_channel(), "") + "\" ";
212 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700213
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700214 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700215
David Zeuthen639aa362014-02-03 16:23:44 -0800216 // If install_date_days is not set (e.g. its value is -1 ), don't
217 // include the attribute.
218 string install_date_in_days_str = "";
219 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700220 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
221 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800222 }
223
Alex Deymo8e18f932015-03-27 16:16:59 -0700224 string app_cohort_args;
225 app_cohort_args += GetCohortArgXml(system_state->prefs(),
226 "cohort", kPrefsOmahaCohort);
227 app_cohort_args += GetCohortArgXml(system_state->prefs(),
228 "cohorthint", kPrefsOmahaCohortHint);
229 app_cohort_args += GetCohortArgXml(system_state->prefs(),
230 "cohortname", kPrefsOmahaCohortName);
231
Alex Deymob0d74eb2015-03-30 17:59:17 -0700232 string app_xml = " <app "
233 "appid=\"" + XmlEncodeWithDefault(params->GetAppId(), "") + "\" " +
234 app_cohort_args +
235 app_versions +
236 app_channels +
237 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
238 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
239 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
240 "delta_okay=\"" + delta_okay_str + "\" "
241 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
242 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
243 install_date_in_days_str +
244 ">\n" +
245 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700246 " </app>\n";
247
248 return app_xml;
249}
250
251// Returns an XML that corresponds to the entire <os> node of the Omaha
252// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700253string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700254 string os_xml =" <os "
255 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
256 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
257 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
258 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700259 return os_xml;
260}
261
262// Returns an XML that corresponds to the entire Omaha request based on the
263// given parameters.
264string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700265 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700266 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700267 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700268 int ping_active_days,
269 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800270 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700271 SystemState* system_state) {
272 string os_xml = GetOsXml(params);
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700273 string app_xml = GetAppXml(event, params, ping_only, include_ping,
274 ping_active_days, ping_roll_call_days,
275 install_date_in_days, system_state);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700276
Alex Vakulenko75039d72014-03-25 12:36:28 -0700277 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700278 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700279
280 string request_xml =
281 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700282 "<request protocol=\"3.0\" " + (
283 "version=\"" + XmlEncodeWithDefault(kGupdateVersion, "") + "\" "
284 "updaterversion=\"" + XmlEncodeWithDefault(kGupdateVersion,
285 "") + "\" " +
286 install_source +
287 "ismachine=\"1\">\n") +
288 os_xml +
289 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700290 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700291
292 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000293}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700294
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700295} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000296
David Zeuthene8ed8632014-07-24 13:38:10 -0400297// Struct used for holding data obtained when parsing the XML.
298struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400299 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
300
301 // Pointer to the expat XML_Parser object.
302 XML_Parser xml_parser;
303
David Zeuthene8ed8632014-07-24 13:38:10 -0400304 // This is the state of the parser as it's processing the XML.
305 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400306 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400307 string current_path;
308
309 // These are the values extracted from the XML.
Alex Deymo8e18f932015-03-27 16:16:59 -0700310 string app_cohort;
311 string app_cohorthint;
312 string app_cohortname;
313 bool app_cohort_set = false;
314 bool app_cohorthint_set = false;
315 bool app_cohortname_set = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400316 string updatecheck_status;
317 string updatecheck_poll_interval;
318 string daystart_elapsed_days;
319 string daystart_elapsed_seconds;
320 vector<string> url_codebase;
321 string package_name;
322 string package_size;
323 string manifest_version;
324 map<string, string> action_postinstall_attrs;
325};
326
327namespace {
328
329// Callback function invoked by expat.
330void ParserHandlerStart(void* user_data, const XML_Char* element,
331 const XML_Char** attr) {
332 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
333
334 if (data->failed)
335 return;
336
337 data->current_path += string("/") + element;
338
339 map<string, string> attrs;
340 if (attr != nullptr) {
341 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
342 string key = attr[n];
343 string value = attr[n + 1];
344 attrs[key] = value;
345 }
346 }
347
Alex Deymo8e18f932015-03-27 16:16:59 -0700348 if (data->current_path == "/response/app") {
349 if (attrs.find("cohort") != attrs.end()) {
350 data->app_cohort_set = true;
351 data->app_cohort = attrs["cohort"];
352 }
353 if (attrs.find("cohorthint") != attrs.end()) {
354 data->app_cohorthint_set = true;
355 data->app_cohorthint = attrs["cohorthint"];
356 }
357 if (attrs.find("cohortname") != attrs.end()) {
358 data->app_cohortname_set = true;
359 data->app_cohortname = attrs["cohortname"];
360 }
361 } else if (data->current_path == "/response/app/updatecheck") {
David Zeuthene8ed8632014-07-24 13:38:10 -0400362 // There is only supposed to be a single <updatecheck> element.
363 data->updatecheck_status = attrs["status"];
364 data->updatecheck_poll_interval = attrs["PollInterval"];
365 } else if (data->current_path == "/response/daystart") {
366 // Get the install-date.
367 data->daystart_elapsed_days = attrs["elapsed_days"];
368 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
369 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
370 // Look at all <url> elements.
371 data->url_codebase.push_back(attrs["codebase"]);
372 } else if (data->package_name.empty() && data->current_path ==
373 "/response/app/updatecheck/manifest/packages/package") {
374 // Only look at the first <package>.
375 data->package_name = attrs["name"];
376 data->package_size = attrs["size"];
377 } else if (data->current_path == "/response/app/updatecheck/manifest") {
378 // Get the version.
379 data->manifest_version = attrs[kTagVersion];
380 } else if (data->current_path ==
381 "/response/app/updatecheck/manifest/actions/action") {
382 // We only care about the postinstall action.
383 if (attrs["event"] == "postinstall") {
384 data->action_postinstall_attrs = attrs;
385 }
386 }
387}
388
389// Callback function invoked by expat.
390void ParserHandlerEnd(void* user_data, const XML_Char* element) {
391 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
392 if (data->failed)
393 return;
394
395 const string path_suffix = string("/") + element;
396
397 if (!EndsWith(data->current_path, path_suffix, true)) {
398 LOG(ERROR) << "Unexpected end element '" << element
399 << "' with current_path='" << data->current_path << "'";
400 data->failed = true;
401 return;
402 }
403 data->current_path.resize(data->current_path.size() - path_suffix.size());
404}
405
David Zeuthenf3e28012014-08-26 18:23:52 -0400406// Callback function invoked by expat.
407//
408// This is called for entity declarations. Since Omaha is guaranteed
409// to never return any XML with entities our course of action is to
410// just stop parsing. This avoids potential resource exhaustion
411// problems AKA the "billion laughs". CVE-2013-0340.
412void ParserHandlerEntityDecl(void *user_data,
413 const XML_Char *entity_name,
414 int is_parameter_entity,
415 const XML_Char *value,
416 int value_length,
417 const XML_Char *base,
418 const XML_Char *system_id,
419 const XML_Char *public_id,
420 const XML_Char *notation_name) {
421 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
422
423 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
424 data->failed = true;
425 data->entity_decl = true;
426 XML_StopParser(data->xml_parser, false);
427}
428
David Zeuthene8ed8632014-07-24 13:38:10 -0400429} // namespace
430
Alex Deymob0d74eb2015-03-30 17:59:17 -0700431bool XmlEncode(const string& input, string* output) {
432 if (std::find_if(input.begin(), input.end(),
433 [](const char c){return c & 0x80;}) != input.end()) {
434 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
435 utils::HexDumpString(input);
436 return false;
437 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400438 gchar* escaped = g_markup_escape_text(input.c_str(), input.size());
Alex Deymob0d74eb2015-03-30 17:59:17 -0700439 if (escaped == nullptr)
440 return false;
441 *output = string(escaped);
David Zeuthene8ed8632014-07-24 13:38:10 -0400442 g_free(escaped);
Alex Deymob0d74eb2015-03-30 17:59:17 -0700443 return true;
444}
445
446string XmlEncodeWithDefault(const string& input, const string& default_value) {
447 string output;
448 if (XmlEncode(input, &output))
449 return output;
450 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000451}
452
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800453OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700454 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700455 HttpFetcher* http_fetcher,
456 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800457 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700458 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700459 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700460 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700461 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700462 ping_roll_call_days_(0) {
463 params_ = system_state->request_params();
464}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000465
Darin Petkov6a5b3222010-07-13 14:55:28 -0700466OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000467
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700468// Calculates the value to use for the ping days parameter.
469int OmahaRequestAction::CalculatePingDays(const string& key) {
470 int days = kNeverPinged;
471 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800472 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700473 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
474 if (days < 0) {
475 // If |days| is negative, then the system clock must have jumped
476 // back in time since the ping was sent. Mark the value so that
477 // it doesn't get sent to the server but we still update the
478 // last ping daystart preference. This way the next ping time
479 // will be correct, hopefully.
480 days = kPingTimeJump;
481 LOG(WARNING) <<
482 "System clock jumped back in time. Resetting ping daystarts.";
483 }
484 }
485 return days;
486}
487
488void OmahaRequestAction::InitPingDays() {
489 // We send pings only along with update checks, not with events.
490 if (IsEvent()) {
491 return;
492 }
493 // TODO(petkov): Figure a way to distinguish active use pings
494 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700495 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700496 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
497 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
498}
499
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700500bool OmahaRequestAction::ShouldPing() const {
501 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
502 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
503 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
504 if (powerwash_count > 0) {
505 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
506 << "powerwash_count is " << powerwash_count;
507 return false;
508 }
509 return true;
510 }
511 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
512}
513
David Zeuthen639aa362014-02-03 16:23:44 -0800514// static
515int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
516 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700517 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800518 return -1;
519
520 // If we have the value stored on disk, just return it.
521 int64_t stored_value;
522 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
523 // Convert and sanity-check.
524 int install_date_days = static_cast<int>(stored_value);
525 if (install_date_days >= 0)
526 return install_date_days;
527 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
528 << install_date_days << " looks suspicious.";
529 prefs->Delete(kPrefsInstallDateDays);
530 }
531
532 // Otherwise, if OOBE is not complete then do nothing and wait for
533 // ParseResponse() to call ParseInstallDate() and then
534 // PersistInstallDate() to set the kPrefsInstallDateDays state
535 // variable. Once that is done, we'll then report back in future
536 // Omaha requests. This works exactly because OOBE triggers an
537 // update check.
538 //
539 // However, if OOBE is complete and the kPrefsInstallDateDays state
540 // variable is not set, there are two possibilities
541 //
542 // 1. The update check in OOBE failed so we never got a response
543 // from Omaha (no network etc.); or
544 //
545 // 2. OOBE was done on an older version that didn't write to the
546 // kPrefsInstallDateDays state variable.
547 //
548 // In both cases, we approximate the install date by simply
549 // inspecting the timestamp of when OOBE happened.
550
551 Time time_of_oobe;
Alex Deymobccbc382014-04-03 13:38:55 -0700552 if (!system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800553 LOG(INFO) << "Not generating Omaha InstallData as we have "
554 << "no prefs file and OOBE is not complete.";
555 return -1;
556 }
557
558 int num_days;
559 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
560 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
561 << "as its value '" << utils::ToString(time_of_oobe)
562 << "' looks suspicious.";
563 return -1;
564 }
565
566 // Persist this to disk, for future use.
567 if (!OmahaRequestAction::PersistInstallDate(system_state,
568 num_days,
569 kProvisionedFromOOBEMarker))
570 return -1;
571
572 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
573 << num_days << " days";
574
575 return num_days;
576}
577
Darin Petkov6a5b3222010-07-13 14:55:28 -0700578void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000579 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700580 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700581 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700582 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700583 return;
584 }
David Zeuthen639aa362014-02-03 16:23:44 -0800585
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700586 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700587 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700588 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700589 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700590 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800591 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800592 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700593 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700594
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800595 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
596 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700597 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700598 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700599 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000600}
601
Darin Petkov6a5b3222010-07-13 14:55:28 -0700602void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000603 http_fetcher_->TerminateTransfer();
604}
605
606// We just store the response in the buffer. Once we've received all bytes,
607// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700608void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800609 const void* bytes,
610 size_t length) {
611 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
612 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000613}
614
615namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000616
617// Parses a 64 bit base-10 int from a string and returns it. Returns 0
618// on error. If the string contains "0", that's indistinguishable from
619// error.
620off_t ParseInt(const string& str) {
621 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700622 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000623 if (rc < 1) {
624 // failure
625 return 0;
626 }
627 return ret;
628}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700629
David Zeuthene8ed8632014-07-24 13:38:10 -0400630// Parses |str| and returns |true| if, and only if, its value is "true".
631bool ParseBool(const string& str) {
632 return str == "true";
633}
634
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700635// Update the last ping day preferences based on the server daystart
636// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400637bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700638 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400639 TEST_AND_RETURN_FALSE(
640 base::StringToInt64(parser_data->daystart_elapsed_seconds,
641 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700642 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
643
644 // Remember the local time that matches the server's last midnight
645 // time.
646 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
647 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
648 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
649 return true;
650}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700651} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000652
David Zeuthene8ed8632014-07-24 13:38:10 -0400653bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700654 OmahaResponse* output_object,
655 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400656 if (parser_data->updatecheck_status.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700657 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700658 return false;
659 }
660
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800661 // chromium-os:37289: The PollInterval is not supported by Omaha server
662 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700663 // slow down the request rate from the server-side. Note that the PollInterval
664 // is not persisted, so it has to be sent by the server on every response to
665 // guarantee that the scheduler uses this value (otherwise, if the device got
666 // rebooted after the last server-indicated value, it'll revert to the default
667 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
668 // based on the assumption that we perform an update check every hour so that
669 // the max value of 8 will roughly be equivalent to one work day. If we decide
670 // to use PollInterval permanently, we should update the
671 // max_update_checks_allowed to take PollInterval into account. Note: The
672 // parsing for PollInterval happens even before parsing of the status because
673 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400674 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700675 &output_object->poll_interval);
676
David Zeuthen639aa362014-02-03 16:23:44 -0800677 // Check for the "elapsed_days" attribute in the "daystart"
678 // element. This is the number of days since Jan 1 2007, 0:00
679 // PST. If we don't have a persisted value of the Omaha InstallDate,
680 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400681 if (ParseInstallDate(parser_data, output_object) &&
682 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800683 // Since output_object->install_date_days is never negative, the
684 // elapsed_days -> install-date calculation is reduced to simply
685 // rounding down to the nearest number divisible by 7.
686 int remainder = output_object->install_date_days % 7;
687 int install_date_days_rounded =
688 output_object->install_date_days - remainder;
689 if (PersistInstallDate(system_state_,
690 install_date_days_rounded,
691 kProvisionedFromOmahaResponse)) {
692 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
693 << install_date_days_rounded << " days";
694 }
695 }
696
David Zeuthene8ed8632014-07-24 13:38:10 -0400697 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700698 return false;
699
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800700 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
701 // appends the package name to the URLs populated in this method.
David Zeuthene8ed8632014-07-24 13:38:10 -0400702 if (!ParseUrls(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700703 return false;
704
David Zeuthene8ed8632014-07-24 13:38:10 -0400705 if (!ParsePackage(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700706 return false;
707
David Zeuthene8ed8632014-07-24 13:38:10 -0400708 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700709 return false;
710
Alex Deymo8e18f932015-03-27 16:16:59 -0700711 if (parser_data->app_cohort_set)
712 PersistCohortData(kPrefsOmahaCohort, parser_data->app_cohort);
713 if (parser_data->app_cohorthint_set)
714 PersistCohortData(kPrefsOmahaCohortHint, parser_data->app_cohorthint);
715 if (parser_data->app_cohortname_set)
716 PersistCohortData(kPrefsOmahaCohortName, parser_data->app_cohortname);
717
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700718 return true;
719}
720
David Zeuthene8ed8632014-07-24 13:38:10 -0400721bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700722 OmahaResponse* output_object,
723 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400724 const string& status = parser_data->updatecheck_status;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700725 if (status == "noupdate") {
726 LOG(INFO) << "No update.";
727 output_object->update_exists = false;
728 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700729 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700730 return false;
731 }
732
733 if (status != "ok") {
734 LOG(ERROR) << "Unknown Omaha response status: " << status;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700735 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700736 return false;
737 }
738
739 return true;
740}
741
David Zeuthene8ed8632014-07-24 13:38:10 -0400742bool OmahaRequestAction::ParseUrls(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700743 OmahaResponse* output_object,
744 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400745 if (parser_data->url_codebase.empty()) {
746 LOG(ERROR) << "No Omaha Response URLs";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700747 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700748 return false;
749 }
750
David Zeuthene8ed8632014-07-24 13:38:10 -0400751 LOG(INFO) << "Found " << parser_data->url_codebase.size() << " url(s)";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800752 output_object->payload_urls.clear();
David Zeuthene8ed8632014-07-24 13:38:10 -0400753 for (const auto& codebase : parser_data->url_codebase) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800754 if (codebase.empty()) {
755 LOG(ERROR) << "Omaha Response URL has empty codebase";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700756 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800757 return false;
758 }
759 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700760 }
761
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700762 return true;
763}
764
David Zeuthene8ed8632014-07-24 13:38:10 -0400765bool OmahaRequestAction::ParsePackage(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700766 OmahaResponse* output_object,
767 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400768 if (parser_data->package_name.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700769 LOG(ERROR) << "Omaha Response has empty package name";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700770 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700771 return false;
772 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800773
774 // Append the package name to each URL in our list so that we don't
775 // propagate the urlBase vs packageName distinctions beyond this point.
776 // From now on, we only need to use payload_urls.
David Zeuthene8ed8632014-07-24 13:38:10 -0400777 for (auto& payload_url : output_object->payload_urls)
778 payload_url += parser_data->package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700779
780 // Parse the payload size.
David Zeuthene8ed8632014-07-24 13:38:10 -0400781 off_t size = ParseInt(parser_data->package_size);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700782 if (size <= 0) {
783 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700784 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700785 return false;
786 }
787 output_object->size = size;
788
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800789 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700790
791 return true;
792}
793
David Zeuthene8ed8632014-07-24 13:38:10 -0400794bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700795 OmahaResponse* output_object,
796 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400797 output_object->version = parser_data->manifest_version;
Chris Sosa3b748432013-06-20 16:42:59 -0700798 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700799 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700800 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700801 return false;
802 }
803
804 LOG(INFO) << "Received omaha response to update to version "
805 << output_object->version;
806
David Zeuthene8ed8632014-07-24 13:38:10 -0400807 map<string, string> attrs = parser_data->action_postinstall_attrs;
808 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700809 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700810 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700811 return false;
812 }
813
David Zeuthene8ed8632014-07-24 13:38:10 -0400814 output_object->hash = attrs[kTagSha256];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700815 if (output_object->hash.empty()) {
816 LOG(ERROR) << "Omaha Response has empty sha256 value";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700817 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700818 return false;
819 }
820
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800821 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -0400822 output_object->more_info_url = attrs[kTagMoreInfo];
823 output_object->metadata_size = ParseInt(attrs[kTagMetadataSize]);
824 output_object->metadata_signature = attrs[kTagMetadataSignatureRsa];
825 output_object->prompt = ParseBool(attrs[kTagPrompt]);
826 output_object->deadline = attrs[kTagDeadline];
827 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700828 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -0400829 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700830 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -0400831 ParseBool(attrs[kTagDisableP2PForSharing]);
832 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800833
David Zeuthene8ed8632014-07-24 13:38:10 -0400834 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800835 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800836 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700837
David Zeuthene8ed8632014-07-24 13:38:10 -0400838 output_object->is_delta_payload = ParseBool(attrs[kTagIsDeltaPayload]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800839
840 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -0400841 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800842
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700843 return true;
844}
845
David Zeuthene8ed8632014-07-24 13:38:10 -0400846// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000847// and fill in the appropriate fields of the output object. Also, notifies
848// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700849void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
850 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000851 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800852 string current_response(response_buffer_.begin(), response_buffer_.end());
853 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700854
Gilad Arnold74b5f552014-10-07 08:17:16 -0700855 PayloadStateInterface* const payload_state = system_state_->payload_state();
856
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700857 // Events are best effort transactions -- assume they always succeed.
858 if (IsEvent()) {
859 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800860 if (event_->result == OmahaEvent::kResultError && successful &&
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700861 system_state_->hardware()->IsOfficialBuild()) {
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800862 LOG(INFO) << "Signalling Crash Reporter.";
863 utils::ScheduleCrashReporterUpload();
864 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700865 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700866 return;
867 }
868
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700869 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700870 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700871 int code = GetHTTPResponseCode();
872 // Makes sure we send sane error values.
873 if (code < 0 || code >= 1000) {
874 code = 999;
875 }
David Zeuthena99981f2013-04-29 13:42:47 -0700876 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700877 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000878 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700879 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000880
David Zeuthene8ed8632014-07-24 13:38:10 -0400881 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400882 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400883 XML_SetUserData(parser, &parser_data);
884 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400885 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800886 XML_Status res = XML_Parse(
887 parser,
888 reinterpret_cast<const char*>(response_buffer_.data()),
889 response_buffer_.size(),
890 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400891 XML_ParserFree(parser);
892
893 if (res != XML_STATUS_OK || parser_data.failed) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000894 LOG(ERROR) << "Omaha response not valid XML";
David Zeuthenf3e28012014-08-26 18:23:52 -0400895 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
896 if (response_buffer_.empty()) {
897 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
898 } else if (parser_data.entity_decl) {
899 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
900 }
901 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000902 return;
903 }
904
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700905 // Update the last ping day preferences based on the server daystart response
906 // even if we didn't send a ping. Omaha always includes the daystart in the
907 // response, but log the error if it didn't.
908 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
909 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700910
Thieu Le116fda32011-04-19 11:01:54 -0700911 if (!HasOutputPipe()) {
912 // Just set success to whether or not the http transfer succeeded,
913 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700914 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700915 return;
916 }
917
Darin Petkov6a5b3222010-07-13 14:55:28 -0700918 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400919 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000920 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700921 output_object.update_exists = true;
922 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000923
Chris Sosa77f79e82014-06-02 18:16:24 -0700924 if (ShouldIgnoreUpdate(output_object)) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700925 output_object.update_exists = false;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700926 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700927 return;
928 }
929
David Zeuthen8f191b22013-08-06 12:27:50 -0700930 // If Omaha says to disable p2p, respect that
931 if (output_object.disable_p2p_for_downloading) {
932 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
933 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700934 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700935 }
936 if (output_object.disable_p2p_for_sharing) {
937 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
938 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700939 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700940 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800941
942 // Update the payload state with the current response. The payload state
943 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800944 // from what's stored already. We are updating the payload state as late
945 // as possible in this method so that if a new release gets pushed and then
946 // got pulled back due to some issues, we don't want to clear our internal
947 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800948 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800949
David Zeuthen8f191b22013-08-06 12:27:50 -0700950 // It could be we've already exceeded the deadline for when p2p is
951 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700952 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -0700953 payload_state->P2PNewAttempt();
954 if (!payload_state->P2PAttemptAllowed()) {
955 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
956 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700957 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700958 }
959 }
960
961 // From here on, we'll complete stuff in CompleteProcessing() so
962 // disable |completer| since we'll create a new one in that
963 // function.
964 completer.set_should_complete(false);
965
966 // If we're allowed to use p2p for downloading we do not pay
967 // attention to wall-clock-based waiting if the URL is indeed
968 // available via p2p. Therefore, check if the file is available via
969 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -0700970 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -0700971 LookupPayloadViaP2P(output_object);
972 } else {
973 CompleteProcessing();
974 }
975}
976
977void OmahaRequestAction::CompleteProcessing() {
978 ScopedActionCompleter completer(processor_, this);
979 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
980 PayloadStateInterface* payload_state = system_state_->payload_state();
981
982 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800983 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -0700984 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700985 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -0800986 return;
987 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700988
Chris Sosa20f005c2013-09-05 13:53:08 -0700989 if (payload_state->ShouldBackoffDownload()) {
990 output_object.update_exists = false;
991 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
992 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700993 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -0700994 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700995 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700996 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -0700997}
998
999void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1000 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1001 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001002 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001003 } else {
1004 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1005 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001006 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001007 }
1008 CompleteProcessing();
1009}
1010
1011void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001012 // If the device is in the middle of an update, the state variables
1013 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1014 // tracks the offset and length of the operation currently in
1015 // progress. The offset is based from the end of the manifest which
1016 // is kPrefsManifestMetadataSize bytes long.
1017 //
1018 // To make forward progress and avoid deadlocks, we need to find a
1019 // peer that has at least the entire operation we're currently
1020 // working on. Otherwise we may end up in a situation where two
1021 // devices bounce back and forth downloading from each other,
1022 // neither making any forward progress until one of them decides to
1023 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1024 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001025 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001026 int64_t manifest_metadata_size = 0;
1027 int64_t next_data_offset = 0;
1028 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001029 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001030 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1031 &manifest_metadata_size) &&
1032 manifest_metadata_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001033 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001034 &next_data_offset) &&
1035 next_data_offset != -1 &&
1036 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1037 &next_data_length)) {
1038 minimum_size = manifest_metadata_size + next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001039 }
1040
1041 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001042 if (system_state_->p2p_manager()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001043 LOG(INFO) << "Checking if payload is available via p2p, file_id="
1044 << file_id << " minimum_size=" << minimum_size;
1045 system_state_->p2p_manager()->LookupUrlForFile(
1046 file_id,
1047 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001048 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001049 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1050 base::Unretained(this)));
1051 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001052}
1053
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001054bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001055 if (params_->interactive()) {
1056 LOG(INFO) << "Not deferring download because update is interactive.";
1057 return false;
1058 }
1059
David Zeuthen8f191b22013-08-06 12:27:50 -07001060 // If we're using p2p to download _and_ we have a p2p URL, we never
1061 // defer the download. This is because the download will always
1062 // happen from a peer on the LAN and we've been waiting in line for
1063 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001064 const PayloadStateInterface* payload_state = system_state_->payload_state();
1065 if (payload_state->GetUsingP2PForDownloading() &&
1066 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001067 LOG(INFO) << "Download not deferred because download "
1068 << "will happen from a local peer (via p2p).";
1069 return false;
1070 }
1071
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001072 // We should defer the downloads only if we've first satisfied the
1073 // wall-clock-based-waiting period and then the update-check-based waiting
1074 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001075 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001076 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1077 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001078 return false;
1079 }
1080
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001081 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001082 case kWallClockWaitNotSatisfied:
1083 // We haven't even satisfied the first condition, passing the
1084 // wall-clock-based waiting period, so we should defer the downloads
1085 // until that happens.
1086 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1087 return true;
1088
1089 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1090 LOG(INFO) << "wall-clock-based-wait satisfied and "
1091 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001092 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001093
1094 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1095 // Wall-clock-based waiting period is satisfied, and it's determined
1096 // that we do not need the update-check-based wait. so no need to
1097 // defer downloads.
1098 LOG(INFO) << "wall-clock-based-wait satisfied and "
1099 << "update-check-based-wait is not required.";
1100 return false;
1101
1102 default:
1103 // Returning false for this default case so we err on the
1104 // side of downloading updates than deferring in case of any bugs.
1105 NOTREACHED();
1106 return false;
1107 }
1108}
1109
1110OmahaRequestAction::WallClockWaitResult
1111OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001112 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001113 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001114 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001115
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001116 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1117 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1118 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001119 // Note: This timestamp could be that of ANY update we saw in the past
1120 // (not necessarily this particular update we're considering to apply)
1121 // but never got to apply because of some reason (e.g. stop AU policy,
1122 // updates being pulled out from Omaha, changes in target version prefix,
1123 // new update being rolled out, etc.). But for the purposes of scattering
1124 // it doesn't matter which update the timestamp corresponds to. i.e.
1125 // the clock starts ticking the first time we see an update and we're
1126 // ready to apply when the random wait period is satisfied relative to
1127 // that first seen timestamp.
1128 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1129 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1130 << utils::ToString(update_first_seen_at);
1131 } else {
1132 // This seems like an unexpected error where the persisted value exists
1133 // but it's not readable for some reason. Just skip scattering in this
1134 // case to be safe.
1135 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1136 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1137 }
1138 } else {
1139 update_first_seen_at = Time::Now();
1140 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001141 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1142 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001143 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1144 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001145 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001146 // This seems like an unexpected error where the value cannot be
1147 // persisted for some reason. Just skip scattering in this
1148 // case to be safe.
1149 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1150 << utils::ToString(update_first_seen_at)
1151 << " cannot be persisted";
1152 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1153 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001154 }
1155
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001156 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001157 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001158 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001159
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001160 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001161 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001162 << ", Time Elapsed = "
1163 << utils::FormatSecs(elapsed_time.InSeconds())
1164 << ", MaxDaysToScatter = "
1165 << max_scatter_period.InDays();
1166
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001167 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001168 // The deadline is set for all rules which serve a delta update from a
1169 // previous FSI, which means this update will be applied mostly in OOBE
1170 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1171 // quickly.
1172 LOG(INFO) << "Not scattering as deadline flag is set";
1173 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1174 }
1175
1176 if (max_scatter_period.InDays() == 0) {
1177 // This means the Omaha rule creator decides that this rule
1178 // should not be scattered irrespective of the policy.
1179 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1180 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1181 }
1182
1183 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001184 // This means we've waited more than the upperbound wait in the rule
1185 // from the time we first saw a valid update available to us.
1186 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001187 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1188 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1189 }
1190
1191 // This means we are required to participate in scattering.
1192 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001193 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001194 if (remaining_wait_time.InSeconds() <= 0) {
1195 // Yes, it's our turn now.
1196 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1197
1198 // But we can't download until the update-check-count-based wait is also
1199 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001200 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001201 kWallClockWaitDoneButUpdateCheckWaitRequired :
1202 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1203 }
1204
1205 // Not our turn yet, so we have to wait until our turn to
1206 // help scatter the downloads across all clients of the enterprise.
1207 LOG(INFO) << "Update deferred for another "
1208 << utils::FormatSecs(remaining_wait_time.InSeconds())
1209 << " per policy.";
1210 return kWallClockWaitNotSatisfied;
1211}
1212
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001213bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001214 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001215
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001216 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1217 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1218 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001219 // We are unable to read the update check count from file for some reason.
1220 // So let's proceed anyway so as to not stall the update.
1221 LOG(ERROR) << "Unable to read update check count. "
1222 << "Skipping update-check-count-based-wait.";
1223 return true;
1224 }
1225 } else {
1226 // This file does not exist. This means we haven't started our update
1227 // check count down yet, so this is the right time to start the count down.
1228 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001229 params_->min_update_checks_needed(),
1230 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001231
1232 LOG(INFO) << "Randomly picked update check count value = "
1233 << update_check_count_value;
1234
1235 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001236 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1237 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001238 // We weren't able to write the update check count file for some reason.
1239 // So let's proceed anyway so as to not stall the update.
1240 LOG(ERROR) << "Unable to write update check count. "
1241 << "Skipping update-check-count-based-wait.";
1242 return true;
1243 }
1244 }
1245
1246 if (update_check_count_value == 0) {
1247 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1248 return true;
1249 }
1250
1251 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001252 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001253 // We err on the side of skipping scattering logic instead of stalling
1254 // a machine from receiving any updates in case of any unexpected state.
1255 LOG(ERROR) << "Invalid value for update check count detected. "
1256 << "Skipping update-check-count-based-wait.";
1257 return true;
1258 }
1259
1260 // Legal value, we need to wait for more update checks to happen
1261 // until this becomes 0.
1262 LOG(INFO) << "Deferring Omaha updates for another "
1263 << update_check_count_value
1264 << " update checks per policy";
1265 return false;
1266}
1267
David Zeuthen639aa362014-02-03 16:23:44 -08001268// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001269bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001270 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001271 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001272 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001273 &elapsed_days))
1274 return false;
1275
1276 if (elapsed_days < 0)
1277 return false;
1278
1279 output_object->install_date_days = elapsed_days;
1280 return true;
1281}
1282
1283// static
1284bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1285 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001286 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001287 return false;
1288
1289 return prefs->Exists(kPrefsInstallDateDays);
1290}
1291
1292// static
1293bool OmahaRequestAction::PersistInstallDate(
1294 SystemState *system_state,
1295 int install_date_days,
1296 InstallDateProvisioningSource source) {
1297 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1298
1299 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001300 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001301 return false;
1302
1303 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1304 return false;
1305
1306 string metric_name = "Installer.InstallDateProvisioningSource";
1307 system_state->metrics_lib()->SendEnumToUMA(
1308 metric_name,
David Zeuthen33bae492014-02-25 16:16:18 -08001309 static_cast<int>(source), // Sample.
1310 kProvisionedMax); // Maximum.
1311
1312 metric_name = metrics::kMetricInstallDateProvisioningSource;
1313 system_state->metrics_lib()->SendEnumToUMA(
1314 metric_name,
1315 static_cast<int>(source), // Sample.
1316 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001317
1318 return true;
1319}
1320
Alex Deymo8e18f932015-03-27 16:16:59 -07001321bool OmahaRequestAction::PersistCohortData(
1322 const string& prefs_key,
1323 const string& new_value) {
1324 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1325 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1326 return system_state_->prefs()->Delete(prefs_key);
1327 } else if (!new_value.empty()) {
1328 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1329 return system_state_->prefs()->SetString(prefs_key, new_value);
1330 }
1331 return true;
1332}
1333
David Zeuthen33bae492014-02-25 16:16:18 -08001334void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1335 // We only want to report this on "update check".
1336 if (ping_only_ || event_ != nullptr)
1337 return;
1338
1339 metrics::CheckResult result = metrics::CheckResult::kUnset;
1340 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1341 metrics::DownloadErrorCode download_error_code =
1342 metrics::DownloadErrorCode::kUnset;
1343
1344 // Regular update attempt.
1345 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001346 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001347 // OK, we parsed the response successfully but that does
1348 // necessarily mean that an update is available.
1349 if (HasOutputPipe()) {
1350 const OmahaResponse& response = GetOutputObject();
1351 if (response.update_exists) {
1352 result = metrics::CheckResult::kUpdateAvailable;
1353 reaction = metrics::CheckReaction::kUpdating;
1354 } else {
1355 result = metrics::CheckResult::kNoUpdateAvailable;
1356 }
1357 } else {
1358 result = metrics::CheckResult::kNoUpdateAvailable;
1359 }
1360 break;
1361
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001362 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001363 result = metrics::CheckResult::kUpdateAvailable;
1364 reaction = metrics::CheckReaction::kIgnored;
1365 break;
1366
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001367 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001368 result = metrics::CheckResult::kUpdateAvailable;
1369 reaction = metrics::CheckReaction::kDeferring;
1370 break;
1371
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001372 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001373 result = metrics::CheckResult::kUpdateAvailable;
1374 reaction = metrics::CheckReaction::kBackingOff;
1375 break;
1376
1377 default:
1378 // We report two flavors of errors, "Download errors" and "Parsing
1379 // error". Try to convert to the former and if that doesn't work
1380 // we know it's the latter.
1381 metrics::DownloadErrorCode tmp_error = utils::GetDownloadErrorCode(code);
1382 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1383 result = metrics::CheckResult::kDownloadError;
1384 download_error_code = tmp_error;
1385 } else {
1386 result = metrics::CheckResult::kParsingError;
1387 }
1388 break;
1389 }
1390
1391 metrics::ReportUpdateCheckMetrics(system_state_,
1392 result, reaction, download_error_code);
1393}
1394
Chris Sosa77f79e82014-06-02 18:16:24 -07001395bool OmahaRequestAction::ShouldIgnoreUpdate(
1396 const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001397 // Note: policy decision to not update to a version we rolled back from.
1398 string rollback_version =
1399 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001400 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001401 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001402 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001403 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1404 return true;
1405 }
1406 }
1407
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001408 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001409 LOG(INFO) << "Update is not allowed over current connection.";
1410 return true;
1411 }
1412
1413 // Note: We could technically delete the UpdateFirstSeenAt state when we
1414 // return true. If we do, it'll mean a device has to restart the
1415 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1416 // turned on again. On the other hand, it also increases the chance of update
1417 // starvation if an admin turns AU on/off more frequently. We choose to err on
1418 // the side of preventing starvation at the cost of not applying scattering in
1419 // those cases.
1420 return false;
1421}
1422
1423bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
1424 NetworkConnectionType type;
1425 NetworkTethering tethering;
1426 RealDBusWrapper dbus_iface;
1427 ConnectionManager* connection_manager = system_state_->connection_manager();
1428 if (!connection_manager->GetConnectionProperties(&dbus_iface,
1429 &type, &tethering)) {
1430 LOG(INFO) << "We could not determine our connection type. "
1431 << "Defaulting to allow updates.";
1432 return true;
1433 }
1434 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1435 LOG(INFO) << "We are connected via "
1436 << connection_manager->StringForConnectionType(type)
1437 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1438 return is_allowed;
1439}
1440
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001441} // namespace chromeos_update_engine