blob: 1a0756665d07de756db08c1694bdf271ff51593c [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
rspangler@google.com49fdf182009-10-10 00:57:34 +00009#include <sstream>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070010#include <string>
rspangler@google.com49fdf182009-10-10 00:57:34 +000011
David Zeuthen8f191b22013-08-06 12:27:50 -070012#include <base/bind.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070013#include <base/logging.h>
14#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070015#include <base/strings/string_number_conversions.h>
16#include <base/strings/string_util.h>
17#include <base/strings/stringprintf.h>
18#include <base/time/time.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000019#include <libxml/xpath.h>
20#include <libxml/xpathInternals.h>
21
22#include "update_engine/action_pipe.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070023#include "update_engine/constants.h"
J. Richard Barnette056b0ab2013-10-29 15:24:56 -070024#include "update_engine/hardware_interface.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070025#include "update_engine/omaha_hash_calculator.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070026#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070027#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080028#include "update_engine/payload_state_interface.h"
Darin Petkov1cbd78f2010-07-29 12:38:34 -070029#include "update_engine/prefs_interface.h"
Chris Sosa77f79e82014-06-02 18:16:24 -070030#include "update_engine/real_dbus_wrapper.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000031#include "update_engine/utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000032
Darin Petkov1cbd78f2010-07-29 12:38:34 -070033using base::Time;
34using base::TimeDelta;
rspangler@google.com49fdf182009-10-10 00:57:34 +000035using std::string;
36
37namespace chromeos_update_engine {
38
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080039// List of custom pair tags that we interpret in the Omaha Response:
40static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080041static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070042static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080043// Deprecated: "IsDelta"
44static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080045static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
46static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
47// Deprecated: "ManifestSignatureRsa"
48// Deprecated: "ManifestSize"
49static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
50static const char* kTagMetadataSize = "MetadataSize";
51static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070052// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080053static const char* kTagPrompt = "Prompt";
54static const char* kTagSha256 = "sha256";
David Zeuthen8f191b22013-08-06 12:27:50 -070055static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
56static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
David Zeuthene7f89172013-10-31 10:21:04 -070057static const char* kTagPublicKeyRsa = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080058
rspangler@google.com49fdf182009-10-10 00:57:34 +000059namespace {
60
Alex Vakulenkod2779df2014-06-16 13:19:00 -070061static const char* const kGupdateVersion = "ChromeOSUpdateEngine-0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +000062
63// This is handy for passing strings into libxml2
64#define ConstXMLStr(x) (reinterpret_cast<const xmlChar*>(x))
65
Ben Chan075248b2014-04-24 12:04:14 -070066// These are for scoped_ptr with a custom free function to be specified.
rspangler@google.com49fdf182009-10-10 00:57:34 +000067class ScopedPtrXmlDocFree {
68 public:
69 inline void operator()(void* x) const {
70 xmlFreeDoc(reinterpret_cast<xmlDoc*>(x));
71 }
72};
73class ScopedPtrXmlFree {
74 public:
75 inline void operator()(void* x) const {
76 xmlFree(x);
77 }
78};
79class ScopedPtrXmlXPathObjectFree {
80 public:
81 inline void operator()(void* x) const {
82 xmlXPathFreeObject(reinterpret_cast<xmlXPathObject*>(x));
83 }
84};
85class ScopedPtrXmlXPathContextFree {
86 public:
87 inline void operator()(void* x) const {
88 xmlXPathFreeContext(reinterpret_cast<xmlXPathContext*>(x));
89 }
90};
91
Darin Petkov1cbd78f2010-07-29 12:38:34 -070092// Returns true if |ping_days| has a value that needs to be sent,
93// false otherwise.
94bool ShouldPing(int ping_days) {
95 return ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged;
96}
97
98// Returns an XML ping element attribute assignment with attribute
99// |name| and value |ping_days| if |ping_days| has a value that needs
100// to be sent, or an empty string otherwise.
101string GetPingAttribute(const string& name, int ping_days) {
102 if (ShouldPing(ping_days)) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700103 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700104 }
105 return "";
106}
107
108// Returns an XML ping element if any of the elapsed days need to be
109// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700110string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700111 string ping_active = GetPingAttribute("a", ping_active_days);
112 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
113 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700114 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700115 ping_active.c_str(),
116 ping_roll_call.c_str());
117 }
118 return "";
119}
120
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700121// Returns an XML that goes into the body of the <app> element of the Omaha
122// request based on the given parameters.
123string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700124 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700125 bool ping_only,
126 int ping_active_days,
127 int ping_roll_call_days,
128 PrefsInterface* prefs) {
129 string app_body;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700130 if (event == NULL) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700131 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700132 if (!ping_only) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700133 // not passing update_disabled to Omaha because we want to
134 // get the update and report with UpdateDeferred result so that
135 // borgmon charts show up updates that are deferred. This is also
136 // the expected behavior when we move to Omaha v3.0 protocol, so it'll
137 // be consistent.
Alex Vakulenko75039d72014-03-25 12:36:28 -0700138 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700139 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700140 "></updatecheck>\n",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700141 XmlEncode(params->target_version_prefix()).c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700142
Darin Petkov265f2902011-05-09 15:17:40 -0700143 // If this is the first update check after a reboot following a previous
144 // update, generate an event containing the previous version number. If
145 // the previous version preference file doesn't exist the event is still
146 // generated with a previous version of 0.0.0.0 -- this is relevant for
147 // older clients or new installs. The previous version event is not sent
148 // for ping-only requests because they come before the client has
149 // rebooted.
150 string prev_version;
151 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
152 prev_version = "0.0.0.0";
153 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700154
Alex Vakulenko75039d72014-03-25 12:36:28 -0700155 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700156 " <event eventtype=\"%d\" eventresult=\"%d\" "
157 "previousversion=\"%s\"></event>\n",
158 OmahaEvent::kTypeUpdateComplete,
159 OmahaEvent::kResultSuccessReboot,
160 XmlEncode(prev_version).c_str());
161 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
162 << "Unable to reset the previous version.";
Darin Petkov95508da2011-01-05 12:42:29 -0800163 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700164 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800165 // The error code is an optional attribute so append it only if the result
166 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700167 string error_code;
168 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700169 error_code = base::StringPrintf(" errorcode=\"%d\"",
170 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700171 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700172 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700173 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700174 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700175 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700176
177 return app_body;
178}
179
180// Returns an XML that corresponds to the entire <app> node of the Omaha
181// request based on the given parameters.
182string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700183 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700184 bool ping_only,
185 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) {
189 string app_body = GetAppBody(event, params, ping_only, ping_active_days,
190 ping_roll_call_days, system_state->prefs());
191 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=\"" +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700200 XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700201 } else {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700202 app_versions = "version=\"" + XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700203 }
204
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700205 string download_channel = params->download_channel();
206 string app_channels = "track=\"" + XmlEncode(download_channel) + "\" ";
207 if (params->current_channel() != download_channel)
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700208 app_channels +=
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700209 "from_track=\"" + XmlEncode(params->current_channel()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700210
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700211 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700212
David Zeuthen639aa362014-02-03 16:23:44 -0800213 // If install_date_days is not set (e.g. its value is -1 ), don't
214 // include the attribute.
215 string install_date_in_days_str = "";
216 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700217 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
218 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800219 }
220
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700221 string app_xml =
Jay Srinivasandb0acdf2013-04-02 14:47:45 -0700222 " <app appid=\"" + XmlEncode(params->GetAppId()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700223 app_versions +
224 app_channels +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700225 "lang=\"" + XmlEncode(params->app_lang()) + "\" " +
226 "board=\"" + XmlEncode(params->os_board()) + "\" " +
227 "hardware_class=\"" + XmlEncode(params->hwid()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700228 "delta_okay=\"" + delta_okay_str + "\" "
Chris Sosac1972482013-04-30 22:31:10 -0700229 "fw_version=\"" + XmlEncode(params->fw_version()) + "\" " +
230 "ec_version=\"" + XmlEncode(params->ec_version()) + "\" " +
David Zeuthen639aa362014-02-03 16:23:44 -0800231 install_date_in_days_str +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700232 ">\n" +
233 app_body +
234 " </app>\n";
235
236 return app_xml;
237}
238
239// Returns an XML that corresponds to the entire <os> node of the Omaha
240// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700241string GetOsXml(OmahaRequestParams* params) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700242 string os_xml =
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700243 " <os version=\"" + XmlEncode(params->os_version()) + "\" " +
244 "platform=\"" + XmlEncode(params->os_platform()) + "\" " +
245 "sp=\"" + XmlEncode(params->os_sp()) + "\">"
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700246 "</os>\n";
247 return os_xml;
248}
249
250// Returns an XML that corresponds to the entire Omaha request based on the
251// given parameters.
252string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700253 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700254 bool ping_only,
255 int ping_active_days,
256 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800257 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700258 SystemState* system_state) {
259 string os_xml = GetOsXml(params);
260 string app_xml = GetAppXml(event, params, ping_only, ping_active_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800261 ping_roll_call_days, install_date_in_days,
262 system_state);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700263
Alex Vakulenko75039d72014-03-25 12:36:28 -0700264 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700265 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700266
267 string request_xml =
268 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700269 "<request protocol=\"3.0\" "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700270 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
271 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" " +
272 install_source +
273 "ismachine=\"1\">\n" +
274 os_xml +
275 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700276 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700277
278 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000279}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700280
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700281} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000282
283// Encodes XML entities in a given string with libxml2. input must be
284// UTF-8 formatted. Output will be UTF-8 formatted.
285string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700286 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
287 // // cpu, considering creating one and caching it.
Ben Chan075248b2014-04-24 12:04:14 -0700288 // scoped_ptr<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
Darin Petkov6a5b3222010-07-13 14:55:28 -0700289 // xmlNewDoc(ConstXMLStr("1.0")));
290 // if (!xml_doc.get()) {
291 // LOG(ERROR) << "Unable to create xmlDoc";
292 // return "";
293 // }
Ben Chan075248b2014-04-24 12:04:14 -0700294 scoped_ptr<xmlChar, ScopedPtrXmlFree> str(
rspangler@google.com49fdf182009-10-10 00:57:34 +0000295 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
296 return string(reinterpret_cast<const char *>(str.get()));
297}
298
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800299OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700300 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700301 HttpFetcher* http_fetcher,
302 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800303 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700304 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700305 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700306 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700307 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700308 ping_roll_call_days_(0) {
309 params_ = system_state->request_params();
310}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000311
Darin Petkov6a5b3222010-07-13 14:55:28 -0700312OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000313
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700314// Calculates the value to use for the ping days parameter.
315int OmahaRequestAction::CalculatePingDays(const string& key) {
316 int days = kNeverPinged;
317 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800318 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700319 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
320 if (days < 0) {
321 // If |days| is negative, then the system clock must have jumped
322 // back in time since the ping was sent. Mark the value so that
323 // it doesn't get sent to the server but we still update the
324 // last ping daystart preference. This way the next ping time
325 // will be correct, hopefully.
326 days = kPingTimeJump;
327 LOG(WARNING) <<
328 "System clock jumped back in time. Resetting ping daystarts.";
329 }
330 }
331 return days;
332}
333
334void OmahaRequestAction::InitPingDays() {
335 // We send pings only along with update checks, not with events.
336 if (IsEvent()) {
337 return;
338 }
339 // TODO(petkov): Figure a way to distinguish active use pings
340 // vs. roll call pings. Currently, the two pings are identical. A
341 // fix needs to change this code as well as UpdateLastPingDays.
342 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
343 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
344}
345
David Zeuthen639aa362014-02-03 16:23:44 -0800346// static
347int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
348 PrefsInterface* prefs = system_state->prefs();
349 if (prefs == NULL)
350 return -1;
351
352 // If we have the value stored on disk, just return it.
353 int64_t stored_value;
354 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
355 // Convert and sanity-check.
356 int install_date_days = static_cast<int>(stored_value);
357 if (install_date_days >= 0)
358 return install_date_days;
359 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
360 << install_date_days << " looks suspicious.";
361 prefs->Delete(kPrefsInstallDateDays);
362 }
363
364 // Otherwise, if OOBE is not complete then do nothing and wait for
365 // ParseResponse() to call ParseInstallDate() and then
366 // PersistInstallDate() to set the kPrefsInstallDateDays state
367 // variable. Once that is done, we'll then report back in future
368 // Omaha requests. This works exactly because OOBE triggers an
369 // update check.
370 //
371 // However, if OOBE is complete and the kPrefsInstallDateDays state
372 // variable is not set, there are two possibilities
373 //
374 // 1. The update check in OOBE failed so we never got a response
375 // from Omaha (no network etc.); or
376 //
377 // 2. OOBE was done on an older version that didn't write to the
378 // kPrefsInstallDateDays state variable.
379 //
380 // In both cases, we approximate the install date by simply
381 // inspecting the timestamp of when OOBE happened.
382
383 Time time_of_oobe;
Alex Deymobccbc382014-04-03 13:38:55 -0700384 if (!system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800385 LOG(INFO) << "Not generating Omaha InstallData as we have "
386 << "no prefs file and OOBE is not complete.";
387 return -1;
388 }
389
390 int num_days;
391 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
392 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
393 << "as its value '" << utils::ToString(time_of_oobe)
394 << "' looks suspicious.";
395 return -1;
396 }
397
398 // Persist this to disk, for future use.
399 if (!OmahaRequestAction::PersistInstallDate(system_state,
400 num_days,
401 kProvisionedFromOOBEMarker))
402 return -1;
403
404 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
405 << num_days << " days";
406
407 return num_days;
408}
409
Darin Petkov6a5b3222010-07-13 14:55:28 -0700410void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000411 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700412 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700413 if (ping_only_ &&
414 !ShouldPing(ping_active_days_) &&
415 !ShouldPing(ping_roll_call_days_)) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700416 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700417 return;
418 }
David Zeuthen639aa362014-02-03 16:23:44 -0800419
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700420 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700421 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700422 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700423 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800424 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800425 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700426 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700427
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800428 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
429 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700430 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700431 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700432 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000433}
434
Darin Petkov6a5b3222010-07-13 14:55:28 -0700435void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000436 http_fetcher_->TerminateTransfer();
437}
438
439// We just store the response in the buffer. Once we've received all bytes,
440// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700441void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
442 const char* bytes,
443 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000444 response_buffer_.reserve(response_buffer_.size() + length);
445 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
446}
447
448namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000449// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
450// on the returned object.
451// This code is roughly based on the libxml tutorial at:
452// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700453xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000454 xmlXPathObject* result = NULL;
455
Ben Chan075248b2014-04-24 12:04:14 -0700456 scoped_ptr<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
rspangler@google.com49fdf182009-10-10 00:57:34 +0000457 xmlXPathNewContext(doc));
458 if (!context.get()) {
459 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
460 return NULL;
461 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000462
463 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000464 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700465 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000466 return NULL;
467 }
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700468 if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700469 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000470 xmlXPathFreeObject(result);
471 return NULL;
472 }
473 return result;
474}
475
476// Returns the string value of a named attribute on a node, or empty string
477// if no such node exists. If the attribute exists and has a value of
478// empty string, there's no way to distinguish that from the attribute
479// not existing.
480string XmlGetProperty(xmlNode* node, const char* name) {
481 if (!xmlHasProp(node, ConstXMLStr(name)))
482 return "";
Ben Chan075248b2014-04-24 12:04:14 -0700483 scoped_ptr<xmlChar, ScopedPtrXmlFree> str(
rspangler@google.com49fdf182009-10-10 00:57:34 +0000484 xmlGetProp(node, ConstXMLStr(name)));
485 string ret(reinterpret_cast<const char *>(str.get()));
486 return ret;
487}
488
489// Parses a 64 bit base-10 int from a string and returns it. Returns 0
490// on error. If the string contains "0", that's indistinguishable from
491// error.
492off_t ParseInt(const string& str) {
493 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700494 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000495 if (rc < 1) {
496 // failure
497 return 0;
498 }
499 return ret;
500}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700501
502// Update the last ping day preferences based on the server daystart
503// response. Returns true on success, false otherwise.
504bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700505 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700506
Ben Chan075248b2014-04-24 12:04:14 -0700507 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700508 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700509 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
510 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
511 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
512 xmlNode* daystart_node = nodeset->nodeTab[0];
513 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
514 ConstXMLStr("elapsed_seconds")));
515
516 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700517 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
518 "elapsed_seconds"),
519 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700520 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
521
522 // Remember the local time that matches the server's last midnight
523 // time.
524 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
525 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
526 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
527 return true;
528}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700529} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000530
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700531bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
532 OmahaResponse* output_object,
533 ScopedActionCompleter* completer) {
534 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
535
Ben Chan075248b2014-04-24 12:04:14 -0700536 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700537 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
538 if (!xpath_nodeset.get()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700539 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700540 return false;
541 }
542
543 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
544 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
545 CHECK_GE(nodeset->nodeNr, 1);
546 xmlNode* update_check_node = nodeset->nodeTab[0];
547
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800548 // chromium-os:37289: The PollInterval is not supported by Omaha server
549 // currently. But still keeping this existing code in case we ever decide to
550 // slow down the request rate from the server-side. Note that the
551 // PollInterval is not persisted, so it has to be sent by the server on every
552 // response to guarantee that the UpdateCheckScheduler uses this value
553 // (otherwise, if the device got rebooted after the last server-indicated
554 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
555 // value for the scattering logic is based on the assumption that we perform
556 // an update check every hour so that the max value of 8 will roughly be
557 // equivalent to one work day. If we decide to use PollInterval permanently,
558 // we should update the max_update_checks_allowed to take PollInterval into
559 // account. Note: The parsing for PollInterval happens even before parsing
560 // of the status because we may want to specify the PollInterval even when
561 // there's no update.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700562 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
563 &output_object->poll_interval);
564
David Zeuthen639aa362014-02-03 16:23:44 -0800565 // Check for the "elapsed_days" attribute in the "daystart"
566 // element. This is the number of days since Jan 1 2007, 0:00
567 // PST. If we don't have a persisted value of the Omaha InstallDate,
568 // we'll use it to calculate it and then persist it.
569 if (ParseInstallDate(doc, output_object) && !HasInstallDate(system_state_)) {
570 // Since output_object->install_date_days is never negative, the
571 // elapsed_days -> install-date calculation is reduced to simply
572 // rounding down to the nearest number divisible by 7.
573 int remainder = output_object->install_date_days % 7;
574 int install_date_days_rounded =
575 output_object->install_date_days - remainder;
576 if (PersistInstallDate(system_state_,
577 install_date_days_rounded,
578 kProvisionedFromOmahaResponse)) {
579 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
580 << install_date_days_rounded << " days";
581 }
582 }
583
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700584 if (!ParseStatus(update_check_node, output_object, completer))
585 return false;
586
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800587 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
588 // appends the package name to the URLs populated in this method.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700589 if (!ParseUrls(doc, output_object, completer))
590 return false;
591
592 if (!ParsePackage(doc, output_object, completer))
593 return false;
594
595 if (!ParseParams(doc, output_object, completer))
596 return false;
597
598 return true;
599}
600
601bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
602 OmahaResponse* output_object,
603 ScopedActionCompleter* completer) {
604 // Get status.
605 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
606 LOG(ERROR) << "Omaha Response missing status";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700607 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700608 return false;
609 }
610
611 const string status(XmlGetProperty(update_check_node, "status"));
612 if (status == "noupdate") {
613 LOG(INFO) << "No update.";
614 output_object->update_exists = false;
615 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700616 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700617 return false;
618 }
619
620 if (status != "ok") {
621 LOG(ERROR) << "Unknown Omaha response status: " << status;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700622 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700623 return false;
624 }
625
626 return true;
627}
628
629bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
630 OmahaResponse* output_object,
631 ScopedActionCompleter* completer) {
632 // Get the update URL.
633 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
634
Ben Chan075248b2014-04-24 12:04:14 -0700635 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700636 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
637 if (!xpath_nodeset.get()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700638 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700639 return false;
640 }
641
642 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
643 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
644 CHECK_GE(nodeset->nodeNr, 1);
645
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800646 LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)";
647 output_object->payload_urls.clear();
648 for (int i = 0; i < nodeset->nodeNr; i++) {
649 xmlNode* url_node = nodeset->nodeTab[i];
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800650 const string codebase(XmlGetProperty(url_node, "codebase"));
651 if (codebase.empty()) {
652 LOG(ERROR) << "Omaha Response URL has empty codebase";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700653 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800654 return false;
655 }
656 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700657 }
658
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700659 return true;
660}
661
662bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
663 OmahaResponse* output_object,
664 ScopedActionCompleter* completer) {
665 // Get the package node.
666 static const char* kPackageNodeXPath(
667 "/response/app/updatecheck/manifest/packages/package");
668
Ben Chan075248b2014-04-24 12:04:14 -0700669 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700670 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
671 if (!xpath_nodeset.get()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700672 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700673 return false;
674 }
675
676 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
677 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
678 CHECK_GE(nodeset->nodeNr, 1);
679
680 // We only care about the first package.
681 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
682 xmlNode* package_node = nodeset->nodeTab[0];
683
684 // Get package properties one by one.
685
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800686 // Parse the payload name to be appended to the base Url value.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700687 const string package_name(XmlGetProperty(package_node, "name"));
688 LOG(INFO) << "Omaha Response package name = " << package_name;
689 if (package_name.empty()) {
690 LOG(ERROR) << "Omaha Response has empty package name";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700691 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700692 return false;
693 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800694
695 // Append the package name to each URL in our list so that we don't
696 // propagate the urlBase vs packageName distinctions beyond this point.
697 // From now on, we only need to use payload_urls.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700698 for (size_t i = 0; i < output_object->payload_urls.size(); i++)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800699 output_object->payload_urls[i] += package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700700
701 // Parse the payload size.
702 off_t size = ParseInt(XmlGetProperty(package_node, "size"));
703 if (size <= 0) {
704 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700705 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700706 return false;
707 }
708 output_object->size = size;
709
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800710 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700711
712 return true;
713}
714
715bool OmahaRequestAction::ParseParams(xmlDoc* doc,
716 OmahaResponse* output_object,
717 ScopedActionCompleter* completer) {
Chris Sosa3b748432013-06-20 16:42:59 -0700718 // XPath location for response elements we care about.
719 static const char* kManifestNodeXPath("/response/app/updatecheck/manifest");\
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700720 static const char* kActionNodeXPath(
Chris Sosa3b748432013-06-20 16:42:59 -0700721 "/response/app/updatecheck/manifest/actions/action");
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700722
Chris Sosa3b748432013-06-20 16:42:59 -0700723 // Get the manifest node where version is present.
Ben Chan075248b2014-04-24 12:04:14 -0700724 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Chris Sosa3b748432013-06-20 16:42:59 -0700725 xpath_manifest_nodeset(GetNodeSet(doc, ConstXMLStr(kManifestNodeXPath)));
726 if (!xpath_manifest_nodeset.get()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700727 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700728 return false;
729 }
730
Chris Sosa3b748432013-06-20 16:42:59 -0700731 // Grab the only matching node there should be from the xpath.
732 xmlNodeSet* nodeset = xpath_manifest_nodeset->nodesetval;
733 CHECK(nodeset) << "XPath missing " << kManifestNodeXPath;
734 CHECK_GE(nodeset->nodeNr, 1);
735 xmlNode* manifest_node = nodeset->nodeTab[0];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700736
Chris Sosa3b748432013-06-20 16:42:59 -0700737 // Set the version.
738 output_object->version = XmlGetProperty(manifest_node, kTagVersion);
739 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700740 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700741 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700742 return false;
743 }
744
745 LOG(INFO) << "Received omaha response to update to version "
746 << output_object->version;
747
748 // Grab the action nodes.
Ben Chan075248b2014-04-24 12:04:14 -0700749 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Chris Sosa3b748432013-06-20 16:42:59 -0700750 xpath_action_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
751 if (!xpath_action_nodeset.get()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700752 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700753 return false;
754 }
755
756 // We only care about the action that has event "postinstall", because this is
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700757 // where Omaha puts all the generic name/value pairs in the rule.
Chris Sosa3b748432013-06-20 16:42:59 -0700758 nodeset = xpath_action_nodeset->nodesetval;
759 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700760 LOG(INFO) << "Found " << nodeset->nodeNr
761 << " action(s). Processing the postinstall action.";
762
763 // pie_action_node holds the action node corresponding to the
764 // postinstall event action, if present.
765 xmlNode* pie_action_node = NULL;
766 for (int i = 0; i < nodeset->nodeNr; i++) {
767 xmlNode* action_node = nodeset->nodeTab[i];
768 if (XmlGetProperty(action_node, "event") == "postinstall") {
769 pie_action_node = action_node;
770 break;
771 }
772 }
773
774 if (!pie_action_node) {
775 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700776 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700777 return false;
778 }
779
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800780 output_object->hash = XmlGetProperty(pie_action_node, kTagSha256);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700781 if (output_object->hash.empty()) {
782 LOG(ERROR) << "Omaha Response has empty sha256 value";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700783 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700784 return false;
785 }
786
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800787 // Get the optional properties one by one.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800788 output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700789 output_object->metadata_size =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800790 ParseInt(XmlGetProperty(pie_action_node, kTagMetadataSize));
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700791 output_object->metadata_signature =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800792 XmlGetProperty(pie_action_node, kTagMetadataSignatureRsa);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800793 output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true";
794 output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700795 output_object->max_days_to_scatter =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800796 ParseInt(XmlGetProperty(pie_action_node, kTagMaxDaysToScatter));
David Zeuthen8f191b22013-08-06 12:27:50 -0700797 output_object->disable_p2p_for_downloading =
798 (XmlGetProperty(pie_action_node, kTagDisableP2PForDownloading) == "true");
799 output_object->disable_p2p_for_sharing =
800 (XmlGetProperty(pie_action_node, kTagDisableP2PForSharing) == "true");
David Zeuthene7f89172013-10-31 10:21:04 -0700801 output_object->public_key_rsa =
802 XmlGetProperty(pie_action_node, kTagPublicKeyRsa);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800803
804 string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl);
Jay Srinivasan08262882012-12-28 19:29:43 -0800805 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800806 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700807
Jay Srinivasan08262882012-12-28 19:29:43 -0800808 output_object->is_delta_payload =
809 XmlGetProperty(pie_action_node, kTagIsDeltaPayload) == "true";
810
811 output_object->disable_payload_backoff =
812 XmlGetProperty(pie_action_node, kTagDisablePayloadBackoff) == "true";
813
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700814 return true;
815}
816
rspangler@google.com49fdf182009-10-10 00:57:34 +0000817// If the transfer was successful, this uses libxml2 to parse the response
818// and fill in the appropriate fields of the output object. Also, notifies
819// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700820void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
821 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000822 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800823 string current_response(response_buffer_.begin(), response_buffer_.end());
824 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700825
826 // Events are best effort transactions -- assume they always succeed.
827 if (IsEvent()) {
828 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800829 if (event_->result == OmahaEvent::kResultError && successful &&
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700830 system_state_->hardware()->IsOfficialBuild()) {
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800831 LOG(INFO) << "Signalling Crash Reporter.";
832 utils::ScheduleCrashReporterUpload();
833 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700834 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700835 return;
836 }
837
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700838 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700839 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700840 int code = GetHTTPResponseCode();
841 // Makes sure we send sane error values.
842 if (code < 0 || code >= 1000) {
843 code = 999;
844 }
David Zeuthena99981f2013-04-29 13:42:47 -0700845 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700846 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000847 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700848 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000849
850 // parse our response and fill the fields in the output object
Ben Chan075248b2014-04-24 12:04:14 -0700851 scoped_ptr<xmlDoc, ScopedPtrXmlDocFree> doc(
rspangler@google.com49fdf182009-10-10 00:57:34 +0000852 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
853 if (!doc.get()) {
854 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700855 completer.set_code(response_buffer_.empty() ?
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700856 ErrorCode::kOmahaRequestEmptyResponseError :
857 ErrorCode::kOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000858 return;
859 }
860
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700861 // If a ping was sent, update the last ping day preferences based on
862 // the server daystart response.
863 if (ShouldPing(ping_active_days_) ||
864 ShouldPing(ping_roll_call_days_) ||
865 ping_active_days_ == kPingTimeJump ||
866 ping_roll_call_days_ == kPingTimeJump) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800867 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700868 << "Failed to update the last ping day preferences!";
869 }
870
Thieu Le116fda32011-04-19 11:01:54 -0700871 if (!HasOutputPipe()) {
872 // Just set success to whether or not the http transfer succeeded,
873 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700874 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700875 return;
876 }
877
Darin Petkov6a5b3222010-07-13 14:55:28 -0700878 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700879 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000880 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700881 output_object.update_exists = true;
882 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000883
Chris Sosa77f79e82014-06-02 18:16:24 -0700884 if (ShouldIgnoreUpdate(output_object)) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700885 output_object.update_exists = false;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700886 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700887 return;
888 }
889
David Zeuthen8f191b22013-08-06 12:27:50 -0700890 // If Omaha says to disable p2p, respect that
891 if (output_object.disable_p2p_for_downloading) {
892 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
893 << "requested by Omaha.";
894 params_->set_use_p2p_for_downloading(false);
895 }
896 if (output_object.disable_p2p_for_sharing) {
897 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
898 << "requested by Omaha.";
899 params_->set_use_p2p_for_sharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700900 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800901
902 // Update the payload state with the current response. The payload state
903 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800904 // from what's stored already. We are updating the payload state as late
905 // as possible in this method so that if a new release gets pushed and then
906 // got pulled back due to some issues, we don't want to clear our internal
907 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800908 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800909 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800910
David Zeuthen8f191b22013-08-06 12:27:50 -0700911 // It could be we've already exceeded the deadline for when p2p is
912 // allowed or that we've tried too many times with p2p. Check that.
913 if (params_->use_p2p_for_downloading()) {
914 payload_state->P2PNewAttempt();
915 if (!payload_state->P2PAttemptAllowed()) {
916 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
917 << "of previous failures when using p2p.";
918 params_->set_use_p2p_for_downloading(false);
919 }
920 }
921
922 // From here on, we'll complete stuff in CompleteProcessing() so
923 // disable |completer| since we'll create a new one in that
924 // function.
925 completer.set_should_complete(false);
926
927 // If we're allowed to use p2p for downloading we do not pay
928 // attention to wall-clock-based waiting if the URL is indeed
929 // available via p2p. Therefore, check if the file is available via
930 // p2p before deferring...
931 if (params_->use_p2p_for_downloading()) {
932 LookupPayloadViaP2P(output_object);
933 } else {
934 CompleteProcessing();
935 }
936}
937
938void OmahaRequestAction::CompleteProcessing() {
939 ScopedActionCompleter completer(processor_, this);
940 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
941 PayloadStateInterface* payload_state = system_state_->payload_state();
942
943 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800944 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -0700945 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700946 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -0800947 return;
948 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700949
Chris Sosa20f005c2013-09-05 13:53:08 -0700950 if (payload_state->ShouldBackoffDownload()) {
951 output_object.update_exists = false;
952 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
953 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700954 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -0700955 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700956 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700957 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -0700958}
959
960void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
961 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
962 if (!url.empty()) {
963 params_->set_p2p_url(url);
964 } else {
965 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
966 << "because no suitable peer could be found.";
967 params_->set_use_p2p_for_downloading(false);
968 }
969 CompleteProcessing();
970}
971
972void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -0700973 // If the device is in the middle of an update, the state variables
974 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
975 // tracks the offset and length of the operation currently in
976 // progress. The offset is based from the end of the manifest which
977 // is kPrefsManifestMetadataSize bytes long.
978 //
979 // To make forward progress and avoid deadlocks, we need to find a
980 // peer that has at least the entire operation we're currently
981 // working on. Otherwise we may end up in a situation where two
982 // devices bounce back and forth downloading from each other,
983 // neither making any forward progress until one of them decides to
984 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
985 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -0700986 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -0700987 int64_t manifest_metadata_size = 0;
988 int64_t next_data_offset = 0;
989 int64_t next_data_length = 0;
David Zeuthen8f191b22013-08-06 12:27:50 -0700990 if (system_state_ != NULL &&
David Zeuthen41996ad2013-09-24 15:43:24 -0700991 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
992 &manifest_metadata_size) &&
993 manifest_metadata_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -0700994 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -0700995 &next_data_offset) &&
996 next_data_offset != -1 &&
997 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
998 &next_data_length)) {
999 minimum_size = manifest_metadata_size + next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001000 }
1001
1002 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
1003 if (system_state_->p2p_manager() != NULL) {
1004 LOG(INFO) << "Checking if payload is available via p2p, file_id="
1005 << file_id << " minimum_size=" << minimum_size;
1006 system_state_->p2p_manager()->LookupUrlForFile(
1007 file_id,
1008 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001009 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001010 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1011 base::Unretained(this)));
1012 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001013}
1014
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001015bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001016 if (params_->interactive()) {
1017 LOG(INFO) << "Not deferring download because update is interactive.";
1018 return false;
1019 }
1020
David Zeuthen8f191b22013-08-06 12:27:50 -07001021 // If we're using p2p to download _and_ we have a p2p URL, we never
1022 // defer the download. This is because the download will always
1023 // happen from a peer on the LAN and we've been waiting in line for
1024 // our turn.
1025 if (params_->use_p2p_for_downloading() && !params_->p2p_url().empty()) {
1026 LOG(INFO) << "Download not deferred because download "
1027 << "will happen from a local peer (via p2p).";
1028 return false;
1029 }
1030
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001031 // We should defer the downloads only if we've first satisfied the
1032 // wall-clock-based-waiting period and then the update-check-based waiting
1033 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001034 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001035 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1036 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001037 return false;
1038 }
1039
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001040 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001041 case kWallClockWaitNotSatisfied:
1042 // We haven't even satisfied the first condition, passing the
1043 // wall-clock-based waiting period, so we should defer the downloads
1044 // until that happens.
1045 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1046 return true;
1047
1048 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1049 LOG(INFO) << "wall-clock-based-wait satisfied and "
1050 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001051 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001052
1053 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1054 // Wall-clock-based waiting period is satisfied, and it's determined
1055 // that we do not need the update-check-based wait. so no need to
1056 // defer downloads.
1057 LOG(INFO) << "wall-clock-based-wait satisfied and "
1058 << "update-check-based-wait is not required.";
1059 return false;
1060
1061 default:
1062 // Returning false for this default case so we err on the
1063 // side of downloading updates than deferring in case of any bugs.
1064 NOTREACHED();
1065 return false;
1066 }
1067}
1068
1069OmahaRequestAction::WallClockWaitResult
1070OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001071 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001072 Time update_first_seen_at;
1073 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001074
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001075 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1076 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1077 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001078 // Note: This timestamp could be that of ANY update we saw in the past
1079 // (not necessarily this particular update we're considering to apply)
1080 // but never got to apply because of some reason (e.g. stop AU policy,
1081 // updates being pulled out from Omaha, changes in target version prefix,
1082 // new update being rolled out, etc.). But for the purposes of scattering
1083 // it doesn't matter which update the timestamp corresponds to. i.e.
1084 // the clock starts ticking the first time we see an update and we're
1085 // ready to apply when the random wait period is satisfied relative to
1086 // that first seen timestamp.
1087 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1088 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1089 << utils::ToString(update_first_seen_at);
1090 } else {
1091 // This seems like an unexpected error where the persisted value exists
1092 // but it's not readable for some reason. Just skip scattering in this
1093 // case to be safe.
1094 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1095 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1096 }
1097 } else {
1098 update_first_seen_at = Time::Now();
1099 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001100 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1101 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001102 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1103 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001104 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001105 // This seems like an unexpected error where the value cannot be
1106 // persisted for some reason. Just skip scattering in this
1107 // case to be safe.
1108 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1109 << utils::ToString(update_first_seen_at)
1110 << " cannot be persisted";
1111 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1112 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001113 }
1114
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001115 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001116 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001117 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001118
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001119 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001120 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001121 << ", Time Elapsed = "
1122 << utils::FormatSecs(elapsed_time.InSeconds())
1123 << ", MaxDaysToScatter = "
1124 << max_scatter_period.InDays();
1125
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001126 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001127 // The deadline is set for all rules which serve a delta update from a
1128 // previous FSI, which means this update will be applied mostly in OOBE
1129 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1130 // quickly.
1131 LOG(INFO) << "Not scattering as deadline flag is set";
1132 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1133 }
1134
1135 if (max_scatter_period.InDays() == 0) {
1136 // This means the Omaha rule creator decides that this rule
1137 // should not be scattered irrespective of the policy.
1138 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1139 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1140 }
1141
1142 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001143 // This means we've waited more than the upperbound wait in the rule
1144 // from the time we first saw a valid update available to us.
1145 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001146 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1147 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1148 }
1149
1150 // This means we are required to participate in scattering.
1151 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001152 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001153 if (remaining_wait_time.InSeconds() <= 0) {
1154 // Yes, it's our turn now.
1155 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1156
1157 // But we can't download until the update-check-count-based wait is also
1158 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001159 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001160 kWallClockWaitDoneButUpdateCheckWaitRequired :
1161 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1162 }
1163
1164 // Not our turn yet, so we have to wait until our turn to
1165 // help scatter the downloads across all clients of the enterprise.
1166 LOG(INFO) << "Update deferred for another "
1167 << utils::FormatSecs(remaining_wait_time.InSeconds())
1168 << " per policy.";
1169 return kWallClockWaitNotSatisfied;
1170}
1171
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001172bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001173 int64 update_check_count_value;
1174
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001175 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1176 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1177 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001178 // We are unable to read the update check count from file for some reason.
1179 // So let's proceed anyway so as to not stall the update.
1180 LOG(ERROR) << "Unable to read update check count. "
1181 << "Skipping update-check-count-based-wait.";
1182 return true;
1183 }
1184 } else {
1185 // This file does not exist. This means we haven't started our update
1186 // check count down yet, so this is the right time to start the count down.
1187 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001188 params_->min_update_checks_needed(),
1189 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001190
1191 LOG(INFO) << "Randomly picked update check count value = "
1192 << update_check_count_value;
1193
1194 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001195 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1196 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001197 // We weren't able to write the update check count file for some reason.
1198 // So let's proceed anyway so as to not stall the update.
1199 LOG(ERROR) << "Unable to write update check count. "
1200 << "Skipping update-check-count-based-wait.";
1201 return true;
1202 }
1203 }
1204
1205 if (update_check_count_value == 0) {
1206 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1207 return true;
1208 }
1209
1210 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001211 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001212 // We err on the side of skipping scattering logic instead of stalling
1213 // a machine from receiving any updates in case of any unexpected state.
1214 LOG(ERROR) << "Invalid value for update check count detected. "
1215 << "Skipping update-check-count-based-wait.";
1216 return true;
1217 }
1218
1219 // Legal value, we need to wait for more update checks to happen
1220 // until this becomes 0.
1221 LOG(INFO) << "Deferring Omaha updates for another "
1222 << update_check_count_value
1223 << " update checks per policy";
1224 return false;
1225}
1226
David Zeuthen639aa362014-02-03 16:23:44 -08001227// static
1228bool OmahaRequestAction::ParseInstallDate(xmlDoc* doc,
1229 OmahaResponse* output_object) {
Ben Chan075248b2014-04-24 12:04:14 -07001230 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
David Zeuthen639aa362014-02-03 16:23:44 -08001231 xpath_nodeset(GetNodeSet(doc, ConstXMLStr("/response/daystart")));
1232
1233 if (xpath_nodeset.get() == NULL)
1234 return false;
1235
1236 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
1237 if (nodeset == NULL || nodeset->nodeNr < 1)
1238 return false;
1239
1240 xmlNode* daystart_node = nodeset->nodeTab[0];
1241 if (!xmlHasProp(daystart_node, ConstXMLStr("elapsed_days")))
1242 return false;
1243
1244 int64_t elapsed_days = 0;
1245 if (!base::StringToInt64(XmlGetProperty(daystart_node, "elapsed_days"),
1246 &elapsed_days))
1247 return false;
1248
1249 if (elapsed_days < 0)
1250 return false;
1251
1252 output_object->install_date_days = elapsed_days;
1253 return true;
1254}
1255
1256// static
1257bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1258 PrefsInterface* prefs = system_state->prefs();
1259 if (prefs == NULL)
1260 return false;
1261
1262 return prefs->Exists(kPrefsInstallDateDays);
1263}
1264
1265// static
1266bool OmahaRequestAction::PersistInstallDate(
1267 SystemState *system_state,
1268 int install_date_days,
1269 InstallDateProvisioningSource source) {
1270 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1271
1272 PrefsInterface* prefs = system_state->prefs();
1273 if (prefs == NULL)
1274 return false;
1275
1276 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1277 return false;
1278
1279 string metric_name = "Installer.InstallDateProvisioningSource";
1280 system_state->metrics_lib()->SendEnumToUMA(
1281 metric_name,
David Zeuthen33bae492014-02-25 16:16:18 -08001282 static_cast<int>(source), // Sample.
1283 kProvisionedMax); // Maximum.
1284
1285 metric_name = metrics::kMetricInstallDateProvisioningSource;
1286 system_state->metrics_lib()->SendEnumToUMA(
1287 metric_name,
1288 static_cast<int>(source), // Sample.
1289 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001290
1291 return true;
1292}
1293
David Zeuthen33bae492014-02-25 16:16:18 -08001294void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1295 // We only want to report this on "update check".
1296 if (ping_only_ || event_ != nullptr)
1297 return;
1298
1299 metrics::CheckResult result = metrics::CheckResult::kUnset;
1300 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1301 metrics::DownloadErrorCode download_error_code =
1302 metrics::DownloadErrorCode::kUnset;
1303
1304 // Regular update attempt.
1305 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001306 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001307 // OK, we parsed the response successfully but that does
1308 // necessarily mean that an update is available.
1309 if (HasOutputPipe()) {
1310 const OmahaResponse& response = GetOutputObject();
1311 if (response.update_exists) {
1312 result = metrics::CheckResult::kUpdateAvailable;
1313 reaction = metrics::CheckReaction::kUpdating;
1314 } else {
1315 result = metrics::CheckResult::kNoUpdateAvailable;
1316 }
1317 } else {
1318 result = metrics::CheckResult::kNoUpdateAvailable;
1319 }
1320 break;
1321
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001322 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001323 result = metrics::CheckResult::kUpdateAvailable;
1324 reaction = metrics::CheckReaction::kIgnored;
1325 break;
1326
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001327 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001328 result = metrics::CheckResult::kUpdateAvailable;
1329 reaction = metrics::CheckReaction::kDeferring;
1330 break;
1331
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001332 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001333 result = metrics::CheckResult::kUpdateAvailable;
1334 reaction = metrics::CheckReaction::kBackingOff;
1335 break;
1336
1337 default:
1338 // We report two flavors of errors, "Download errors" and "Parsing
1339 // error". Try to convert to the former and if that doesn't work
1340 // we know it's the latter.
1341 metrics::DownloadErrorCode tmp_error = utils::GetDownloadErrorCode(code);
1342 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1343 result = metrics::CheckResult::kDownloadError;
1344 download_error_code = tmp_error;
1345 } else {
1346 result = metrics::CheckResult::kParsingError;
1347 }
1348 break;
1349 }
1350
1351 metrics::ReportUpdateCheckMetrics(system_state_,
1352 result, reaction, download_error_code);
1353}
1354
Chris Sosa77f79e82014-06-02 18:16:24 -07001355bool OmahaRequestAction::ShouldIgnoreUpdate(
1356 const OmahaResponse& response) const {
1357 if (params_->update_disabled()) {
1358 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
1359 return true;
1360 }
1361
1362 // Note: policy decision to not update to a version we rolled back from.
1363 string rollback_version =
1364 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001365 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001366 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001367 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001368 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1369 return true;
1370 }
1371 }
1372
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001373 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001374 LOG(INFO) << "Update is not allowed over current connection.";
1375 return true;
1376 }
1377
1378 // Note: We could technically delete the UpdateFirstSeenAt state when we
1379 // return true. If we do, it'll mean a device has to restart the
1380 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1381 // turned on again. On the other hand, it also increases the chance of update
1382 // starvation if an admin turns AU on/off more frequently. We choose to err on
1383 // the side of preventing starvation at the cost of not applying scattering in
1384 // those cases.
1385 return false;
1386}
1387
1388bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
1389 NetworkConnectionType type;
1390 NetworkTethering tethering;
1391 RealDBusWrapper dbus_iface;
1392 ConnectionManager* connection_manager = system_state_->connection_manager();
1393 if (!connection_manager->GetConnectionProperties(&dbus_iface,
1394 &type, &tethering)) {
1395 LOG(INFO) << "We could not determine our connection type. "
1396 << "Defaulting to allow updates.";
1397 return true;
1398 }
1399 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1400 LOG(INFO) << "We are connected via "
1401 << connection_manager->StringForConnectionType(type)
1402 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1403 return is_allowed;
1404}
1405
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001406} // namespace chromeos_update_engine