blob: 19b7989342cc21538f2b7d2de9610f02cb435bde [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>
Darin Petkov85ced132010-09-01 10:20:56 -070015#include <base/string_number_conversions.h>
16#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040017#include <base/stringprintf.h>
Darin Petkov85ced132010-09-01 10:20:56 -070018#include <base/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
65// These are for scoped_ptr_malloc, which is like scoped_ptr, but allows
66// a custom free() function to be specified.
67class 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)) {
103 return StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
104 }
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()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700114 return 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.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700138 app_body += StringPrintf(
139 " <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
155 app_body += StringPrintf(
156 " <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) {
Darin Petkov18c7bce2011-06-16 14:07:00 -0700169 error_code = StringPrintf(" errorcode=\"%d\"", event->error_code);
Darin Petkove17f86b2010-07-20 09:12:01 -0700170 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700171 app_body = 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,
186 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
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700211 string app_xml =
Jay Srinivasandb0acdf2013-04-02 14:47:45 -0700212 " <app appid=\"" + XmlEncode(params->GetAppId()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700213 app_versions +
214 app_channels +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700215 "lang=\"" + XmlEncode(params->app_lang()) + "\" " +
216 "board=\"" + XmlEncode(params->os_board()) + "\" " +
217 "hardware_class=\"" + XmlEncode(params->hwid()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700218 "delta_okay=\"" + delta_okay_str + "\" "
Chris Sosac1972482013-04-30 22:31:10 -0700219 "fw_version=\"" + XmlEncode(params->fw_version()) + "\" " +
220 "ec_version=\"" + XmlEncode(params->ec_version()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700221 ">\n" +
222 app_body +
223 " </app>\n";
224
225 return app_xml;
226}
227
228// Returns an XML that corresponds to the entire <os> node of the Omaha
229// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700230string GetOsXml(OmahaRequestParams* params) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700231 string os_xml =
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700232 " <os version=\"" + XmlEncode(params->os_version()) + "\" " +
233 "platform=\"" + XmlEncode(params->os_platform()) + "\" " +
234 "sp=\"" + XmlEncode(params->os_sp()) + "\">"
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700235 "</os>\n";
236 return os_xml;
237}
238
239// Returns an XML that corresponds to the entire Omaha request based on the
240// given parameters.
241string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700242 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700243 bool ping_only,
244 int ping_active_days,
245 int ping_roll_call_days,
246 SystemState* system_state) {
247 string os_xml = GetOsXml(params);
248 string app_xml = GetAppXml(event, params, ping_only, ping_active_days,
249 ping_roll_call_days, system_state);
250
251 string install_source = StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700252 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700253
254 string request_xml =
255 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700256 "<request protocol=\"3.0\" "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700257 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
258 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" " +
259 install_source +
260 "ismachine=\"1\">\n" +
261 os_xml +
262 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700263 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700264
265 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000266}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700267
rspangler@google.com49fdf182009-10-10 00:57:34 +0000268} // namespace {}
269
270// Encodes XML entities in a given string with libxml2. input must be
271// UTF-8 formatted. Output will be UTF-8 formatted.
272string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700273 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
274 // // cpu, considering creating one and caching it.
275 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
276 // xmlNewDoc(ConstXMLStr("1.0")));
277 // if (!xml_doc.get()) {
278 // LOG(ERROR) << "Unable to create xmlDoc";
279 // return "";
280 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000281 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
282 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
283 return string(reinterpret_cast<const char *>(str.get()));
284}
285
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800286OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700287 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700288 HttpFetcher* http_fetcher,
289 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800290 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700291 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700292 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700293 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700294 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700295 ping_roll_call_days_(0) {
296 params_ = system_state->request_params();
297}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000298
Darin Petkov6a5b3222010-07-13 14:55:28 -0700299OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000300
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700301// Calculates the value to use for the ping days parameter.
302int OmahaRequestAction::CalculatePingDays(const string& key) {
303 int days = kNeverPinged;
304 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800305 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700306 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
307 if (days < 0) {
308 // If |days| is negative, then the system clock must have jumped
309 // back in time since the ping was sent. Mark the value so that
310 // it doesn't get sent to the server but we still update the
311 // last ping daystart preference. This way the next ping time
312 // will be correct, hopefully.
313 days = kPingTimeJump;
314 LOG(WARNING) <<
315 "System clock jumped back in time. Resetting ping daystarts.";
316 }
317 }
318 return days;
319}
320
321void OmahaRequestAction::InitPingDays() {
322 // We send pings only along with update checks, not with events.
323 if (IsEvent()) {
324 return;
325 }
326 // TODO(petkov): Figure a way to distinguish active use pings
327 // vs. roll call pings. Currently, the two pings are identical. A
328 // fix needs to change this code as well as UpdateLastPingDays.
329 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
330 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
331}
332
Darin Petkov6a5b3222010-07-13 14:55:28 -0700333void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000334 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700335 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700336 if (ping_only_ &&
337 !ShouldPing(ping_active_days_) &&
338 !ShouldPing(ping_roll_call_days_)) {
David Zeuthena99981f2013-04-29 13:42:47 -0700339 processor_->ActionComplete(this, kErrorCodeSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700340 return;
341 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700342 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700343 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700344 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700345 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800346 ping_roll_call_days_,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700347 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700348
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800349 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
350 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700351 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700352 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700353 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000354}
355
Darin Petkov6a5b3222010-07-13 14:55:28 -0700356void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000357 http_fetcher_->TerminateTransfer();
358}
359
360// We just store the response in the buffer. Once we've received all bytes,
361// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700362void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
363 const char* bytes,
364 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000365 response_buffer_.reserve(response_buffer_.size() + length);
366 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
367}
368
369namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000370// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
371// on the returned object.
372// This code is roughly based on the libxml tutorial at:
373// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700374xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000375 xmlXPathObject* result = NULL;
376
377 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
378 xmlXPathNewContext(doc));
379 if (!context.get()) {
380 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
381 return NULL;
382 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000383
384 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000385 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700386 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000387 return NULL;
388 }
389 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700390 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000391 xmlXPathFreeObject(result);
392 return NULL;
393 }
394 return result;
395}
396
397// Returns the string value of a named attribute on a node, or empty string
398// if no such node exists. If the attribute exists and has a value of
399// empty string, there's no way to distinguish that from the attribute
400// not existing.
401string XmlGetProperty(xmlNode* node, const char* name) {
402 if (!xmlHasProp(node, ConstXMLStr(name)))
403 return "";
404 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
405 xmlGetProp(node, ConstXMLStr(name)));
406 string ret(reinterpret_cast<const char *>(str.get()));
407 return ret;
408}
409
410// Parses a 64 bit base-10 int from a string and returns it. Returns 0
411// on error. If the string contains "0", that's indistinguishable from
412// error.
413off_t ParseInt(const string& str) {
414 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700415 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000416 if (rc < 1) {
417 // failure
418 return 0;
419 }
420 return ret;
421}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700422
423// Update the last ping day preferences based on the server daystart
424// response. Returns true on success, false otherwise.
425bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700426 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700427
428 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700429 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700430 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
431 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
432 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
433 xmlNode* daystart_node = nodeset->nodeTab[0];
434 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
435 ConstXMLStr("elapsed_seconds")));
436
437 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700438 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
439 "elapsed_seconds"),
440 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700441 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
442
443 // Remember the local time that matches the server's last midnight
444 // time.
445 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
446 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
447 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
448 return true;
449}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000450} // namespace {}
451
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700452bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
453 OmahaResponse* output_object,
454 ScopedActionCompleter* completer) {
455 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
456
457 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
458 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
459 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700460 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700461 return false;
462 }
463
464 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
465 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
466 CHECK_GE(nodeset->nodeNr, 1);
467 xmlNode* update_check_node = nodeset->nodeTab[0];
468
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800469 // chromium-os:37289: The PollInterval is not supported by Omaha server
470 // currently. But still keeping this existing code in case we ever decide to
471 // slow down the request rate from the server-side. Note that the
472 // PollInterval is not persisted, so it has to be sent by the server on every
473 // response to guarantee that the UpdateCheckScheduler uses this value
474 // (otherwise, if the device got rebooted after the last server-indicated
475 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
476 // value for the scattering logic is based on the assumption that we perform
477 // an update check every hour so that the max value of 8 will roughly be
478 // equivalent to one work day. If we decide to use PollInterval permanently,
479 // we should update the max_update_checks_allowed to take PollInterval into
480 // account. Note: The parsing for PollInterval happens even before parsing
481 // of the status because we may want to specify the PollInterval even when
482 // there's no update.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700483 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
484 &output_object->poll_interval);
485
486 if (!ParseStatus(update_check_node, output_object, completer))
487 return false;
488
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800489 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
490 // appends the package name to the URLs populated in this method.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700491 if (!ParseUrls(doc, output_object, completer))
492 return false;
493
494 if (!ParsePackage(doc, output_object, completer))
495 return false;
496
497 if (!ParseParams(doc, output_object, completer))
498 return false;
499
500 return true;
501}
502
503bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
504 OmahaResponse* output_object,
505 ScopedActionCompleter* completer) {
506 // Get status.
507 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
508 LOG(ERROR) << "Omaha Response missing status";
David Zeuthena99981f2013-04-29 13:42:47 -0700509 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700510 return false;
511 }
512
513 const string status(XmlGetProperty(update_check_node, "status"));
514 if (status == "noupdate") {
515 LOG(INFO) << "No update.";
516 output_object->update_exists = false;
517 SetOutputObject(*output_object);
David Zeuthena99981f2013-04-29 13:42:47 -0700518 completer->set_code(kErrorCodeSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700519 return false;
520 }
521
522 if (status != "ok") {
523 LOG(ERROR) << "Unknown Omaha response status: " << status;
David Zeuthena99981f2013-04-29 13:42:47 -0700524 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700525 return false;
526 }
527
528 return true;
529}
530
531bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
532 OmahaResponse* output_object,
533 ScopedActionCompleter* completer) {
534 // Get the update URL.
535 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
536
537 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
538 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
539 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700540 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700541 return false;
542 }
543
544 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
545 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
546 CHECK_GE(nodeset->nodeNr, 1);
547
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800548 LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)";
549 output_object->payload_urls.clear();
550 for (int i = 0; i < nodeset->nodeNr; i++) {
551 xmlNode* url_node = nodeset->nodeTab[i];
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800552 const string codebase(XmlGetProperty(url_node, "codebase"));
553 if (codebase.empty()) {
554 LOG(ERROR) << "Omaha Response URL has empty codebase";
David Zeuthena99981f2013-04-29 13:42:47 -0700555 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800556 return false;
557 }
558 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700559 }
560
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700561 return true;
562}
563
564bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
565 OmahaResponse* output_object,
566 ScopedActionCompleter* completer) {
567 // Get the package node.
568 static const char* kPackageNodeXPath(
569 "/response/app/updatecheck/manifest/packages/package");
570
571 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
572 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
573 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700574 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700575 return false;
576 }
577
578 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
579 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
580 CHECK_GE(nodeset->nodeNr, 1);
581
582 // We only care about the first package.
583 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
584 xmlNode* package_node = nodeset->nodeTab[0];
585
586 // Get package properties one by one.
587
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800588 // Parse the payload name to be appended to the base Url value.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700589 const string package_name(XmlGetProperty(package_node, "name"));
590 LOG(INFO) << "Omaha Response package name = " << package_name;
591 if (package_name.empty()) {
592 LOG(ERROR) << "Omaha Response has empty package name";
David Zeuthena99981f2013-04-29 13:42:47 -0700593 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700594 return false;
595 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800596
597 // Append the package name to each URL in our list so that we don't
598 // propagate the urlBase vs packageName distinctions beyond this point.
599 // From now on, we only need to use payload_urls.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700600 for (size_t i = 0; i < output_object->payload_urls.size(); i++)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800601 output_object->payload_urls[i] += package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700602
603 // Parse the payload size.
604 off_t size = ParseInt(XmlGetProperty(package_node, "size"));
605 if (size <= 0) {
606 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
David Zeuthena99981f2013-04-29 13:42:47 -0700607 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700608 return false;
609 }
610 output_object->size = size;
611
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800612 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700613
614 return true;
615}
616
617bool OmahaRequestAction::ParseParams(xmlDoc* doc,
618 OmahaResponse* output_object,
619 ScopedActionCompleter* completer) {
Chris Sosa3b748432013-06-20 16:42:59 -0700620 // XPath location for response elements we care about.
621 static const char* kManifestNodeXPath("/response/app/updatecheck/manifest");\
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700622 static const char* kActionNodeXPath(
Chris Sosa3b748432013-06-20 16:42:59 -0700623 "/response/app/updatecheck/manifest/actions/action");
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700624
Chris Sosa3b748432013-06-20 16:42:59 -0700625 // Get the manifest node where version is present.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700626 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Chris Sosa3b748432013-06-20 16:42:59 -0700627 xpath_manifest_nodeset(GetNodeSet(doc, ConstXMLStr(kManifestNodeXPath)));
628 if (!xpath_manifest_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700629 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700630 return false;
631 }
632
Chris Sosa3b748432013-06-20 16:42:59 -0700633 // Grab the only matching node there should be from the xpath.
634 xmlNodeSet* nodeset = xpath_manifest_nodeset->nodesetval;
635 CHECK(nodeset) << "XPath missing " << kManifestNodeXPath;
636 CHECK_GE(nodeset->nodeNr, 1);
637 xmlNode* manifest_node = nodeset->nodeTab[0];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700638
Chris Sosa3b748432013-06-20 16:42:59 -0700639 // Set the version.
640 output_object->version = XmlGetProperty(manifest_node, kTagVersion);
641 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700642 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Chris Sosa3b748432013-06-20 16:42:59 -0700643 completer->set_code(kErrorCodeOmahaResponseInvalid);
644 return false;
645 }
646
647 LOG(INFO) << "Received omaha response to update to version "
648 << output_object->version;
649
650 // Grab the action nodes.
651 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
652 xpath_action_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
653 if (!xpath_action_nodeset.get()) {
654 completer->set_code(kErrorCodeOmahaResponseInvalid);
655 return false;
656 }
657
658 // We only care about the action that has event "postinstall", because this is
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700659 // where Omaha puts all the generic name/value pairs in the rule.
Chris Sosa3b748432013-06-20 16:42:59 -0700660 nodeset = xpath_action_nodeset->nodesetval;
661 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700662 LOG(INFO) << "Found " << nodeset->nodeNr
663 << " action(s). Processing the postinstall action.";
664
665 // pie_action_node holds the action node corresponding to the
666 // postinstall event action, if present.
667 xmlNode* pie_action_node = NULL;
668 for (int i = 0; i < nodeset->nodeNr; i++) {
669 xmlNode* action_node = nodeset->nodeTab[i];
670 if (XmlGetProperty(action_node, "event") == "postinstall") {
671 pie_action_node = action_node;
672 break;
673 }
674 }
675
676 if (!pie_action_node) {
677 LOG(ERROR) << "Omaha Response has no postinstall event action";
David Zeuthena99981f2013-04-29 13:42:47 -0700678 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700679 return false;
680 }
681
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800682 output_object->hash = XmlGetProperty(pie_action_node, kTagSha256);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700683 if (output_object->hash.empty()) {
684 LOG(ERROR) << "Omaha Response has empty sha256 value";
David Zeuthena99981f2013-04-29 13:42:47 -0700685 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700686 return false;
687 }
688
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800689 // Get the optional properties one by one.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800690 output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700691 output_object->metadata_size =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800692 ParseInt(XmlGetProperty(pie_action_node, kTagMetadataSize));
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700693 output_object->metadata_signature =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800694 XmlGetProperty(pie_action_node, kTagMetadataSignatureRsa);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800695 output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true";
696 output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700697 output_object->max_days_to_scatter =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800698 ParseInt(XmlGetProperty(pie_action_node, kTagMaxDaysToScatter));
David Zeuthen8f191b22013-08-06 12:27:50 -0700699 output_object->disable_p2p_for_downloading =
700 (XmlGetProperty(pie_action_node, kTagDisableP2PForDownloading) == "true");
701 output_object->disable_p2p_for_sharing =
702 (XmlGetProperty(pie_action_node, kTagDisableP2PForSharing) == "true");
David Zeuthene7f89172013-10-31 10:21:04 -0700703 output_object->public_key_rsa =
704 XmlGetProperty(pie_action_node, kTagPublicKeyRsa);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800705
706 string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl);
Jay Srinivasan08262882012-12-28 19:29:43 -0800707 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800708 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700709
Jay Srinivasan08262882012-12-28 19:29:43 -0800710 output_object->is_delta_payload =
711 XmlGetProperty(pie_action_node, kTagIsDeltaPayload) == "true";
712
713 output_object->disable_payload_backoff =
714 XmlGetProperty(pie_action_node, kTagDisablePayloadBackoff) == "true";
715
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700716 return true;
717}
718
rspangler@google.com49fdf182009-10-10 00:57:34 +0000719// If the transfer was successful, this uses libxml2 to parse the response
720// and fill in the appropriate fields of the output object. Also, notifies
721// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700722void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
723 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000724 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800725 string current_response(response_buffer_.begin(), response_buffer_.end());
726 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700727
728 // Events are best effort transactions -- assume they always succeed.
729 if (IsEvent()) {
730 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800731 if (event_->result == OmahaEvent::kResultError && successful &&
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700732 system_state_->hardware()->IsOfficialBuild()) {
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800733 LOG(INFO) << "Signalling Crash Reporter.";
734 utils::ScheduleCrashReporterUpload();
735 }
David Zeuthena99981f2013-04-29 13:42:47 -0700736 completer.set_code(kErrorCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700737 return;
738 }
739
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700740 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700741 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700742 int code = GetHTTPResponseCode();
743 // Makes sure we send sane error values.
744 if (code < 0 || code >= 1000) {
745 code = 999;
746 }
David Zeuthena99981f2013-04-29 13:42:47 -0700747 completer.set_code(static_cast<ErrorCode>(
748 kErrorCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000749 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700750 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000751
752 // parse our response and fill the fields in the output object
753 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
754 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
755 if (!doc.get()) {
756 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700757 completer.set_code(response_buffer_.empty() ?
David Zeuthena99981f2013-04-29 13:42:47 -0700758 kErrorCodeOmahaRequestEmptyResponseError :
759 kErrorCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000760 return;
761 }
762
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700763 // If a ping was sent, update the last ping day preferences based on
764 // the server daystart response.
765 if (ShouldPing(ping_active_days_) ||
766 ShouldPing(ping_roll_call_days_) ||
767 ping_active_days_ == kPingTimeJump ||
768 ping_roll_call_days_ == kPingTimeJump) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800769 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700770 << "Failed to update the last ping day preferences!";
771 }
772
Thieu Le116fda32011-04-19 11:01:54 -0700773 if (!HasOutputPipe()) {
774 // Just set success to whether or not the http transfer succeeded,
775 // which must be true at this point in the code.
David Zeuthena99981f2013-04-29 13:42:47 -0700776 completer.set_code(kErrorCodeSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700777 return;
778 }
779
Darin Petkov6a5b3222010-07-13 14:55:28 -0700780 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700781 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000782 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700783 output_object.update_exists = true;
784 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000785
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700786 if (params_->update_disabled()) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700787 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700788 output_object.update_exists = false;
David Zeuthena99981f2013-04-29 13:42:47 -0700789 completer.set_code(kErrorCodeOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700790 // Note: We could technically delete the UpdateFirstSeenAt state here.
791 // If we do, it'll mean a device has to restart the UpdateFirstSeenAt
792 // and thus help scattering take effect when the AU is turned on again.
793 // On the other hand, it also increases the chance of update starvation if
794 // an admin turns AU on/off more frequently. We choose to err on the side
795 // of preventing starvation at the cost of not applying scattering in
796 // those cases.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700797 return;
798 }
799
David Zeuthen8f191b22013-08-06 12:27:50 -0700800 // If Omaha says to disable p2p, respect that
801 if (output_object.disable_p2p_for_downloading) {
802 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
803 << "requested by Omaha.";
804 params_->set_use_p2p_for_downloading(false);
805 }
806 if (output_object.disable_p2p_for_sharing) {
807 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
808 << "requested by Omaha.";
809 params_->set_use_p2p_for_sharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700810 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800811
812 // Update the payload state with the current response. The payload state
813 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800814 // from what's stored already. We are updating the payload state as late
815 // as possible in this method so that if a new release gets pushed and then
816 // got pulled back due to some issues, we don't want to clear our internal
817 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800818 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800819 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800820
David Zeuthen8f191b22013-08-06 12:27:50 -0700821 // It could be we've already exceeded the deadline for when p2p is
822 // allowed or that we've tried too many times with p2p. Check that.
823 if (params_->use_p2p_for_downloading()) {
824 payload_state->P2PNewAttempt();
825 if (!payload_state->P2PAttemptAllowed()) {
826 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
827 << "of previous failures when using p2p.";
828 params_->set_use_p2p_for_downloading(false);
829 }
830 }
831
832 // From here on, we'll complete stuff in CompleteProcessing() so
833 // disable |completer| since we'll create a new one in that
834 // function.
835 completer.set_should_complete(false);
836
837 // If we're allowed to use p2p for downloading we do not pay
838 // attention to wall-clock-based waiting if the URL is indeed
839 // available via p2p. Therefore, check if the file is available via
840 // p2p before deferring...
841 if (params_->use_p2p_for_downloading()) {
842 LookupPayloadViaP2P(output_object);
843 } else {
844 CompleteProcessing();
845 }
846}
847
848void OmahaRequestAction::CompleteProcessing() {
849 ScopedActionCompleter completer(processor_, this);
850 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
851 PayloadStateInterface* payload_state = system_state_->payload_state();
852
853 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800854 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -0700855 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
856 completer.set_code(kErrorCodeOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -0800857 return;
858 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700859
Chris Sosa20f005c2013-09-05 13:53:08 -0700860 if (payload_state->ShouldBackoffDownload()) {
861 output_object.update_exists = false;
862 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
863 << "attempts";
864 completer.set_code(kErrorCodeOmahaUpdateDeferredForBackoff);
865 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700866 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700867 completer.set_code(kErrorCodeSuccess);
868}
869
870void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
871 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
872 if (!url.empty()) {
873 params_->set_p2p_url(url);
874 } else {
875 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
876 << "because no suitable peer could be found.";
877 params_->set_use_p2p_for_downloading(false);
878 }
879 CompleteProcessing();
880}
881
882void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -0700883 // If the device is in the middle of an update, the state variables
884 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
885 // tracks the offset and length of the operation currently in
886 // progress. The offset is based from the end of the manifest which
887 // is kPrefsManifestMetadataSize bytes long.
888 //
889 // To make forward progress and avoid deadlocks, we need to find a
890 // peer that has at least the entire operation we're currently
891 // working on. Otherwise we may end up in a situation where two
892 // devices bounce back and forth downloading from each other,
893 // neither making any forward progress until one of them decides to
894 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
895 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -0700896 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -0700897 int64_t manifest_metadata_size = 0;
898 int64_t next_data_offset = 0;
899 int64_t next_data_length = 0;
David Zeuthen8f191b22013-08-06 12:27:50 -0700900 if (system_state_ != NULL &&
David Zeuthen41996ad2013-09-24 15:43:24 -0700901 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
902 &manifest_metadata_size) &&
903 manifest_metadata_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -0700904 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -0700905 &next_data_offset) &&
906 next_data_offset != -1 &&
907 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
908 &next_data_length)) {
909 minimum_size = manifest_metadata_size + next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -0700910 }
911
912 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
913 if (system_state_->p2p_manager() != NULL) {
914 LOG(INFO) << "Checking if payload is available via p2p, file_id="
915 << file_id << " minimum_size=" << minimum_size;
916 system_state_->p2p_manager()->LookupUrlForFile(
917 file_id,
918 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -0800919 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -0700920 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
921 base::Unretained(this)));
922 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000923}
924
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700925bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -0700926 if (params_->interactive()) {
927 LOG(INFO) << "Not deferring download because update is interactive.";
928 return false;
929 }
930
David Zeuthen8f191b22013-08-06 12:27:50 -0700931 // If we're using p2p to download _and_ we have a p2p URL, we never
932 // defer the download. This is because the download will always
933 // happen from a peer on the LAN and we've been waiting in line for
934 // our turn.
935 if (params_->use_p2p_for_downloading() && !params_->p2p_url().empty()) {
936 LOG(INFO) << "Download not deferred because download "
937 << "will happen from a local peer (via p2p).";
938 return false;
939 }
940
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700941 // We should defer the downloads only if we've first satisfied the
942 // wall-clock-based-waiting period and then the update-check-based waiting
943 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700944 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -0700945 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
946 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700947 return false;
948 }
949
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700950 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700951 case kWallClockWaitNotSatisfied:
952 // We haven't even satisfied the first condition, passing the
953 // wall-clock-based waiting period, so we should defer the downloads
954 // until that happens.
955 LOG(INFO) << "wall-clock-based-wait not satisfied.";
956 return true;
957
958 case kWallClockWaitDoneButUpdateCheckWaitRequired:
959 LOG(INFO) << "wall-clock-based-wait satisfied and "
960 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700961 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700962
963 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
964 // Wall-clock-based waiting period is satisfied, and it's determined
965 // that we do not need the update-check-based wait. so no need to
966 // defer downloads.
967 LOG(INFO) << "wall-clock-based-wait satisfied and "
968 << "update-check-based-wait is not required.";
969 return false;
970
971 default:
972 // Returning false for this default case so we err on the
973 // side of downloading updates than deferring in case of any bugs.
974 NOTREACHED();
975 return false;
976 }
977}
978
979OmahaRequestAction::WallClockWaitResult
980OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700981 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700982 Time update_first_seen_at;
983 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700984
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800985 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
986 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
987 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700988 // Note: This timestamp could be that of ANY update we saw in the past
989 // (not necessarily this particular update we're considering to apply)
990 // but never got to apply because of some reason (e.g. stop AU policy,
991 // updates being pulled out from Omaha, changes in target version prefix,
992 // new update being rolled out, etc.). But for the purposes of scattering
993 // it doesn't matter which update the timestamp corresponds to. i.e.
994 // the clock starts ticking the first time we see an update and we're
995 // ready to apply when the random wait period is satisfied relative to
996 // that first seen timestamp.
997 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
998 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
999 << utils::ToString(update_first_seen_at);
1000 } else {
1001 // This seems like an unexpected error where the persisted value exists
1002 // but it's not readable for some reason. Just skip scattering in this
1003 // case to be safe.
1004 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1005 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1006 }
1007 } else {
1008 update_first_seen_at = Time::Now();
1009 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001010 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1011 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001012 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1013 << utils::ToString(update_first_seen_at);
1014 }
1015 else {
1016 // This seems like an unexpected error where the value cannot be
1017 // persisted for some reason. Just skip scattering in this
1018 // case to be safe.
1019 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1020 << utils::ToString(update_first_seen_at)
1021 << " cannot be persisted";
1022 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1023 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001024 }
1025
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001026 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001027 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001028 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001029
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001030 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001031 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001032 << ", Time Elapsed = "
1033 << utils::FormatSecs(elapsed_time.InSeconds())
1034 << ", MaxDaysToScatter = "
1035 << max_scatter_period.InDays();
1036
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001037 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001038 // The deadline is set for all rules which serve a delta update from a
1039 // previous FSI, which means this update will be applied mostly in OOBE
1040 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1041 // quickly.
1042 LOG(INFO) << "Not scattering as deadline flag is set";
1043 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1044 }
1045
1046 if (max_scatter_period.InDays() == 0) {
1047 // This means the Omaha rule creator decides that this rule
1048 // should not be scattered irrespective of the policy.
1049 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1050 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1051 }
1052
1053 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001054 // This means we've waited more than the upperbound wait in the rule
1055 // from the time we first saw a valid update available to us.
1056 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001057 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1058 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1059 }
1060
1061 // This means we are required to participate in scattering.
1062 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001063 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001064 if (remaining_wait_time.InSeconds() <= 0) {
1065 // Yes, it's our turn now.
1066 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1067
1068 // But we can't download until the update-check-count-based wait is also
1069 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001070 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001071 kWallClockWaitDoneButUpdateCheckWaitRequired :
1072 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1073 }
1074
1075 // Not our turn yet, so we have to wait until our turn to
1076 // help scatter the downloads across all clients of the enterprise.
1077 LOG(INFO) << "Update deferred for another "
1078 << utils::FormatSecs(remaining_wait_time.InSeconds())
1079 << " per policy.";
1080 return kWallClockWaitNotSatisfied;
1081}
1082
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001083bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001084 int64 update_check_count_value;
1085
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001086 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1087 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1088 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001089 // We are unable to read the update check count from file for some reason.
1090 // So let's proceed anyway so as to not stall the update.
1091 LOG(ERROR) << "Unable to read update check count. "
1092 << "Skipping update-check-count-based-wait.";
1093 return true;
1094 }
1095 } else {
1096 // This file does not exist. This means we haven't started our update
1097 // check count down yet, so this is the right time to start the count down.
1098 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001099 params_->min_update_checks_needed(),
1100 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001101
1102 LOG(INFO) << "Randomly picked update check count value = "
1103 << update_check_count_value;
1104
1105 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001106 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1107 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001108 // We weren't able to write the update check count file for some reason.
1109 // So let's proceed anyway so as to not stall the update.
1110 LOG(ERROR) << "Unable to write update check count. "
1111 << "Skipping update-check-count-based-wait.";
1112 return true;
1113 }
1114 }
1115
1116 if (update_check_count_value == 0) {
1117 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1118 return true;
1119 }
1120
1121 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001122 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001123 // We err on the side of skipping scattering logic instead of stalling
1124 // a machine from receiving any updates in case of any unexpected state.
1125 LOG(ERROR) << "Invalid value for update check count detected. "
1126 << "Skipping update-check-count-based-wait.";
1127 return true;
1128 }
1129
1130 // Legal value, we need to wait for more update checks to happen
1131 // until this becomes 0.
1132 LOG(INFO) << "Deferring Omaha updates for another "
1133 << update_check_count_value
1134 << " update checks per policy";
1135 return false;
1136}
1137
1138} // namespace chromeos_update_engine
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001139
1140