blob: 9c5bbf59e8987d931febde2bfc3453e32e8d278f [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"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000030#include "update_engine/utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000031
Darin Petkov1cbd78f2010-07-29 12:38:34 -070032using base::Time;
33using base::TimeDelta;
rspangler@google.com49fdf182009-10-10 00:57:34 +000034using std::string;
35
36namespace chromeos_update_engine {
37
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080038// List of custom pair tags that we interpret in the Omaha Response:
39static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080040static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070041static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080042// Deprecated: "IsDelta"
43static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080044static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
45static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
46// Deprecated: "ManifestSignatureRsa"
47// Deprecated: "ManifestSize"
48static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
49static const char* kTagMetadataSize = "MetadataSize";
50static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070051// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080052static const char* kTagPrompt = "Prompt";
53static const char* kTagSha256 = "sha256";
David Zeuthen8f191b22013-08-06 12:27:50 -070054static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
55static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
David Zeuthene7f89172013-10-31 10:21:04 -070056static const char* kTagPublicKeyRsa = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080057
rspangler@google.com49fdf182009-10-10 00:57:34 +000058namespace {
59
60const string kGupdateVersion("ChromeOSUpdateEngine-0.1.0.0");
61
62// This is handy for passing strings into libxml2
63#define ConstXMLStr(x) (reinterpret_cast<const xmlChar*>(x))
64
Ben Chan075248b2014-04-24 12:04:14 -070065// These are for scoped_ptr with a custom free function to be specified.
rspangler@google.com49fdf182009-10-10 00:57:34 +000066class ScopedPtrXmlDocFree {
67 public:
68 inline void operator()(void* x) const {
69 xmlFreeDoc(reinterpret_cast<xmlDoc*>(x));
70 }
71};
72class ScopedPtrXmlFree {
73 public:
74 inline void operator()(void* x) const {
75 xmlFree(x);
76 }
77};
78class ScopedPtrXmlXPathObjectFree {
79 public:
80 inline void operator()(void* x) const {
81 xmlXPathFreeObject(reinterpret_cast<xmlXPathObject*>(x));
82 }
83};
84class ScopedPtrXmlXPathContextFree {
85 public:
86 inline void operator()(void* x) const {
87 xmlXPathFreeContext(reinterpret_cast<xmlXPathContext*>(x));
88 }
89};
90
Darin Petkov1cbd78f2010-07-29 12:38:34 -070091// Returns true if |ping_days| has a value that needs to be sent,
92// false otherwise.
93bool ShouldPing(int ping_days) {
94 return ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged;
95}
96
97// Returns an XML ping element attribute assignment with attribute
98// |name| and value |ping_days| if |ping_days| has a value that needs
99// to be sent, or an empty string otherwise.
100string GetPingAttribute(const string& name, int ping_days) {
101 if (ShouldPing(ping_days)) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700102 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700103 }
104 return "";
105}
106
107// Returns an XML ping element if any of the elapsed days need to be
108// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700109string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700110 string ping_active = GetPingAttribute("a", ping_active_days);
111 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
112 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700113 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700114 ping_active.c_str(),
115 ping_roll_call.c_str());
116 }
117 return "";
118}
119
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700120// Returns an XML that goes into the body of the <app> element of the Omaha
121// request based on the given parameters.
122string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700123 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700124 bool ping_only,
125 int ping_active_days,
126 int ping_roll_call_days,
127 PrefsInterface* prefs) {
128 string app_body;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700129 if (event == NULL) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700130 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700131 if (!ping_only) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700132 // not passing update_disabled to Omaha because we want to
133 // get the update and report with UpdateDeferred result so that
134 // borgmon charts show up updates that are deferred. This is also
135 // the expected behavior when we move to Omaha v3.0 protocol, so it'll
136 // be consistent.
Alex Vakulenko75039d72014-03-25 12:36:28 -0700137 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700138 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700139 "></updatecheck>\n",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700140 XmlEncode(params->target_version_prefix()).c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700141
Darin Petkov265f2902011-05-09 15:17:40 -0700142 // If this is the first update check after a reboot following a previous
143 // update, generate an event containing the previous version number. If
144 // the previous version preference file doesn't exist the event is still
145 // generated with a previous version of 0.0.0.0 -- this is relevant for
146 // older clients or new installs. The previous version event is not sent
147 // for ping-only requests because they come before the client has
148 // rebooted.
149 string prev_version;
150 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
151 prev_version = "0.0.0.0";
152 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700153
Alex Vakulenko75039d72014-03-25 12:36:28 -0700154 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700155 " <event eventtype=\"%d\" eventresult=\"%d\" "
156 "previousversion=\"%s\"></event>\n",
157 OmahaEvent::kTypeUpdateComplete,
158 OmahaEvent::kResultSuccessReboot,
159 XmlEncode(prev_version).c_str());
160 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
161 << "Unable to reset the previous version.";
Darin Petkov95508da2011-01-05 12:42:29 -0800162 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700163 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800164 // The error code is an optional attribute so append it only if the result
165 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700166 string error_code;
167 if (event->result != OmahaEvent::kResultSuccess) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700168 error_code = base::StringPrintf(" errorcode=\"%d\"", event->error_code);
Darin Petkove17f86b2010-07-20 09:12:01 -0700169 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700170 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700171 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700172 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700173 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700174
175 return app_body;
176}
177
178// Returns an XML that corresponds to the entire <app> node of the Omaha
179// request based on the given parameters.
180string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700181 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700182 bool ping_only,
183 int ping_active_days,
184 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800185 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700186 SystemState* system_state) {
187 string app_body = GetAppBody(event, params, ping_only, ping_active_days,
188 ping_roll_call_days, system_state->prefs());
189 string app_versions;
190
191 // If we are upgrading to a more stable channel and we are allowed to do
192 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
193 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700194 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700195 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
196 << "on downgrading to the version in the more stable channel";
197 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700198 XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700199 } else {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700200 app_versions = "version=\"" + XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700201 }
202
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700203 string download_channel = params->download_channel();
204 string app_channels = "track=\"" + XmlEncode(download_channel) + "\" ";
205 if (params->current_channel() != download_channel)
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700206 app_channels +=
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700207 "from_track=\"" + XmlEncode(params->current_channel()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700208
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700209 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700210
David Zeuthen639aa362014-02-03 16:23:44 -0800211 // If install_date_days is not set (e.g. its value is -1 ), don't
212 // include the attribute.
213 string install_date_in_days_str = "";
214 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700215 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
216 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800217 }
218
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700219 string app_xml =
Jay Srinivasandb0acdf2013-04-02 14:47:45 -0700220 " <app appid=\"" + XmlEncode(params->GetAppId()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700221 app_versions +
222 app_channels +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700223 "lang=\"" + XmlEncode(params->app_lang()) + "\" " +
224 "board=\"" + XmlEncode(params->os_board()) + "\" " +
225 "hardware_class=\"" + XmlEncode(params->hwid()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700226 "delta_okay=\"" + delta_okay_str + "\" "
Chris Sosac1972482013-04-30 22:31:10 -0700227 "fw_version=\"" + XmlEncode(params->fw_version()) + "\" " +
228 "ec_version=\"" + XmlEncode(params->ec_version()) + "\" " +
David Zeuthen639aa362014-02-03 16:23:44 -0800229 install_date_in_days_str +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700230 ">\n" +
231 app_body +
232 " </app>\n";
233
234 return app_xml;
235}
236
237// Returns an XML that corresponds to the entire <os> node of the Omaha
238// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700239string GetOsXml(OmahaRequestParams* params) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700240 string os_xml =
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700241 " <os version=\"" + XmlEncode(params->os_version()) + "\" " +
242 "platform=\"" + XmlEncode(params->os_platform()) + "\" " +
243 "sp=\"" + XmlEncode(params->os_sp()) + "\">"
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700244 "</os>\n";
245 return os_xml;
246}
247
248// Returns an XML that corresponds to the entire Omaha request based on the
249// given parameters.
250string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700251 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700252 bool ping_only,
253 int ping_active_days,
254 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800255 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700256 SystemState* system_state) {
257 string os_xml = GetOsXml(params);
258 string app_xml = GetAppXml(event, params, ping_only, ping_active_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800259 ping_roll_call_days, install_date_in_days,
260 system_state);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700261
Alex Vakulenko75039d72014-03-25 12:36:28 -0700262 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700263 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700264
265 string request_xml =
266 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700267 "<request protocol=\"3.0\" "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700268 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
269 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" " +
270 install_source +
271 "ismachine=\"1\">\n" +
272 os_xml +
273 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700274 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700275
276 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000277}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700278
rspangler@google.com49fdf182009-10-10 00:57:34 +0000279} // namespace {}
280
281// Encodes XML entities in a given string with libxml2. input must be
282// UTF-8 formatted. Output will be UTF-8 formatted.
283string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700284 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
285 // // cpu, considering creating one and caching it.
Ben Chan075248b2014-04-24 12:04:14 -0700286 // scoped_ptr<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
Darin Petkov6a5b3222010-07-13 14:55:28 -0700287 // xmlNewDoc(ConstXMLStr("1.0")));
288 // if (!xml_doc.get()) {
289 // LOG(ERROR) << "Unable to create xmlDoc";
290 // return "";
291 // }
Ben Chan075248b2014-04-24 12:04:14 -0700292 scoped_ptr<xmlChar, ScopedPtrXmlFree> str(
rspangler@google.com49fdf182009-10-10 00:57:34 +0000293 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
294 return string(reinterpret_cast<const char *>(str.get()));
295}
296
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800297OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700298 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700299 HttpFetcher* http_fetcher,
300 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800301 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700302 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700303 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700304 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700305 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700306 ping_roll_call_days_(0) {
307 params_ = system_state->request_params();
308}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000309
Darin Petkov6a5b3222010-07-13 14:55:28 -0700310OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000311
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700312// Calculates the value to use for the ping days parameter.
313int OmahaRequestAction::CalculatePingDays(const string& key) {
314 int days = kNeverPinged;
315 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800316 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700317 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
318 if (days < 0) {
319 // If |days| is negative, then the system clock must have jumped
320 // back in time since the ping was sent. Mark the value so that
321 // it doesn't get sent to the server but we still update the
322 // last ping daystart preference. This way the next ping time
323 // will be correct, hopefully.
324 days = kPingTimeJump;
325 LOG(WARNING) <<
326 "System clock jumped back in time. Resetting ping daystarts.";
327 }
328 }
329 return days;
330}
331
332void OmahaRequestAction::InitPingDays() {
333 // We send pings only along with update checks, not with events.
334 if (IsEvent()) {
335 return;
336 }
337 // TODO(petkov): Figure a way to distinguish active use pings
338 // vs. roll call pings. Currently, the two pings are identical. A
339 // fix needs to change this code as well as UpdateLastPingDays.
340 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
341 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
342}
343
David Zeuthen639aa362014-02-03 16:23:44 -0800344// static
345int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
346 PrefsInterface* prefs = system_state->prefs();
347 if (prefs == NULL)
348 return -1;
349
350 // If we have the value stored on disk, just return it.
351 int64_t stored_value;
352 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
353 // Convert and sanity-check.
354 int install_date_days = static_cast<int>(stored_value);
355 if (install_date_days >= 0)
356 return install_date_days;
357 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
358 << install_date_days << " looks suspicious.";
359 prefs->Delete(kPrefsInstallDateDays);
360 }
361
362 // Otherwise, if OOBE is not complete then do nothing and wait for
363 // ParseResponse() to call ParseInstallDate() and then
364 // PersistInstallDate() to set the kPrefsInstallDateDays state
365 // variable. Once that is done, we'll then report back in future
366 // Omaha requests. This works exactly because OOBE triggers an
367 // update check.
368 //
369 // However, if OOBE is complete and the kPrefsInstallDateDays state
370 // variable is not set, there are two possibilities
371 //
372 // 1. The update check in OOBE failed so we never got a response
373 // from Omaha (no network etc.); or
374 //
375 // 2. OOBE was done on an older version that didn't write to the
376 // kPrefsInstallDateDays state variable.
377 //
378 // In both cases, we approximate the install date by simply
379 // inspecting the timestamp of when OOBE happened.
380
381 Time time_of_oobe;
Alex Deymobccbc382014-04-03 13:38:55 -0700382 if (!system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800383 LOG(INFO) << "Not generating Omaha InstallData as we have "
384 << "no prefs file and OOBE is not complete.";
385 return -1;
386 }
387
388 int num_days;
389 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
390 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
391 << "as its value '" << utils::ToString(time_of_oobe)
392 << "' looks suspicious.";
393 return -1;
394 }
395
396 // Persist this to disk, for future use.
397 if (!OmahaRequestAction::PersistInstallDate(system_state,
398 num_days,
399 kProvisionedFromOOBEMarker))
400 return -1;
401
402 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
403 << num_days << " days";
404
405 return num_days;
406}
407
Darin Petkov6a5b3222010-07-13 14:55:28 -0700408void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000409 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700410 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700411 if (ping_only_ &&
412 !ShouldPing(ping_active_days_) &&
413 !ShouldPing(ping_roll_call_days_)) {
David Zeuthena99981f2013-04-29 13:42:47 -0700414 processor_->ActionComplete(this, kErrorCodeSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700415 return;
416 }
David Zeuthen639aa362014-02-03 16:23:44 -0800417
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700418 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700419 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700420 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700421 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800422 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800423 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700424 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700425
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800426 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
427 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700428 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700429 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700430 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000431}
432
Darin Petkov6a5b3222010-07-13 14:55:28 -0700433void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000434 http_fetcher_->TerminateTransfer();
435}
436
437// We just store the response in the buffer. Once we've received all bytes,
438// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700439void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
440 const char* bytes,
441 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000442 response_buffer_.reserve(response_buffer_.size() + length);
443 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
444}
445
446namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000447// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
448// on the returned object.
449// This code is roughly based on the libxml tutorial at:
450// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700451xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000452 xmlXPathObject* result = NULL;
453
Ben Chan075248b2014-04-24 12:04:14 -0700454 scoped_ptr<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
rspangler@google.com49fdf182009-10-10 00:57:34 +0000455 xmlXPathNewContext(doc));
456 if (!context.get()) {
457 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
458 return NULL;
459 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000460
461 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000462 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700463 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000464 return NULL;
465 }
466 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700467 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000468 xmlXPathFreeObject(result);
469 return NULL;
470 }
471 return result;
472}
473
474// Returns the string value of a named attribute on a node, or empty string
475// if no such node exists. If the attribute exists and has a value of
476// empty string, there's no way to distinguish that from the attribute
477// not existing.
478string XmlGetProperty(xmlNode* node, const char* name) {
479 if (!xmlHasProp(node, ConstXMLStr(name)))
480 return "";
Ben Chan075248b2014-04-24 12:04:14 -0700481 scoped_ptr<xmlChar, ScopedPtrXmlFree> str(
rspangler@google.com49fdf182009-10-10 00:57:34 +0000482 xmlGetProp(node, ConstXMLStr(name)));
483 string ret(reinterpret_cast<const char *>(str.get()));
484 return ret;
485}
486
487// Parses a 64 bit base-10 int from a string and returns it. Returns 0
488// on error. If the string contains "0", that's indistinguishable from
489// error.
490off_t ParseInt(const string& str) {
491 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700492 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000493 if (rc < 1) {
494 // failure
495 return 0;
496 }
497 return ret;
498}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700499
500// Update the last ping day preferences based on the server daystart
501// response. Returns true on success, false otherwise.
502bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700503 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700504
Ben Chan075248b2014-04-24 12:04:14 -0700505 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700506 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700507 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
508 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
509 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
510 xmlNode* daystart_node = nodeset->nodeTab[0];
511 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
512 ConstXMLStr("elapsed_seconds")));
513
514 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700515 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
516 "elapsed_seconds"),
517 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700518 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
519
520 // Remember the local time that matches the server's last midnight
521 // time.
522 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
523 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
524 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
525 return true;
526}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000527} // namespace {}
528
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700529bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
530 OmahaResponse* output_object,
531 ScopedActionCompleter* completer) {
532 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
533
Ben Chan075248b2014-04-24 12:04:14 -0700534 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700535 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
536 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700537 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700538 return false;
539 }
540
541 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
542 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
543 CHECK_GE(nodeset->nodeNr, 1);
544 xmlNode* update_check_node = nodeset->nodeTab[0];
545
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800546 // chromium-os:37289: The PollInterval is not supported by Omaha server
547 // currently. But still keeping this existing code in case we ever decide to
548 // slow down the request rate from the server-side. Note that the
549 // PollInterval is not persisted, so it has to be sent by the server on every
550 // response to guarantee that the UpdateCheckScheduler uses this value
551 // (otherwise, if the device got rebooted after the last server-indicated
552 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
553 // value for the scattering logic is based on the assumption that we perform
554 // an update check every hour so that the max value of 8 will roughly be
555 // equivalent to one work day. If we decide to use PollInterval permanently,
556 // we should update the max_update_checks_allowed to take PollInterval into
557 // account. Note: The parsing for PollInterval happens even before parsing
558 // of the status because we may want to specify the PollInterval even when
559 // there's no update.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700560 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
561 &output_object->poll_interval);
562
David Zeuthen639aa362014-02-03 16:23:44 -0800563 // Check for the "elapsed_days" attribute in the "daystart"
564 // element. This is the number of days since Jan 1 2007, 0:00
565 // PST. If we don't have a persisted value of the Omaha InstallDate,
566 // we'll use it to calculate it and then persist it.
567 if (ParseInstallDate(doc, output_object) && !HasInstallDate(system_state_)) {
568 // Since output_object->install_date_days is never negative, the
569 // elapsed_days -> install-date calculation is reduced to simply
570 // rounding down to the nearest number divisible by 7.
571 int remainder = output_object->install_date_days % 7;
572 int install_date_days_rounded =
573 output_object->install_date_days - remainder;
574 if (PersistInstallDate(system_state_,
575 install_date_days_rounded,
576 kProvisionedFromOmahaResponse)) {
577 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
578 << install_date_days_rounded << " days";
579 }
580 }
581
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700582 if (!ParseStatus(update_check_node, output_object, completer))
583 return false;
584
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800585 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
586 // appends the package name to the URLs populated in this method.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700587 if (!ParseUrls(doc, output_object, completer))
588 return false;
589
590 if (!ParsePackage(doc, output_object, completer))
591 return false;
592
593 if (!ParseParams(doc, output_object, completer))
594 return false;
595
596 return true;
597}
598
599bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
600 OmahaResponse* output_object,
601 ScopedActionCompleter* completer) {
602 // Get status.
603 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
604 LOG(ERROR) << "Omaha Response missing status";
David Zeuthena99981f2013-04-29 13:42:47 -0700605 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700606 return false;
607 }
608
609 const string status(XmlGetProperty(update_check_node, "status"));
610 if (status == "noupdate") {
611 LOG(INFO) << "No update.";
612 output_object->update_exists = false;
613 SetOutputObject(*output_object);
David Zeuthena99981f2013-04-29 13:42:47 -0700614 completer->set_code(kErrorCodeSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700615 return false;
616 }
617
618 if (status != "ok") {
619 LOG(ERROR) << "Unknown Omaha response status: " << status;
David Zeuthena99981f2013-04-29 13:42:47 -0700620 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700621 return false;
622 }
623
624 return true;
625}
626
627bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
628 OmahaResponse* output_object,
629 ScopedActionCompleter* completer) {
630 // Get the update URL.
631 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
632
Ben Chan075248b2014-04-24 12:04:14 -0700633 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700634 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
635 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700636 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700637 return false;
638 }
639
640 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
641 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
642 CHECK_GE(nodeset->nodeNr, 1);
643
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800644 LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)";
645 output_object->payload_urls.clear();
646 for (int i = 0; i < nodeset->nodeNr; i++) {
647 xmlNode* url_node = nodeset->nodeTab[i];
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800648 const string codebase(XmlGetProperty(url_node, "codebase"));
649 if (codebase.empty()) {
650 LOG(ERROR) << "Omaha Response URL has empty codebase";
David Zeuthena99981f2013-04-29 13:42:47 -0700651 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800652 return false;
653 }
654 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700655 }
656
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700657 return true;
658}
659
660bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
661 OmahaResponse* output_object,
662 ScopedActionCompleter* completer) {
663 // Get the package node.
664 static const char* kPackageNodeXPath(
665 "/response/app/updatecheck/manifest/packages/package");
666
Ben Chan075248b2014-04-24 12:04:14 -0700667 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700668 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
669 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700670 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700671 return false;
672 }
673
674 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
675 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
676 CHECK_GE(nodeset->nodeNr, 1);
677
678 // We only care about the first package.
679 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
680 xmlNode* package_node = nodeset->nodeTab[0];
681
682 // Get package properties one by one.
683
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800684 // Parse the payload name to be appended to the base Url value.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700685 const string package_name(XmlGetProperty(package_node, "name"));
686 LOG(INFO) << "Omaha Response package name = " << package_name;
687 if (package_name.empty()) {
688 LOG(ERROR) << "Omaha Response has empty package name";
David Zeuthena99981f2013-04-29 13:42:47 -0700689 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700690 return false;
691 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800692
693 // Append the package name to each URL in our list so that we don't
694 // propagate the urlBase vs packageName distinctions beyond this point.
695 // From now on, we only need to use payload_urls.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700696 for (size_t i = 0; i < output_object->payload_urls.size(); i++)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800697 output_object->payload_urls[i] += package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700698
699 // Parse the payload size.
700 off_t size = ParseInt(XmlGetProperty(package_node, "size"));
701 if (size <= 0) {
702 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
David Zeuthena99981f2013-04-29 13:42:47 -0700703 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700704 return false;
705 }
706 output_object->size = size;
707
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800708 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700709
710 return true;
711}
712
713bool OmahaRequestAction::ParseParams(xmlDoc* doc,
714 OmahaResponse* output_object,
715 ScopedActionCompleter* completer) {
Chris Sosa3b748432013-06-20 16:42:59 -0700716 // XPath location for response elements we care about.
717 static const char* kManifestNodeXPath("/response/app/updatecheck/manifest");\
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700718 static const char* kActionNodeXPath(
Chris Sosa3b748432013-06-20 16:42:59 -0700719 "/response/app/updatecheck/manifest/actions/action");
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700720
Chris Sosa3b748432013-06-20 16:42:59 -0700721 // Get the manifest node where version is present.
Ben Chan075248b2014-04-24 12:04:14 -0700722 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Chris Sosa3b748432013-06-20 16:42:59 -0700723 xpath_manifest_nodeset(GetNodeSet(doc, ConstXMLStr(kManifestNodeXPath)));
724 if (!xpath_manifest_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700725 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700726 return false;
727 }
728
Chris Sosa3b748432013-06-20 16:42:59 -0700729 // Grab the only matching node there should be from the xpath.
730 xmlNodeSet* nodeset = xpath_manifest_nodeset->nodesetval;
731 CHECK(nodeset) << "XPath missing " << kManifestNodeXPath;
732 CHECK_GE(nodeset->nodeNr, 1);
733 xmlNode* manifest_node = nodeset->nodeTab[0];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700734
Chris Sosa3b748432013-06-20 16:42:59 -0700735 // Set the version.
736 output_object->version = XmlGetProperty(manifest_node, kTagVersion);
737 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700738 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Chris Sosa3b748432013-06-20 16:42:59 -0700739 completer->set_code(kErrorCodeOmahaResponseInvalid);
740 return false;
741 }
742
743 LOG(INFO) << "Received omaha response to update to version "
744 << output_object->version;
745
746 // Grab the action nodes.
Ben Chan075248b2014-04-24 12:04:14 -0700747 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Chris Sosa3b748432013-06-20 16:42:59 -0700748 xpath_action_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
749 if (!xpath_action_nodeset.get()) {
750 completer->set_code(kErrorCodeOmahaResponseInvalid);
751 return false;
752 }
753
754 // We only care about the action that has event "postinstall", because this is
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700755 // where Omaha puts all the generic name/value pairs in the rule.
Chris Sosa3b748432013-06-20 16:42:59 -0700756 nodeset = xpath_action_nodeset->nodesetval;
757 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700758 LOG(INFO) << "Found " << nodeset->nodeNr
759 << " action(s). Processing the postinstall action.";
760
761 // pie_action_node holds the action node corresponding to the
762 // postinstall event action, if present.
763 xmlNode* pie_action_node = NULL;
764 for (int i = 0; i < nodeset->nodeNr; i++) {
765 xmlNode* action_node = nodeset->nodeTab[i];
766 if (XmlGetProperty(action_node, "event") == "postinstall") {
767 pie_action_node = action_node;
768 break;
769 }
770 }
771
772 if (!pie_action_node) {
773 LOG(ERROR) << "Omaha Response has no postinstall event action";
David Zeuthena99981f2013-04-29 13:42:47 -0700774 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700775 return false;
776 }
777
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800778 output_object->hash = XmlGetProperty(pie_action_node, kTagSha256);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700779 if (output_object->hash.empty()) {
780 LOG(ERROR) << "Omaha Response has empty sha256 value";
David Zeuthena99981f2013-04-29 13:42:47 -0700781 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700782 return false;
783 }
784
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800785 // Get the optional properties one by one.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800786 output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700787 output_object->metadata_size =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800788 ParseInt(XmlGetProperty(pie_action_node, kTagMetadataSize));
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700789 output_object->metadata_signature =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800790 XmlGetProperty(pie_action_node, kTagMetadataSignatureRsa);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800791 output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true";
792 output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700793 output_object->max_days_to_scatter =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800794 ParseInt(XmlGetProperty(pie_action_node, kTagMaxDaysToScatter));
David Zeuthen8f191b22013-08-06 12:27:50 -0700795 output_object->disable_p2p_for_downloading =
796 (XmlGetProperty(pie_action_node, kTagDisableP2PForDownloading) == "true");
797 output_object->disable_p2p_for_sharing =
798 (XmlGetProperty(pie_action_node, kTagDisableP2PForSharing) == "true");
David Zeuthene7f89172013-10-31 10:21:04 -0700799 output_object->public_key_rsa =
800 XmlGetProperty(pie_action_node, kTagPublicKeyRsa);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800801
802 string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl);
Jay Srinivasan08262882012-12-28 19:29:43 -0800803 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800804 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700805
Jay Srinivasan08262882012-12-28 19:29:43 -0800806 output_object->is_delta_payload =
807 XmlGetProperty(pie_action_node, kTagIsDeltaPayload) == "true";
808
809 output_object->disable_payload_backoff =
810 XmlGetProperty(pie_action_node, kTagDisablePayloadBackoff) == "true";
811
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700812 return true;
813}
814
rspangler@google.com49fdf182009-10-10 00:57:34 +0000815// If the transfer was successful, this uses libxml2 to parse the response
816// and fill in the appropriate fields of the output object. Also, notifies
817// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700818void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
819 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000820 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800821 string current_response(response_buffer_.begin(), response_buffer_.end());
822 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700823
824 // Events are best effort transactions -- assume they always succeed.
825 if (IsEvent()) {
826 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800827 if (event_->result == OmahaEvent::kResultError && successful &&
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700828 system_state_->hardware()->IsOfficialBuild()) {
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800829 LOG(INFO) << "Signalling Crash Reporter.";
830 utils::ScheduleCrashReporterUpload();
831 }
David Zeuthena99981f2013-04-29 13:42:47 -0700832 completer.set_code(kErrorCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700833 return;
834 }
835
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700836 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700837 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700838 int code = GetHTTPResponseCode();
839 // Makes sure we send sane error values.
840 if (code < 0 || code >= 1000) {
841 code = 999;
842 }
David Zeuthena99981f2013-04-29 13:42:47 -0700843 completer.set_code(static_cast<ErrorCode>(
844 kErrorCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000845 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700846 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000847
848 // parse our response and fill the fields in the output object
Ben Chan075248b2014-04-24 12:04:14 -0700849 scoped_ptr<xmlDoc, ScopedPtrXmlDocFree> doc(
rspangler@google.com49fdf182009-10-10 00:57:34 +0000850 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
851 if (!doc.get()) {
852 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700853 completer.set_code(response_buffer_.empty() ?
David Zeuthena99981f2013-04-29 13:42:47 -0700854 kErrorCodeOmahaRequestEmptyResponseError :
855 kErrorCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000856 return;
857 }
858
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700859 // If a ping was sent, update the last ping day preferences based on
860 // the server daystart response.
861 if (ShouldPing(ping_active_days_) ||
862 ShouldPing(ping_roll_call_days_) ||
863 ping_active_days_ == kPingTimeJump ||
864 ping_roll_call_days_ == kPingTimeJump) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800865 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700866 << "Failed to update the last ping day preferences!";
867 }
868
Thieu Le116fda32011-04-19 11:01:54 -0700869 if (!HasOutputPipe()) {
870 // Just set success to whether or not the http transfer succeeded,
871 // which must be true at this point in the code.
David Zeuthena99981f2013-04-29 13:42:47 -0700872 completer.set_code(kErrorCodeSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700873 return;
874 }
875
Darin Petkov6a5b3222010-07-13 14:55:28 -0700876 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700877 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000878 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700879 output_object.update_exists = true;
880 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000881
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700882 if (params_->update_disabled()) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700883 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
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 Srinivasan34b5d862012-07-23 11:43:22 -0700886 // Note: We could technically delete the UpdateFirstSeenAt state here.
887 // If we do, it'll mean a device has to restart the UpdateFirstSeenAt
888 // and thus help scattering take effect when the AU is turned on again.
889 // On the other hand, it also increases the chance of update starvation if
890 // an admin turns AU on/off more frequently. We choose to err on the side
891 // of preventing starvation at the cost of not applying scattering in
892 // those cases.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700893 return;
894 }
895
David Zeuthen8f191b22013-08-06 12:27:50 -0700896 // If Omaha says to disable p2p, respect that
897 if (output_object.disable_p2p_for_downloading) {
898 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
899 << "requested by Omaha.";
900 params_->set_use_p2p_for_downloading(false);
901 }
902 if (output_object.disable_p2p_for_sharing) {
903 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
904 << "requested by Omaha.";
905 params_->set_use_p2p_for_sharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700906 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800907
908 // Update the payload state with the current response. The payload state
909 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800910 // from what's stored already. We are updating the payload state as late
911 // as possible in this method so that if a new release gets pushed and then
912 // got pulled back due to some issues, we don't want to clear our internal
913 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800914 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800915 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800916
David Zeuthen8f191b22013-08-06 12:27:50 -0700917 // It could be we've already exceeded the deadline for when p2p is
918 // allowed or that we've tried too many times with p2p. Check that.
919 if (params_->use_p2p_for_downloading()) {
920 payload_state->P2PNewAttempt();
921 if (!payload_state->P2PAttemptAllowed()) {
922 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
923 << "of previous failures when using p2p.";
924 params_->set_use_p2p_for_downloading(false);
925 }
926 }
927
928 // From here on, we'll complete stuff in CompleteProcessing() so
929 // disable |completer| since we'll create a new one in that
930 // function.
931 completer.set_should_complete(false);
932
933 // If we're allowed to use p2p for downloading we do not pay
934 // attention to wall-clock-based waiting if the URL is indeed
935 // available via p2p. Therefore, check if the file is available via
936 // p2p before deferring...
937 if (params_->use_p2p_for_downloading()) {
938 LookupPayloadViaP2P(output_object);
939 } else {
940 CompleteProcessing();
941 }
942}
943
944void OmahaRequestAction::CompleteProcessing() {
945 ScopedActionCompleter completer(processor_, this);
946 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
947 PayloadStateInterface* payload_state = system_state_->payload_state();
948
949 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800950 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -0700951 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
952 completer.set_code(kErrorCodeOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -0800953 return;
954 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700955
Chris Sosa20f005c2013-09-05 13:53:08 -0700956 if (payload_state->ShouldBackoffDownload()) {
957 output_object.update_exists = false;
958 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
959 << "attempts";
960 completer.set_code(kErrorCodeOmahaUpdateDeferredForBackoff);
961 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700962 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700963 completer.set_code(kErrorCodeSuccess);
964}
965
966void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
967 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
968 if (!url.empty()) {
969 params_->set_p2p_url(url);
970 } else {
971 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
972 << "because no suitable peer could be found.";
973 params_->set_use_p2p_for_downloading(false);
974 }
975 CompleteProcessing();
976}
977
978void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -0700979 // If the device is in the middle of an update, the state variables
980 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
981 // tracks the offset and length of the operation currently in
982 // progress. The offset is based from the end of the manifest which
983 // is kPrefsManifestMetadataSize bytes long.
984 //
985 // To make forward progress and avoid deadlocks, we need to find a
986 // peer that has at least the entire operation we're currently
987 // working on. Otherwise we may end up in a situation where two
988 // devices bounce back and forth downloading from each other,
989 // neither making any forward progress until one of them decides to
990 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
991 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -0700992 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -0700993 int64_t manifest_metadata_size = 0;
994 int64_t next_data_offset = 0;
995 int64_t next_data_length = 0;
David Zeuthen8f191b22013-08-06 12:27:50 -0700996 if (system_state_ != NULL &&
David Zeuthen41996ad2013-09-24 15:43:24 -0700997 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
998 &manifest_metadata_size) &&
999 manifest_metadata_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001000 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001001 &next_data_offset) &&
1002 next_data_offset != -1 &&
1003 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1004 &next_data_length)) {
1005 minimum_size = manifest_metadata_size + next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001006 }
1007
1008 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
1009 if (system_state_->p2p_manager() != NULL) {
1010 LOG(INFO) << "Checking if payload is available via p2p, file_id="
1011 << file_id << " minimum_size=" << minimum_size;
1012 system_state_->p2p_manager()->LookupUrlForFile(
1013 file_id,
1014 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001015 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001016 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1017 base::Unretained(this)));
1018 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001019}
1020
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001021bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001022 if (params_->interactive()) {
1023 LOG(INFO) << "Not deferring download because update is interactive.";
1024 return false;
1025 }
1026
David Zeuthen8f191b22013-08-06 12:27:50 -07001027 // If we're using p2p to download _and_ we have a p2p URL, we never
1028 // defer the download. This is because the download will always
1029 // happen from a peer on the LAN and we've been waiting in line for
1030 // our turn.
1031 if (params_->use_p2p_for_downloading() && !params_->p2p_url().empty()) {
1032 LOG(INFO) << "Download not deferred because download "
1033 << "will happen from a local peer (via p2p).";
1034 return false;
1035 }
1036
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001037 // We should defer the downloads only if we've first satisfied the
1038 // wall-clock-based-waiting period and then the update-check-based waiting
1039 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001040 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001041 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1042 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001043 return false;
1044 }
1045
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001046 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001047 case kWallClockWaitNotSatisfied:
1048 // We haven't even satisfied the first condition, passing the
1049 // wall-clock-based waiting period, so we should defer the downloads
1050 // until that happens.
1051 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1052 return true;
1053
1054 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1055 LOG(INFO) << "wall-clock-based-wait satisfied and "
1056 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001057 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001058
1059 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1060 // Wall-clock-based waiting period is satisfied, and it's determined
1061 // that we do not need the update-check-based wait. so no need to
1062 // defer downloads.
1063 LOG(INFO) << "wall-clock-based-wait satisfied and "
1064 << "update-check-based-wait is not required.";
1065 return false;
1066
1067 default:
1068 // Returning false for this default case so we err on the
1069 // side of downloading updates than deferring in case of any bugs.
1070 NOTREACHED();
1071 return false;
1072 }
1073}
1074
1075OmahaRequestAction::WallClockWaitResult
1076OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001077 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001078 Time update_first_seen_at;
1079 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001080
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001081 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1082 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1083 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001084 // Note: This timestamp could be that of ANY update we saw in the past
1085 // (not necessarily this particular update we're considering to apply)
1086 // but never got to apply because of some reason (e.g. stop AU policy,
1087 // updates being pulled out from Omaha, changes in target version prefix,
1088 // new update being rolled out, etc.). But for the purposes of scattering
1089 // it doesn't matter which update the timestamp corresponds to. i.e.
1090 // the clock starts ticking the first time we see an update and we're
1091 // ready to apply when the random wait period is satisfied relative to
1092 // that first seen timestamp.
1093 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1094 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1095 << utils::ToString(update_first_seen_at);
1096 } else {
1097 // This seems like an unexpected error where the persisted value exists
1098 // but it's not readable for some reason. Just skip scattering in this
1099 // case to be safe.
1100 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1101 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1102 }
1103 } else {
1104 update_first_seen_at = Time::Now();
1105 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001106 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1107 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001108 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1109 << utils::ToString(update_first_seen_at);
1110 }
1111 else {
1112 // This seems like an unexpected error where the value cannot be
1113 // persisted for some reason. Just skip scattering in this
1114 // case to be safe.
1115 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1116 << utils::ToString(update_first_seen_at)
1117 << " cannot be persisted";
1118 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1119 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001120 }
1121
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001122 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001123 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001124 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001125
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001126 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001127 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001128 << ", Time Elapsed = "
1129 << utils::FormatSecs(elapsed_time.InSeconds())
1130 << ", MaxDaysToScatter = "
1131 << max_scatter_period.InDays();
1132
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001133 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001134 // The deadline is set for all rules which serve a delta update from a
1135 // previous FSI, which means this update will be applied mostly in OOBE
1136 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1137 // quickly.
1138 LOG(INFO) << "Not scattering as deadline flag is set";
1139 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1140 }
1141
1142 if (max_scatter_period.InDays() == 0) {
1143 // This means the Omaha rule creator decides that this rule
1144 // should not be scattered irrespective of the policy.
1145 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1146 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1147 }
1148
1149 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001150 // This means we've waited more than the upperbound wait in the rule
1151 // from the time we first saw a valid update available to us.
1152 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001153 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1154 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1155 }
1156
1157 // This means we are required to participate in scattering.
1158 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001159 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001160 if (remaining_wait_time.InSeconds() <= 0) {
1161 // Yes, it's our turn now.
1162 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1163
1164 // But we can't download until the update-check-count-based wait is also
1165 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001166 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001167 kWallClockWaitDoneButUpdateCheckWaitRequired :
1168 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1169 }
1170
1171 // Not our turn yet, so we have to wait until our turn to
1172 // help scatter the downloads across all clients of the enterprise.
1173 LOG(INFO) << "Update deferred for another "
1174 << utils::FormatSecs(remaining_wait_time.InSeconds())
1175 << " per policy.";
1176 return kWallClockWaitNotSatisfied;
1177}
1178
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001179bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001180 int64 update_check_count_value;
1181
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001182 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1183 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1184 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001185 // We are unable to read the update check count from file for some reason.
1186 // So let's proceed anyway so as to not stall the update.
1187 LOG(ERROR) << "Unable to read update check count. "
1188 << "Skipping update-check-count-based-wait.";
1189 return true;
1190 }
1191 } else {
1192 // This file does not exist. This means we haven't started our update
1193 // check count down yet, so this is the right time to start the count down.
1194 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001195 params_->min_update_checks_needed(),
1196 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001197
1198 LOG(INFO) << "Randomly picked update check count value = "
1199 << update_check_count_value;
1200
1201 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001202 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1203 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001204 // We weren't able to write the update check count file for some reason.
1205 // So let's proceed anyway so as to not stall the update.
1206 LOG(ERROR) << "Unable to write update check count. "
1207 << "Skipping update-check-count-based-wait.";
1208 return true;
1209 }
1210 }
1211
1212 if (update_check_count_value == 0) {
1213 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1214 return true;
1215 }
1216
1217 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001218 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001219 // We err on the side of skipping scattering logic instead of stalling
1220 // a machine from receiving any updates in case of any unexpected state.
1221 LOG(ERROR) << "Invalid value for update check count detected. "
1222 << "Skipping update-check-count-based-wait.";
1223 return true;
1224 }
1225
1226 // Legal value, we need to wait for more update checks to happen
1227 // until this becomes 0.
1228 LOG(INFO) << "Deferring Omaha updates for another "
1229 << update_check_count_value
1230 << " update checks per policy";
1231 return false;
1232}
1233
David Zeuthen639aa362014-02-03 16:23:44 -08001234// static
1235bool OmahaRequestAction::ParseInstallDate(xmlDoc* doc,
1236 OmahaResponse* output_object) {
Ben Chan075248b2014-04-24 12:04:14 -07001237 scoped_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
David Zeuthen639aa362014-02-03 16:23:44 -08001238 xpath_nodeset(GetNodeSet(doc, ConstXMLStr("/response/daystart")));
1239
1240 if (xpath_nodeset.get() == NULL)
1241 return false;
1242
1243 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
1244 if (nodeset == NULL || nodeset->nodeNr < 1)
1245 return false;
1246
1247 xmlNode* daystart_node = nodeset->nodeTab[0];
1248 if (!xmlHasProp(daystart_node, ConstXMLStr("elapsed_days")))
1249 return false;
1250
1251 int64_t elapsed_days = 0;
1252 if (!base::StringToInt64(XmlGetProperty(daystart_node, "elapsed_days"),
1253 &elapsed_days))
1254 return false;
1255
1256 if (elapsed_days < 0)
1257 return false;
1258
1259 output_object->install_date_days = elapsed_days;
1260 return true;
1261}
1262
1263// static
1264bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1265 PrefsInterface* prefs = system_state->prefs();
1266 if (prefs == NULL)
1267 return false;
1268
1269 return prefs->Exists(kPrefsInstallDateDays);
1270}
1271
1272// static
1273bool OmahaRequestAction::PersistInstallDate(
1274 SystemState *system_state,
1275 int install_date_days,
1276 InstallDateProvisioningSource source) {
1277 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1278
1279 PrefsInterface* prefs = system_state->prefs();
1280 if (prefs == NULL)
1281 return false;
1282
1283 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1284 return false;
1285
1286 string metric_name = "Installer.InstallDateProvisioningSource";
1287 system_state->metrics_lib()->SendEnumToUMA(
1288 metric_name,
David Zeuthen33bae492014-02-25 16:16:18 -08001289 static_cast<int>(source), // Sample.
1290 kProvisionedMax); // Maximum.
1291
1292 metric_name = metrics::kMetricInstallDateProvisioningSource;
1293 system_state->metrics_lib()->SendEnumToUMA(
1294 metric_name,
1295 static_cast<int>(source), // Sample.
1296 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001297
1298 return true;
1299}
1300
David Zeuthen33bae492014-02-25 16:16:18 -08001301void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1302 // We only want to report this on "update check".
1303 if (ping_only_ || event_ != nullptr)
1304 return;
1305
1306 metrics::CheckResult result = metrics::CheckResult::kUnset;
1307 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1308 metrics::DownloadErrorCode download_error_code =
1309 metrics::DownloadErrorCode::kUnset;
1310
1311 // Regular update attempt.
1312 switch (code) {
1313 case kErrorCodeSuccess:
1314 // OK, we parsed the response successfully but that does
1315 // necessarily mean that an update is available.
1316 if (HasOutputPipe()) {
1317 const OmahaResponse& response = GetOutputObject();
1318 if (response.update_exists) {
1319 result = metrics::CheckResult::kUpdateAvailable;
1320 reaction = metrics::CheckReaction::kUpdating;
1321 } else {
1322 result = metrics::CheckResult::kNoUpdateAvailable;
1323 }
1324 } else {
1325 result = metrics::CheckResult::kNoUpdateAvailable;
1326 }
1327 break;
1328
1329 case kErrorCodeOmahaUpdateIgnoredPerPolicy:
1330 result = metrics::CheckResult::kUpdateAvailable;
1331 reaction = metrics::CheckReaction::kIgnored;
1332 break;
1333
1334 case kErrorCodeOmahaUpdateDeferredPerPolicy:
1335 result = metrics::CheckResult::kUpdateAvailable;
1336 reaction = metrics::CheckReaction::kDeferring;
1337 break;
1338
1339 case kErrorCodeOmahaUpdateDeferredForBackoff:
1340 result = metrics::CheckResult::kUpdateAvailable;
1341 reaction = metrics::CheckReaction::kBackingOff;
1342 break;
1343
1344 default:
1345 // We report two flavors of errors, "Download errors" and "Parsing
1346 // error". Try to convert to the former and if that doesn't work
1347 // we know it's the latter.
1348 metrics::DownloadErrorCode tmp_error = utils::GetDownloadErrorCode(code);
1349 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1350 result = metrics::CheckResult::kDownloadError;
1351 download_error_code = tmp_error;
1352 } else {
1353 result = metrics::CheckResult::kParsingError;
1354 }
1355 break;
1356 }
1357
1358 metrics::ReportUpdateCheckMetrics(system_state_,
1359 result, reaction, download_error_code);
1360}
1361
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001362} // namespace chromeos_update_engine