blob: 9e43385df3182019866bd36086d23033f4ecc5f2 [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
61const string kGupdateVersion("ChromeOSUpdateEngine-0.1.0.0");
62
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) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700169 error_code = base::StringPrintf(" errorcode=\"%d\"", event->error_code);
Darin Petkove17f86b2010-07-20 09:12:01 -0700170 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700171 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700172 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700173 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700174 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700175
176 return app_body;
177}
178
179// Returns an XML that corresponds to the entire <app> node of the Omaha
180// request based on the given parameters.
181string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700182 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700183 bool ping_only,
184 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) {
188 string app_body = GetAppBody(event, params, ping_only, ping_active_days,
189 ping_roll_call_days, system_state->prefs());
190 string app_versions;
191
192 // If we are upgrading to a more stable channel and we are allowed to do
193 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
194 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700195 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700196 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
197 << "on downgrading to the version in the more stable channel";
198 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700199 XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700200 } else {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700201 app_versions = "version=\"" + XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700202 }
203
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700204 string download_channel = params->download_channel();
205 string app_channels = "track=\"" + XmlEncode(download_channel) + "\" ";
206 if (params->current_channel() != download_channel)
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700207 app_channels +=
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700208 "from_track=\"" + XmlEncode(params->current_channel()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700209
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700210 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700211
David Zeuthen639aa362014-02-03 16:23:44 -0800212 // If install_date_days is not set (e.g. its value is -1 ), don't
213 // include the attribute.
214 string install_date_in_days_str = "";
215 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700216 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
217 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800218 }
219
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700220 string app_xml =
Jay Srinivasandb0acdf2013-04-02 14:47:45 -0700221 " <app appid=\"" + XmlEncode(params->GetAppId()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700222 app_versions +
223 app_channels +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700224 "lang=\"" + XmlEncode(params->app_lang()) + "\" " +
225 "board=\"" + XmlEncode(params->os_board()) + "\" " +
226 "hardware_class=\"" + XmlEncode(params->hwid()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700227 "delta_okay=\"" + delta_okay_str + "\" "
Chris Sosac1972482013-04-30 22:31:10 -0700228 "fw_version=\"" + XmlEncode(params->fw_version()) + "\" " +
229 "ec_version=\"" + XmlEncode(params->ec_version()) + "\" " +
David Zeuthen639aa362014-02-03 16:23:44 -0800230 install_date_in_days_str +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700231 ">\n" +
232 app_body +
233 " </app>\n";
234
235 return app_xml;
236}
237
238// Returns an XML that corresponds to the entire <os> node of the Omaha
239// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700240string GetOsXml(OmahaRequestParams* params) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700241 string os_xml =
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700242 " <os version=\"" + XmlEncode(params->os_version()) + "\" " +
243 "platform=\"" + XmlEncode(params->os_platform()) + "\" " +
244 "sp=\"" + XmlEncode(params->os_sp()) + "\">"
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700245 "</os>\n";
246 return os_xml;
247}
248
249// Returns an XML that corresponds to the entire Omaha request based on the
250// given parameters.
251string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700252 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700253 bool ping_only,
254 int ping_active_days,
255 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800256 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700257 SystemState* system_state) {
258 string os_xml = GetOsXml(params);
259 string app_xml = GetAppXml(event, params, ping_only, ping_active_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800260 ping_roll_call_days, install_date_in_days,
261 system_state);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700262
Alex Vakulenko75039d72014-03-25 12:36:28 -0700263 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700264 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700265
266 string request_xml =
267 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700268 "<request protocol=\"3.0\" "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700269 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
270 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" " +
271 install_source +
272 "ismachine=\"1\">\n" +
273 os_xml +
274 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700275 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700276
277 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000278}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700279
rspangler@google.com49fdf182009-10-10 00:57:34 +0000280} // namespace {}
281
282// Encodes XML entities in a given string with libxml2. input must be
283// UTF-8 formatted. Output will be UTF-8 formatted.
284string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700285 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
286 // // cpu, considering creating one and caching it.
Ben Chan075248b2014-04-24 12:04:14 -0700287 // scoped_ptr<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
Darin Petkov6a5b3222010-07-13 14:55:28 -0700288 // xmlNewDoc(ConstXMLStr("1.0")));
289 // if (!xml_doc.get()) {
290 // LOG(ERROR) << "Unable to create xmlDoc";
291 // return "";
292 // }
Ben Chan075248b2014-04-24 12:04:14 -0700293 scoped_ptr<xmlChar, ScopedPtrXmlFree> str(
rspangler@google.com49fdf182009-10-10 00:57:34 +0000294 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
295 return string(reinterpret_cast<const char *>(str.get()));
296}
297
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800298OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700299 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700300 HttpFetcher* http_fetcher,
301 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800302 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700303 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700304 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700305 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700306 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700307 ping_roll_call_days_(0) {
308 params_ = system_state->request_params();
309}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000310
Darin Petkov6a5b3222010-07-13 14:55:28 -0700311OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000312
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700313// Calculates the value to use for the ping days parameter.
314int OmahaRequestAction::CalculatePingDays(const string& key) {
315 int days = kNeverPinged;
316 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800317 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700318 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
319 if (days < 0) {
320 // If |days| is negative, then the system clock must have jumped
321 // back in time since the ping was sent. Mark the value so that
322 // it doesn't get sent to the server but we still update the
323 // last ping daystart preference. This way the next ping time
324 // will be correct, hopefully.
325 days = kPingTimeJump;
326 LOG(WARNING) <<
327 "System clock jumped back in time. Resetting ping daystarts.";
328 }
329 }
330 return days;
331}
332
333void OmahaRequestAction::InitPingDays() {
334 // We send pings only along with update checks, not with events.
335 if (IsEvent()) {
336 return;
337 }
338 // TODO(petkov): Figure a way to distinguish active use pings
339 // vs. roll call pings. Currently, the two pings are identical. A
340 // fix needs to change this code as well as UpdateLastPingDays.
341 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
342 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
343}
344
David Zeuthen639aa362014-02-03 16:23:44 -0800345// static
346int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
347 PrefsInterface* prefs = system_state->prefs();
348 if (prefs == NULL)
349 return -1;
350
351 // If we have the value stored on disk, just return it.
352 int64_t stored_value;
353 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
354 // Convert and sanity-check.
355 int install_date_days = static_cast<int>(stored_value);
356 if (install_date_days >= 0)
357 return install_date_days;
358 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
359 << install_date_days << " looks suspicious.";
360 prefs->Delete(kPrefsInstallDateDays);
361 }
362
363 // Otherwise, if OOBE is not complete then do nothing and wait for
364 // ParseResponse() to call ParseInstallDate() and then
365 // PersistInstallDate() to set the kPrefsInstallDateDays state
366 // variable. Once that is done, we'll then report back in future
367 // Omaha requests. This works exactly because OOBE triggers an
368 // update check.
369 //
370 // However, if OOBE is complete and the kPrefsInstallDateDays state
371 // variable is not set, there are two possibilities
372 //
373 // 1. The update check in OOBE failed so we never got a response
374 // from Omaha (no network etc.); or
375 //
376 // 2. OOBE was done on an older version that didn't write to the
377 // kPrefsInstallDateDays state variable.
378 //
379 // In both cases, we approximate the install date by simply
380 // inspecting the timestamp of when OOBE happened.
381
382 Time time_of_oobe;
Alex Deymobccbc382014-04-03 13:38:55 -0700383 if (!system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800384 LOG(INFO) << "Not generating Omaha InstallData as we have "
385 << "no prefs file and OOBE is not complete.";
386 return -1;
387 }
388
389 int num_days;
390 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
391 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
392 << "as its value '" << utils::ToString(time_of_oobe)
393 << "' looks suspicious.";
394 return -1;
395 }
396
397 // Persist this to disk, for future use.
398 if (!OmahaRequestAction::PersistInstallDate(system_state,
399 num_days,
400 kProvisionedFromOOBEMarker))
401 return -1;
402
403 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
404 << num_days << " days";
405
406 return num_days;
407}
408
Darin Petkov6a5b3222010-07-13 14:55:28 -0700409void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000410 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700411 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700412 if (ping_only_ &&
413 !ShouldPing(ping_active_days_) &&
414 !ShouldPing(ping_roll_call_days_)) {
David Zeuthena99981f2013-04-29 13:42:47 -0700415 processor_->ActionComplete(this, kErrorCodeSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700416 return;
417 }
David Zeuthen639aa362014-02-03 16:23:44 -0800418
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700419 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700420 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700421 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700422 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800423 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800424 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700425 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700426
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800427 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
428 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700429 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700430 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700431 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000432}
433
Darin Petkov6a5b3222010-07-13 14:55:28 -0700434void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000435 http_fetcher_->TerminateTransfer();
436}
437
438// We just store the response in the buffer. Once we've received all bytes,
439// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700440void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
441 const char* bytes,
442 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000443 response_buffer_.reserve(response_buffer_.size() + length);
444 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
445}
446
447namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000448// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
449// on the returned object.
450// This code is roughly based on the libxml tutorial at:
451// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700452xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000453 xmlXPathObject* result = NULL;
454
Ben Chan075248b2014-04-24 12:04:14 -0700455 scoped_ptr<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
rspangler@google.com49fdf182009-10-10 00:57:34 +0000456 xmlXPathNewContext(doc));
457 if (!context.get()) {
458 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
459 return NULL;
460 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000461
462 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000463 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700464 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000465 return NULL;
466 }
467 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700468 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000469 xmlXPathFreeObject(result);
470 return NULL;
471 }
472 return result;
473}
474
475// Returns the string value of a named attribute on a node, or empty string
476// if no such node exists. If the attribute exists and has a value of
477// empty string, there's no way to distinguish that from the attribute
478// not existing.
479string XmlGetProperty(xmlNode* node, const char* name) {
480 if (!xmlHasProp(node, ConstXMLStr(name)))
481 return "";
Ben Chan075248b2014-04-24 12:04:14 -0700482 scoped_ptr<xmlChar, ScopedPtrXmlFree> str(
rspangler@google.com49fdf182009-10-10 00:57:34 +0000483 xmlGetProp(node, ConstXMLStr(name)));
484 string ret(reinterpret_cast<const char *>(str.get()));
485 return ret;
486}
487
488// Parses a 64 bit base-10 int from a string and returns it. Returns 0
489// on error. If the string contains "0", that's indistinguishable from
490// error.
491off_t ParseInt(const string& str) {
492 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700493 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000494 if (rc < 1) {
495 // failure
496 return 0;
497 }
498 return ret;
499}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700500
501// Update the last ping day preferences based on the server daystart
502// response. Returns true on success, false otherwise.
503bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700504 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700505
Ben Chan075248b2014-04-24 12:04:14 -0700506 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700507 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700508 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
509 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
510 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
511 xmlNode* daystart_node = nodeset->nodeTab[0];
512 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
513 ConstXMLStr("elapsed_seconds")));
514
515 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700516 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
517 "elapsed_seconds"),
518 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700519 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
520
521 // Remember the local time that matches the server's last midnight
522 // time.
523 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
524 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
525 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
526 return true;
527}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000528} // namespace {}
529
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700530bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
531 OmahaResponse* output_object,
532 ScopedActionCompleter* completer) {
533 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
534
Ben Chan075248b2014-04-24 12:04:14 -0700535 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700536 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
537 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700538 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700539 return false;
540 }
541
542 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
543 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
544 CHECK_GE(nodeset->nodeNr, 1);
545 xmlNode* update_check_node = nodeset->nodeTab[0];
546
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800547 // chromium-os:37289: The PollInterval is not supported by Omaha server
548 // currently. But still keeping this existing code in case we ever decide to
549 // slow down the request rate from the server-side. Note that the
550 // PollInterval is not persisted, so it has to be sent by the server on every
551 // response to guarantee that the UpdateCheckScheduler uses this value
552 // (otherwise, if the device got rebooted after the last server-indicated
553 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
554 // value for the scattering logic is based on the assumption that we perform
555 // an update check every hour so that the max value of 8 will roughly be
556 // equivalent to one work day. If we decide to use PollInterval permanently,
557 // we should update the max_update_checks_allowed to take PollInterval into
558 // account. Note: The parsing for PollInterval happens even before parsing
559 // of the status because we may want to specify the PollInterval even when
560 // there's no update.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700561 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
562 &output_object->poll_interval);
563
David Zeuthen639aa362014-02-03 16:23:44 -0800564 // Check for the "elapsed_days" attribute in the "daystart"
565 // element. This is the number of days since Jan 1 2007, 0:00
566 // PST. If we don't have a persisted value of the Omaha InstallDate,
567 // we'll use it to calculate it and then persist it.
568 if (ParseInstallDate(doc, output_object) && !HasInstallDate(system_state_)) {
569 // Since output_object->install_date_days is never negative, the
570 // elapsed_days -> install-date calculation is reduced to simply
571 // rounding down to the nearest number divisible by 7.
572 int remainder = output_object->install_date_days % 7;
573 int install_date_days_rounded =
574 output_object->install_date_days - remainder;
575 if (PersistInstallDate(system_state_,
576 install_date_days_rounded,
577 kProvisionedFromOmahaResponse)) {
578 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
579 << install_date_days_rounded << " days";
580 }
581 }
582
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700583 if (!ParseStatus(update_check_node, output_object, completer))
584 return false;
585
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800586 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
587 // appends the package name to the URLs populated in this method.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700588 if (!ParseUrls(doc, output_object, completer))
589 return false;
590
591 if (!ParsePackage(doc, output_object, completer))
592 return false;
593
594 if (!ParseParams(doc, output_object, completer))
595 return false;
596
597 return true;
598}
599
600bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
601 OmahaResponse* output_object,
602 ScopedActionCompleter* completer) {
603 // Get status.
604 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
605 LOG(ERROR) << "Omaha Response missing status";
David Zeuthena99981f2013-04-29 13:42:47 -0700606 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700607 return false;
608 }
609
610 const string status(XmlGetProperty(update_check_node, "status"));
611 if (status == "noupdate") {
612 LOG(INFO) << "No update.";
613 output_object->update_exists = false;
614 SetOutputObject(*output_object);
David Zeuthena99981f2013-04-29 13:42:47 -0700615 completer->set_code(kErrorCodeSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700616 return false;
617 }
618
619 if (status != "ok") {
620 LOG(ERROR) << "Unknown Omaha response status: " << status;
David Zeuthena99981f2013-04-29 13:42:47 -0700621 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700622 return false;
623 }
624
625 return true;
626}
627
628bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
629 OmahaResponse* output_object,
630 ScopedActionCompleter* completer) {
631 // Get the update URL.
632 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
633
Ben Chan075248b2014-04-24 12:04:14 -0700634 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700635 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
636 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700637 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700638 return false;
639 }
640
641 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
642 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
643 CHECK_GE(nodeset->nodeNr, 1);
644
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800645 LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)";
646 output_object->payload_urls.clear();
647 for (int i = 0; i < nodeset->nodeNr; i++) {
648 xmlNode* url_node = nodeset->nodeTab[i];
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800649 const string codebase(XmlGetProperty(url_node, "codebase"));
650 if (codebase.empty()) {
651 LOG(ERROR) << "Omaha Response URL has empty codebase";
David Zeuthena99981f2013-04-29 13:42:47 -0700652 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800653 return false;
654 }
655 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700656 }
657
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700658 return true;
659}
660
661bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
662 OmahaResponse* output_object,
663 ScopedActionCompleter* completer) {
664 // Get the package node.
665 static const char* kPackageNodeXPath(
666 "/response/app/updatecheck/manifest/packages/package");
667
Ben Chan075248b2014-04-24 12:04:14 -0700668 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700669 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
670 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700671 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700672 return false;
673 }
674
675 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
676 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
677 CHECK_GE(nodeset->nodeNr, 1);
678
679 // We only care about the first package.
680 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
681 xmlNode* package_node = nodeset->nodeTab[0];
682
683 // Get package properties one by one.
684
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800685 // Parse the payload name to be appended to the base Url value.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700686 const string package_name(XmlGetProperty(package_node, "name"));
687 LOG(INFO) << "Omaha Response package name = " << package_name;
688 if (package_name.empty()) {
689 LOG(ERROR) << "Omaha Response has empty package name";
David Zeuthena99981f2013-04-29 13:42:47 -0700690 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700691 return false;
692 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800693
694 // Append the package name to each URL in our list so that we don't
695 // propagate the urlBase vs packageName distinctions beyond this point.
696 // From now on, we only need to use payload_urls.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700697 for (size_t i = 0; i < output_object->payload_urls.size(); i++)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800698 output_object->payload_urls[i] += package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700699
700 // Parse the payload size.
701 off_t size = ParseInt(XmlGetProperty(package_node, "size"));
702 if (size <= 0) {
703 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
David Zeuthena99981f2013-04-29 13:42:47 -0700704 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700705 return false;
706 }
707 output_object->size = size;
708
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800709 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700710
711 return true;
712}
713
714bool OmahaRequestAction::ParseParams(xmlDoc* doc,
715 OmahaResponse* output_object,
716 ScopedActionCompleter* completer) {
Chris Sosa3b748432013-06-20 16:42:59 -0700717 // XPath location for response elements we care about.
718 static const char* kManifestNodeXPath("/response/app/updatecheck/manifest");\
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700719 static const char* kActionNodeXPath(
Chris Sosa3b748432013-06-20 16:42:59 -0700720 "/response/app/updatecheck/manifest/actions/action");
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700721
Chris Sosa3b748432013-06-20 16:42:59 -0700722 // Get the manifest node where version is present.
Ben Chan075248b2014-04-24 12:04:14 -0700723 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Chris Sosa3b748432013-06-20 16:42:59 -0700724 xpath_manifest_nodeset(GetNodeSet(doc, ConstXMLStr(kManifestNodeXPath)));
725 if (!xpath_manifest_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700726 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700727 return false;
728 }
729
Chris Sosa3b748432013-06-20 16:42:59 -0700730 // Grab the only matching node there should be from the xpath.
731 xmlNodeSet* nodeset = xpath_manifest_nodeset->nodesetval;
732 CHECK(nodeset) << "XPath missing " << kManifestNodeXPath;
733 CHECK_GE(nodeset->nodeNr, 1);
734 xmlNode* manifest_node = nodeset->nodeTab[0];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700735
Chris Sosa3b748432013-06-20 16:42:59 -0700736 // Set the version.
737 output_object->version = XmlGetProperty(manifest_node, kTagVersion);
738 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700739 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Chris Sosa3b748432013-06-20 16:42:59 -0700740 completer->set_code(kErrorCodeOmahaResponseInvalid);
741 return false;
742 }
743
744 LOG(INFO) << "Received omaha response to update to version "
745 << output_object->version;
746
747 // Grab the action nodes.
Ben Chan075248b2014-04-24 12:04:14 -0700748 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Chris Sosa3b748432013-06-20 16:42:59 -0700749 xpath_action_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
750 if (!xpath_action_nodeset.get()) {
751 completer->set_code(kErrorCodeOmahaResponseInvalid);
752 return false;
753 }
754
755 // We only care about the action that has event "postinstall", because this is
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700756 // where Omaha puts all the generic name/value pairs in the rule.
Chris Sosa3b748432013-06-20 16:42:59 -0700757 nodeset = xpath_action_nodeset->nodesetval;
758 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700759 LOG(INFO) << "Found " << nodeset->nodeNr
760 << " action(s). Processing the postinstall action.";
761
762 // pie_action_node holds the action node corresponding to the
763 // postinstall event action, if present.
764 xmlNode* pie_action_node = NULL;
765 for (int i = 0; i < nodeset->nodeNr; i++) {
766 xmlNode* action_node = nodeset->nodeTab[i];
767 if (XmlGetProperty(action_node, "event") == "postinstall") {
768 pie_action_node = action_node;
769 break;
770 }
771 }
772
773 if (!pie_action_node) {
774 LOG(ERROR) << "Omaha Response has no postinstall event action";
David Zeuthena99981f2013-04-29 13:42:47 -0700775 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700776 return false;
777 }
778
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800779 output_object->hash = XmlGetProperty(pie_action_node, kTagSha256);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700780 if (output_object->hash.empty()) {
781 LOG(ERROR) << "Omaha Response has empty sha256 value";
David Zeuthena99981f2013-04-29 13:42:47 -0700782 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700783 return false;
784 }
785
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800786 // Get the optional properties one by one.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800787 output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700788 output_object->metadata_size =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800789 ParseInt(XmlGetProperty(pie_action_node, kTagMetadataSize));
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700790 output_object->metadata_signature =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800791 XmlGetProperty(pie_action_node, kTagMetadataSignatureRsa);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800792 output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true";
793 output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700794 output_object->max_days_to_scatter =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800795 ParseInt(XmlGetProperty(pie_action_node, kTagMaxDaysToScatter));
David Zeuthen8f191b22013-08-06 12:27:50 -0700796 output_object->disable_p2p_for_downloading =
797 (XmlGetProperty(pie_action_node, kTagDisableP2PForDownloading) == "true");
798 output_object->disable_p2p_for_sharing =
799 (XmlGetProperty(pie_action_node, kTagDisableP2PForSharing) == "true");
David Zeuthene7f89172013-10-31 10:21:04 -0700800 output_object->public_key_rsa =
801 XmlGetProperty(pie_action_node, kTagPublicKeyRsa);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800802
803 string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl);
Jay Srinivasan08262882012-12-28 19:29:43 -0800804 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800805 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700806
Jay Srinivasan08262882012-12-28 19:29:43 -0800807 output_object->is_delta_payload =
808 XmlGetProperty(pie_action_node, kTagIsDeltaPayload) == "true";
809
810 output_object->disable_payload_backoff =
811 XmlGetProperty(pie_action_node, kTagDisablePayloadBackoff) == "true";
812
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700813 return true;
814}
815
rspangler@google.com49fdf182009-10-10 00:57:34 +0000816// If the transfer was successful, this uses libxml2 to parse the response
817// and fill in the appropriate fields of the output object. Also, notifies
818// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700819void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
820 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000821 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800822 string current_response(response_buffer_.begin(), response_buffer_.end());
823 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700824
825 // Events are best effort transactions -- assume they always succeed.
826 if (IsEvent()) {
827 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800828 if (event_->result == OmahaEvent::kResultError && successful &&
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700829 system_state_->hardware()->IsOfficialBuild()) {
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800830 LOG(INFO) << "Signalling Crash Reporter.";
831 utils::ScheduleCrashReporterUpload();
832 }
David Zeuthena99981f2013-04-29 13:42:47 -0700833 completer.set_code(kErrorCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700834 return;
835 }
836
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700837 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700838 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700839 int code = GetHTTPResponseCode();
840 // Makes sure we send sane error values.
841 if (code < 0 || code >= 1000) {
842 code = 999;
843 }
David Zeuthena99981f2013-04-29 13:42:47 -0700844 completer.set_code(static_cast<ErrorCode>(
845 kErrorCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000846 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700847 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000848
849 // parse our response and fill the fields in the output object
Ben Chan075248b2014-04-24 12:04:14 -0700850 scoped_ptr<xmlDoc, ScopedPtrXmlDocFree> doc(
rspangler@google.com49fdf182009-10-10 00:57:34 +0000851 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
852 if (!doc.get()) {
853 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700854 completer.set_code(response_buffer_.empty() ?
David Zeuthena99981f2013-04-29 13:42:47 -0700855 kErrorCodeOmahaRequestEmptyResponseError :
856 kErrorCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000857 return;
858 }
859
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700860 // If a ping was sent, update the last ping day preferences based on
861 // the server daystart response.
862 if (ShouldPing(ping_active_days_) ||
863 ShouldPing(ping_roll_call_days_) ||
864 ping_active_days_ == kPingTimeJump ||
865 ping_roll_call_days_ == kPingTimeJump) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800866 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700867 << "Failed to update the last ping day preferences!";
868 }
869
Thieu Le116fda32011-04-19 11:01:54 -0700870 if (!HasOutputPipe()) {
871 // Just set success to whether or not the http transfer succeeded,
872 // which must be true at this point in the code.
David Zeuthena99981f2013-04-29 13:42:47 -0700873 completer.set_code(kErrorCodeSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700874 return;
875 }
876
Darin Petkov6a5b3222010-07-13 14:55:28 -0700877 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700878 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000879 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700880 output_object.update_exists = true;
881 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000882
Chris Sosa77f79e82014-06-02 18:16:24 -0700883 if (ShouldIgnoreUpdate(output_object)) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700884 output_object.update_exists = false;
David Zeuthena99981f2013-04-29 13:42:47 -0700885 completer.set_code(kErrorCodeOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700886 return;
887 }
888
David Zeuthen8f191b22013-08-06 12:27:50 -0700889 // If Omaha says to disable p2p, respect that
890 if (output_object.disable_p2p_for_downloading) {
891 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
892 << "requested by Omaha.";
893 params_->set_use_p2p_for_downloading(false);
894 }
895 if (output_object.disable_p2p_for_sharing) {
896 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
897 << "requested by Omaha.";
898 params_->set_use_p2p_for_sharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700899 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800900
901 // Update the payload state with the current response. The payload state
902 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800903 // from what's stored already. We are updating the payload state as late
904 // as possible in this method so that if a new release gets pushed and then
905 // got pulled back due to some issues, we don't want to clear our internal
906 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800907 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800908 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800909
David Zeuthen8f191b22013-08-06 12:27:50 -0700910 // It could be we've already exceeded the deadline for when p2p is
911 // allowed or that we've tried too many times with p2p. Check that.
912 if (params_->use_p2p_for_downloading()) {
913 payload_state->P2PNewAttempt();
914 if (!payload_state->P2PAttemptAllowed()) {
915 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
916 << "of previous failures when using p2p.";
917 params_->set_use_p2p_for_downloading(false);
918 }
919 }
920
921 // From here on, we'll complete stuff in CompleteProcessing() so
922 // disable |completer| since we'll create a new one in that
923 // function.
924 completer.set_should_complete(false);
925
926 // If we're allowed to use p2p for downloading we do not pay
927 // attention to wall-clock-based waiting if the URL is indeed
928 // available via p2p. Therefore, check if the file is available via
929 // p2p before deferring...
930 if (params_->use_p2p_for_downloading()) {
931 LookupPayloadViaP2P(output_object);
932 } else {
933 CompleteProcessing();
934 }
935}
936
937void OmahaRequestAction::CompleteProcessing() {
938 ScopedActionCompleter completer(processor_, this);
939 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
940 PayloadStateInterface* payload_state = system_state_->payload_state();
941
942 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800943 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -0700944 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
945 completer.set_code(kErrorCodeOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -0800946 return;
947 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700948
Chris Sosa20f005c2013-09-05 13:53:08 -0700949 if (payload_state->ShouldBackoffDownload()) {
950 output_object.update_exists = false;
951 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
952 << "attempts";
953 completer.set_code(kErrorCodeOmahaUpdateDeferredForBackoff);
954 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700955 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700956 completer.set_code(kErrorCodeSuccess);
957}
958
959void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
960 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
961 if (!url.empty()) {
962 params_->set_p2p_url(url);
963 } else {
964 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
965 << "because no suitable peer could be found.";
966 params_->set_use_p2p_for_downloading(false);
967 }
968 CompleteProcessing();
969}
970
971void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -0700972 // If the device is in the middle of an update, the state variables
973 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
974 // tracks the offset and length of the operation currently in
975 // progress. The offset is based from the end of the manifest which
976 // is kPrefsManifestMetadataSize bytes long.
977 //
978 // To make forward progress and avoid deadlocks, we need to find a
979 // peer that has at least the entire operation we're currently
980 // working on. Otherwise we may end up in a situation where two
981 // devices bounce back and forth downloading from each other,
982 // neither making any forward progress until one of them decides to
983 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
984 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -0700985 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -0700986 int64_t manifest_metadata_size = 0;
987 int64_t next_data_offset = 0;
988 int64_t next_data_length = 0;
David Zeuthen8f191b22013-08-06 12:27:50 -0700989 if (system_state_ != NULL &&
David Zeuthen41996ad2013-09-24 15:43:24 -0700990 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
991 &manifest_metadata_size) &&
992 manifest_metadata_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -0700993 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -0700994 &next_data_offset) &&
995 next_data_offset != -1 &&
996 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
997 &next_data_length)) {
998 minimum_size = manifest_metadata_size + next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -0700999 }
1000
1001 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
1002 if (system_state_->p2p_manager() != NULL) {
1003 LOG(INFO) << "Checking if payload is available via p2p, file_id="
1004 << file_id << " minimum_size=" << minimum_size;
1005 system_state_->p2p_manager()->LookupUrlForFile(
1006 file_id,
1007 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001008 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001009 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1010 base::Unretained(this)));
1011 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001012}
1013
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001014bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001015 if (params_->interactive()) {
1016 LOG(INFO) << "Not deferring download because update is interactive.";
1017 return false;
1018 }
1019
David Zeuthen8f191b22013-08-06 12:27:50 -07001020 // If we're using p2p to download _and_ we have a p2p URL, we never
1021 // defer the download. This is because the download will always
1022 // happen from a peer on the LAN and we've been waiting in line for
1023 // our turn.
1024 if (params_->use_p2p_for_downloading() && !params_->p2p_url().empty()) {
1025 LOG(INFO) << "Download not deferred because download "
1026 << "will happen from a local peer (via p2p).";
1027 return false;
1028 }
1029
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001030 // We should defer the downloads only if we've first satisfied the
1031 // wall-clock-based-waiting period and then the update-check-based waiting
1032 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001033 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001034 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1035 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001036 return false;
1037 }
1038
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001039 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001040 case kWallClockWaitNotSatisfied:
1041 // We haven't even satisfied the first condition, passing the
1042 // wall-clock-based waiting period, so we should defer the downloads
1043 // until that happens.
1044 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1045 return true;
1046
1047 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1048 LOG(INFO) << "wall-clock-based-wait satisfied and "
1049 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001050 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001051
1052 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1053 // Wall-clock-based waiting period is satisfied, and it's determined
1054 // that we do not need the update-check-based wait. so no need to
1055 // defer downloads.
1056 LOG(INFO) << "wall-clock-based-wait satisfied and "
1057 << "update-check-based-wait is not required.";
1058 return false;
1059
1060 default:
1061 // Returning false for this default case so we err on the
1062 // side of downloading updates than deferring in case of any bugs.
1063 NOTREACHED();
1064 return false;
1065 }
1066}
1067
1068OmahaRequestAction::WallClockWaitResult
1069OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001070 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001071 Time update_first_seen_at;
1072 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001073
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001074 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1075 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1076 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001077 // Note: This timestamp could be that of ANY update we saw in the past
1078 // (not necessarily this particular update we're considering to apply)
1079 // but never got to apply because of some reason (e.g. stop AU policy,
1080 // updates being pulled out from Omaha, changes in target version prefix,
1081 // new update being rolled out, etc.). But for the purposes of scattering
1082 // it doesn't matter which update the timestamp corresponds to. i.e.
1083 // the clock starts ticking the first time we see an update and we're
1084 // ready to apply when the random wait period is satisfied relative to
1085 // that first seen timestamp.
1086 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1087 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1088 << utils::ToString(update_first_seen_at);
1089 } else {
1090 // This seems like an unexpected error where the persisted value exists
1091 // but it's not readable for some reason. Just skip scattering in this
1092 // case to be safe.
1093 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1094 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1095 }
1096 } else {
1097 update_first_seen_at = Time::Now();
1098 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001099 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1100 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001101 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1102 << utils::ToString(update_first_seen_at);
1103 }
1104 else {
1105 // 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) {
1306 case kErrorCodeSuccess:
1307 // 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
1322 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
1323 result = metrics::CheckResult::kUpdateAvailable;
1324 reaction = metrics::CheckReaction::kIgnored;
1325 break;
1326
1327 case kErrorCodeOmahaUpdateDeferredPerPolicy:
1328 result = metrics::CheckResult::kUpdateAvailable;
1329 reaction = metrics::CheckReaction::kDeferring;
1330 break;
1331
1332 case kErrorCodeOmahaUpdateDeferredForBackoff:
1333 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();
1365 if(!rollback_version.empty()) {
1366 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
1367 if(rollback_version == response.version) {
1368 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1369 return true;
1370 }
1371 }
1372
1373 if(!IsUpdateAllowedOverCurrentConnection()) {
1374 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