blob: 5ce59bbcbb8a2f4f4a6edc9309c3df43b1d09225 [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";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080056
rspangler@google.com49fdf182009-10-10 00:57:34 +000057namespace {
58
59const string kGupdateVersion("ChromeOSUpdateEngine-0.1.0.0");
60
61// This is handy for passing strings into libxml2
62#define ConstXMLStr(x) (reinterpret_cast<const xmlChar*>(x))
63
64// These are for scoped_ptr_malloc, which is like scoped_ptr, but allows
65// a custom free() function to be specified.
66class 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)) {
102 return StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
103 }
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()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700113 return 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.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700137 app_body += StringPrintf(
138 " <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
154 app_body += StringPrintf(
155 " <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) {
Darin Petkov18c7bce2011-06-16 14:07:00 -0700168 error_code = StringPrintf(" errorcode=\"%d\"", event->error_code);
Darin Petkove17f86b2010-07-20 09:12:01 -0700169 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700170 app_body = 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,
185 SystemState* system_state) {
186 string app_body = GetAppBody(event, params, ping_only, ping_active_days,
187 ping_roll_call_days, system_state->prefs());
188 string app_versions;
189
190 // If we are upgrading to a more stable channel and we are allowed to do
191 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
192 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700193 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700194 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
195 << "on downgrading to the version in the more stable channel";
196 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700197 XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700198 } else {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700199 app_versions = "version=\"" + XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700200 }
201
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700202 string download_channel = params->download_channel();
203 string app_channels = "track=\"" + XmlEncode(download_channel) + "\" ";
204 if (params->current_channel() != download_channel)
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700205 app_channels +=
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700206 "from_track=\"" + XmlEncode(params->current_channel()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700207
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700208 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700209
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700210 string app_xml =
Jay Srinivasandb0acdf2013-04-02 14:47:45 -0700211 " <app appid=\"" + XmlEncode(params->GetAppId()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700212 app_versions +
213 app_channels +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700214 "lang=\"" + XmlEncode(params->app_lang()) + "\" " +
215 "board=\"" + XmlEncode(params->os_board()) + "\" " +
216 "hardware_class=\"" + XmlEncode(params->hwid()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700217 "delta_okay=\"" + delta_okay_str + "\" "
Chris Sosac1972482013-04-30 22:31:10 -0700218 "fw_version=\"" + XmlEncode(params->fw_version()) + "\" " +
219 "ec_version=\"" + XmlEncode(params->ec_version()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700220 ">\n" +
221 app_body +
222 " </app>\n";
223
224 return app_xml;
225}
226
227// Returns an XML that corresponds to the entire <os> node of the Omaha
228// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700229string GetOsXml(OmahaRequestParams* params) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700230 string os_xml =
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700231 " <os version=\"" + XmlEncode(params->os_version()) + "\" " +
232 "platform=\"" + XmlEncode(params->os_platform()) + "\" " +
233 "sp=\"" + XmlEncode(params->os_sp()) + "\">"
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700234 "</os>\n";
235 return os_xml;
236}
237
238// Returns an XML that corresponds to the entire Omaha request based on the
239// given parameters.
240string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700241 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700242 bool ping_only,
243 int ping_active_days,
244 int ping_roll_call_days,
245 SystemState* system_state) {
246 string os_xml = GetOsXml(params);
247 string app_xml = GetAppXml(event, params, ping_only, ping_active_days,
248 ping_roll_call_days, system_state);
249
250 string install_source = StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700251 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700252
253 string request_xml =
254 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700255 "<request protocol=\"3.0\" "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700256 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
257 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" " +
258 install_source +
259 "ismachine=\"1\">\n" +
260 os_xml +
261 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700262 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700263
264 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000265}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700266
rspangler@google.com49fdf182009-10-10 00:57:34 +0000267} // namespace {}
268
269// Encodes XML entities in a given string with libxml2. input must be
270// UTF-8 formatted. Output will be UTF-8 formatted.
271string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700272 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
273 // // cpu, considering creating one and caching it.
274 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
275 // xmlNewDoc(ConstXMLStr("1.0")));
276 // if (!xml_doc.get()) {
277 // LOG(ERROR) << "Unable to create xmlDoc";
278 // return "";
279 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000280 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
281 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
282 return string(reinterpret_cast<const char *>(str.get()));
283}
284
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800285OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700286 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700287 HttpFetcher* http_fetcher,
288 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800289 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700290 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700291 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700292 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700293 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700294 ping_roll_call_days_(0) {
295 params_ = system_state->request_params();
296}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000297
Darin Petkov6a5b3222010-07-13 14:55:28 -0700298OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000299
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700300// Calculates the value to use for the ping days parameter.
301int OmahaRequestAction::CalculatePingDays(const string& key) {
302 int days = kNeverPinged;
303 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800304 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700305 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
306 if (days < 0) {
307 // If |days| is negative, then the system clock must have jumped
308 // back in time since the ping was sent. Mark the value so that
309 // it doesn't get sent to the server but we still update the
310 // last ping daystart preference. This way the next ping time
311 // will be correct, hopefully.
312 days = kPingTimeJump;
313 LOG(WARNING) <<
314 "System clock jumped back in time. Resetting ping daystarts.";
315 }
316 }
317 return days;
318}
319
320void OmahaRequestAction::InitPingDays() {
321 // We send pings only along with update checks, not with events.
322 if (IsEvent()) {
323 return;
324 }
325 // TODO(petkov): Figure a way to distinguish active use pings
326 // vs. roll call pings. Currently, the two pings are identical. A
327 // fix needs to change this code as well as UpdateLastPingDays.
328 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
329 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
330}
331
Darin Petkov6a5b3222010-07-13 14:55:28 -0700332void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000333 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700334 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700335 if (ping_only_ &&
336 !ShouldPing(ping_active_days_) &&
337 !ShouldPing(ping_roll_call_days_)) {
David Zeuthena99981f2013-04-29 13:42:47 -0700338 processor_->ActionComplete(this, kErrorCodeSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700339 return;
340 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700341 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700342 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700343 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700344 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800345 ping_roll_call_days_,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700346 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700347
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800348 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
349 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700350 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700351 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700352 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000353}
354
Darin Petkov6a5b3222010-07-13 14:55:28 -0700355void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000356 http_fetcher_->TerminateTransfer();
357}
358
359// We just store the response in the buffer. Once we've received all bytes,
360// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700361void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
362 const char* bytes,
363 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000364 response_buffer_.reserve(response_buffer_.size() + length);
365 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
366}
367
368namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000369// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
370// on the returned object.
371// This code is roughly based on the libxml tutorial at:
372// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700373xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000374 xmlXPathObject* result = NULL;
375
376 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
377 xmlXPathNewContext(doc));
378 if (!context.get()) {
379 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
380 return NULL;
381 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000382
383 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000384 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700385 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000386 return NULL;
387 }
388 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700389 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000390 xmlXPathFreeObject(result);
391 return NULL;
392 }
393 return result;
394}
395
396// Returns the string value of a named attribute on a node, or empty string
397// if no such node exists. If the attribute exists and has a value of
398// empty string, there's no way to distinguish that from the attribute
399// not existing.
400string XmlGetProperty(xmlNode* node, const char* name) {
401 if (!xmlHasProp(node, ConstXMLStr(name)))
402 return "";
403 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
404 xmlGetProp(node, ConstXMLStr(name)));
405 string ret(reinterpret_cast<const char *>(str.get()));
406 return ret;
407}
408
409// Parses a 64 bit base-10 int from a string and returns it. Returns 0
410// on error. If the string contains "0", that's indistinguishable from
411// error.
412off_t ParseInt(const string& str) {
413 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700414 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000415 if (rc < 1) {
416 // failure
417 return 0;
418 }
419 return ret;
420}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700421
422// Update the last ping day preferences based on the server daystart
423// response. Returns true on success, false otherwise.
424bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700425 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700426
427 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700428 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700429 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
430 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
431 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
432 xmlNode* daystart_node = nodeset->nodeTab[0];
433 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
434 ConstXMLStr("elapsed_seconds")));
435
436 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700437 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
438 "elapsed_seconds"),
439 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700440 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
441
442 // Remember the local time that matches the server's last midnight
443 // time.
444 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
445 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
446 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
447 return true;
448}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000449} // namespace {}
450
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700451bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
452 OmahaResponse* output_object,
453 ScopedActionCompleter* completer) {
454 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
455
456 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
457 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
458 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700459 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700460 return false;
461 }
462
463 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
464 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
465 CHECK_GE(nodeset->nodeNr, 1);
466 xmlNode* update_check_node = nodeset->nodeTab[0];
467
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800468 // chromium-os:37289: The PollInterval is not supported by Omaha server
469 // currently. But still keeping this existing code in case we ever decide to
470 // slow down the request rate from the server-side. Note that the
471 // PollInterval is not persisted, so it has to be sent by the server on every
472 // response to guarantee that the UpdateCheckScheduler uses this value
473 // (otherwise, if the device got rebooted after the last server-indicated
474 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
475 // value for the scattering logic is based on the assumption that we perform
476 // an update check every hour so that the max value of 8 will roughly be
477 // equivalent to one work day. If we decide to use PollInterval permanently,
478 // we should update the max_update_checks_allowed to take PollInterval into
479 // account. Note: The parsing for PollInterval happens even before parsing
480 // of the status because we may want to specify the PollInterval even when
481 // there's no update.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700482 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
483 &output_object->poll_interval);
484
485 if (!ParseStatus(update_check_node, output_object, completer))
486 return false;
487
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800488 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
489 // appends the package name to the URLs populated in this method.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700490 if (!ParseUrls(doc, output_object, completer))
491 return false;
492
493 if (!ParsePackage(doc, output_object, completer))
494 return false;
495
496 if (!ParseParams(doc, output_object, completer))
497 return false;
498
499 return true;
500}
501
502bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
503 OmahaResponse* output_object,
504 ScopedActionCompleter* completer) {
505 // Get status.
506 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
507 LOG(ERROR) << "Omaha Response missing status";
David Zeuthena99981f2013-04-29 13:42:47 -0700508 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700509 return false;
510 }
511
512 const string status(XmlGetProperty(update_check_node, "status"));
513 if (status == "noupdate") {
514 LOG(INFO) << "No update.";
515 output_object->update_exists = false;
516 SetOutputObject(*output_object);
David Zeuthena99981f2013-04-29 13:42:47 -0700517 completer->set_code(kErrorCodeSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700518 return false;
519 }
520
521 if (status != "ok") {
522 LOG(ERROR) << "Unknown Omaha response status: " << status;
David Zeuthena99981f2013-04-29 13:42:47 -0700523 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700524 return false;
525 }
526
527 return true;
528}
529
530bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
531 OmahaResponse* output_object,
532 ScopedActionCompleter* completer) {
533 // Get the update URL.
534 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
535
536 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
537 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
538 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700539 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700540 return false;
541 }
542
543 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
544 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
545 CHECK_GE(nodeset->nodeNr, 1);
546
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800547 LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)";
548 output_object->payload_urls.clear();
549 for (int i = 0; i < nodeset->nodeNr; i++) {
550 xmlNode* url_node = nodeset->nodeTab[i];
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800551 const string codebase(XmlGetProperty(url_node, "codebase"));
552 if (codebase.empty()) {
553 LOG(ERROR) << "Omaha Response URL has empty codebase";
David Zeuthena99981f2013-04-29 13:42:47 -0700554 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800555 return false;
556 }
557 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700558 }
559
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700560 return true;
561}
562
563bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
564 OmahaResponse* output_object,
565 ScopedActionCompleter* completer) {
566 // Get the package node.
567 static const char* kPackageNodeXPath(
568 "/response/app/updatecheck/manifest/packages/package");
569
570 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
571 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
572 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700573 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700574 return false;
575 }
576
577 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
578 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
579 CHECK_GE(nodeset->nodeNr, 1);
580
581 // We only care about the first package.
582 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
583 xmlNode* package_node = nodeset->nodeTab[0];
584
585 // Get package properties one by one.
586
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800587 // Parse the payload name to be appended to the base Url value.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700588 const string package_name(XmlGetProperty(package_node, "name"));
589 LOG(INFO) << "Omaha Response package name = " << package_name;
590 if (package_name.empty()) {
591 LOG(ERROR) << "Omaha Response has empty package name";
David Zeuthena99981f2013-04-29 13:42:47 -0700592 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700593 return false;
594 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800595
596 // Append the package name to each URL in our list so that we don't
597 // propagate the urlBase vs packageName distinctions beyond this point.
598 // From now on, we only need to use payload_urls.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700599 for (size_t i = 0; i < output_object->payload_urls.size(); i++)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800600 output_object->payload_urls[i] += package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700601
602 // Parse the payload size.
603 off_t size = ParseInt(XmlGetProperty(package_node, "size"));
604 if (size <= 0) {
605 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
David Zeuthena99981f2013-04-29 13:42:47 -0700606 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700607 return false;
608 }
609 output_object->size = size;
610
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800611 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700612
613 return true;
614}
615
616bool OmahaRequestAction::ParseParams(xmlDoc* doc,
617 OmahaResponse* output_object,
618 ScopedActionCompleter* completer) {
Chris Sosa3b748432013-06-20 16:42:59 -0700619 // XPath location for response elements we care about.
620 static const char* kManifestNodeXPath("/response/app/updatecheck/manifest");\
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700621 static const char* kActionNodeXPath(
Chris Sosa3b748432013-06-20 16:42:59 -0700622 "/response/app/updatecheck/manifest/actions/action");
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700623
Chris Sosa3b748432013-06-20 16:42:59 -0700624 // Get the manifest node where version is present.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700625 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Chris Sosa3b748432013-06-20 16:42:59 -0700626 xpath_manifest_nodeset(GetNodeSet(doc, ConstXMLStr(kManifestNodeXPath)));
627 if (!xpath_manifest_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700628 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700629 return false;
630 }
631
Chris Sosa3b748432013-06-20 16:42:59 -0700632 // Grab the only matching node there should be from the xpath.
633 xmlNodeSet* nodeset = xpath_manifest_nodeset->nodesetval;
634 CHECK(nodeset) << "XPath missing " << kManifestNodeXPath;
635 CHECK_GE(nodeset->nodeNr, 1);
636 xmlNode* manifest_node = nodeset->nodeTab[0];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700637
Chris Sosa3b748432013-06-20 16:42:59 -0700638 // Set the version.
639 output_object->version = XmlGetProperty(manifest_node, kTagVersion);
640 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700641 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Chris Sosa3b748432013-06-20 16:42:59 -0700642 completer->set_code(kErrorCodeOmahaResponseInvalid);
643 return false;
644 }
645
646 LOG(INFO) << "Received omaha response to update to version "
647 << output_object->version;
648
649 // Grab the action nodes.
650 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
651 xpath_action_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
652 if (!xpath_action_nodeset.get()) {
653 completer->set_code(kErrorCodeOmahaResponseInvalid);
654 return false;
655 }
656
657 // We only care about the action that has event "postinstall", because this is
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700658 // where Omaha puts all the generic name/value pairs in the rule.
Chris Sosa3b748432013-06-20 16:42:59 -0700659 nodeset = xpath_action_nodeset->nodesetval;
660 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700661 LOG(INFO) << "Found " << nodeset->nodeNr
662 << " action(s). Processing the postinstall action.";
663
664 // pie_action_node holds the action node corresponding to the
665 // postinstall event action, if present.
666 xmlNode* pie_action_node = NULL;
667 for (int i = 0; i < nodeset->nodeNr; i++) {
668 xmlNode* action_node = nodeset->nodeTab[i];
669 if (XmlGetProperty(action_node, "event") == "postinstall") {
670 pie_action_node = action_node;
671 break;
672 }
673 }
674
675 if (!pie_action_node) {
676 LOG(ERROR) << "Omaha Response has no postinstall event action";
David Zeuthena99981f2013-04-29 13:42:47 -0700677 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700678 return false;
679 }
680
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800681 output_object->hash = XmlGetProperty(pie_action_node, kTagSha256);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700682 if (output_object->hash.empty()) {
683 LOG(ERROR) << "Omaha Response has empty sha256 value";
David Zeuthena99981f2013-04-29 13:42:47 -0700684 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700685 return false;
686 }
687
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800688 // Get the optional properties one by one.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800689 output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700690 output_object->metadata_size =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800691 ParseInt(XmlGetProperty(pie_action_node, kTagMetadataSize));
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700692 output_object->metadata_signature =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800693 XmlGetProperty(pie_action_node, kTagMetadataSignatureRsa);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800694 output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true";
695 output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700696 output_object->max_days_to_scatter =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800697 ParseInt(XmlGetProperty(pie_action_node, kTagMaxDaysToScatter));
David Zeuthen8f191b22013-08-06 12:27:50 -0700698 output_object->disable_p2p_for_downloading =
699 (XmlGetProperty(pie_action_node, kTagDisableP2PForDownloading) == "true");
700 output_object->disable_p2p_for_sharing =
701 (XmlGetProperty(pie_action_node, kTagDisableP2PForSharing) == "true");
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800702
703 string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl);
Jay Srinivasan08262882012-12-28 19:29:43 -0800704 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800705 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700706
Jay Srinivasan08262882012-12-28 19:29:43 -0800707 output_object->is_delta_payload =
708 XmlGetProperty(pie_action_node, kTagIsDeltaPayload) == "true";
709
710 output_object->disable_payload_backoff =
711 XmlGetProperty(pie_action_node, kTagDisablePayloadBackoff) == "true";
712
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700713 return true;
714}
715
rspangler@google.com49fdf182009-10-10 00:57:34 +0000716// If the transfer was successful, this uses libxml2 to parse the response
717// and fill in the appropriate fields of the output object. Also, notifies
718// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700719void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
720 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000721 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800722 string current_response(response_buffer_.begin(), response_buffer_.end());
723 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700724
725 // Events are best effort transactions -- assume they always succeed.
726 if (IsEvent()) {
727 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800728 if (event_->result == OmahaEvent::kResultError && successful &&
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700729 system_state_->hardware()->IsOfficialBuild()) {
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800730 LOG(INFO) << "Signalling Crash Reporter.";
731 utils::ScheduleCrashReporterUpload();
732 }
David Zeuthena99981f2013-04-29 13:42:47 -0700733 completer.set_code(kErrorCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700734 return;
735 }
736
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700737 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700738 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700739 int code = GetHTTPResponseCode();
740 // Makes sure we send sane error values.
741 if (code < 0 || code >= 1000) {
742 code = 999;
743 }
David Zeuthena99981f2013-04-29 13:42:47 -0700744 completer.set_code(static_cast<ErrorCode>(
745 kErrorCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000746 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700747 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000748
749 // parse our response and fill the fields in the output object
750 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
751 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
752 if (!doc.get()) {
753 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700754 completer.set_code(response_buffer_.empty() ?
David Zeuthena99981f2013-04-29 13:42:47 -0700755 kErrorCodeOmahaRequestEmptyResponseError :
756 kErrorCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000757 return;
758 }
759
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700760 // If a ping was sent, update the last ping day preferences based on
761 // the server daystart response.
762 if (ShouldPing(ping_active_days_) ||
763 ShouldPing(ping_roll_call_days_) ||
764 ping_active_days_ == kPingTimeJump ||
765 ping_roll_call_days_ == kPingTimeJump) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800766 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700767 << "Failed to update the last ping day preferences!";
768 }
769
Thieu Le116fda32011-04-19 11:01:54 -0700770 if (!HasOutputPipe()) {
771 // Just set success to whether or not the http transfer succeeded,
772 // which must be true at this point in the code.
David Zeuthena99981f2013-04-29 13:42:47 -0700773 completer.set_code(kErrorCodeSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700774 return;
775 }
776
Darin Petkov6a5b3222010-07-13 14:55:28 -0700777 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700778 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000779 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700780 output_object.update_exists = true;
781 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000782
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700783 if (params_->update_disabled()) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700784 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700785 output_object.update_exists = false;
David Zeuthena99981f2013-04-29 13:42:47 -0700786 completer.set_code(kErrorCodeOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700787 // Note: We could technically delete the UpdateFirstSeenAt state here.
788 // If we do, it'll mean a device has to restart the UpdateFirstSeenAt
789 // and thus help scattering take effect when the AU is turned on again.
790 // On the other hand, it also increases the chance of update starvation if
791 // an admin turns AU on/off more frequently. We choose to err on the side
792 // of preventing starvation at the cost of not applying scattering in
793 // those cases.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700794 return;
795 }
796
David Zeuthen8f191b22013-08-06 12:27:50 -0700797 // If Omaha says to disable p2p, respect that
798 if (output_object.disable_p2p_for_downloading) {
799 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
800 << "requested by Omaha.";
801 params_->set_use_p2p_for_downloading(false);
802 }
803 if (output_object.disable_p2p_for_sharing) {
804 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
805 << "requested by Omaha.";
806 params_->set_use_p2p_for_sharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700807 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800808
809 // Update the payload state with the current response. The payload state
810 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800811 // from what's stored already. We are updating the payload state as late
812 // as possible in this method so that if a new release gets pushed and then
813 // got pulled back due to some issues, we don't want to clear our internal
814 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800815 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800816 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800817
David Zeuthen8f191b22013-08-06 12:27:50 -0700818 // It could be we've already exceeded the deadline for when p2p is
819 // allowed or that we've tried too many times with p2p. Check that.
820 if (params_->use_p2p_for_downloading()) {
821 payload_state->P2PNewAttempt();
822 if (!payload_state->P2PAttemptAllowed()) {
823 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
824 << "of previous failures when using p2p.";
825 params_->set_use_p2p_for_downloading(false);
826 }
827 }
828
829 // From here on, we'll complete stuff in CompleteProcessing() so
830 // disable |completer| since we'll create a new one in that
831 // function.
832 completer.set_should_complete(false);
833
834 // If we're allowed to use p2p for downloading we do not pay
835 // attention to wall-clock-based waiting if the URL is indeed
836 // available via p2p. Therefore, check if the file is available via
837 // p2p before deferring...
838 if (params_->use_p2p_for_downloading()) {
839 LookupPayloadViaP2P(output_object);
840 } else {
841 CompleteProcessing();
842 }
843}
844
845void OmahaRequestAction::CompleteProcessing() {
846 ScopedActionCompleter completer(processor_, this);
847 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
848 PayloadStateInterface* payload_state = system_state_->payload_state();
849
850 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800851 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -0700852 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
853 completer.set_code(kErrorCodeOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -0800854 return;
855 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700856
Chris Sosa20f005c2013-09-05 13:53:08 -0700857 if (payload_state->ShouldBackoffDownload()) {
858 output_object.update_exists = false;
859 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
860 << "attempts";
861 completer.set_code(kErrorCodeOmahaUpdateDeferredForBackoff);
862 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700863 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700864 completer.set_code(kErrorCodeSuccess);
865}
866
867void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
868 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
869 if (!url.empty()) {
870 params_->set_p2p_url(url);
871 } else {
872 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
873 << "because no suitable peer could be found.";
874 params_->set_use_p2p_for_downloading(false);
875 }
876 CompleteProcessing();
877}
878
879void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -0700880 // If the device is in the middle of an update, the state variables
881 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
882 // tracks the offset and length of the operation currently in
883 // progress. The offset is based from the end of the manifest which
884 // is kPrefsManifestMetadataSize bytes long.
885 //
886 // To make forward progress and avoid deadlocks, we need to find a
887 // peer that has at least the entire operation we're currently
888 // working on. Otherwise we may end up in a situation where two
889 // devices bounce back and forth downloading from each other,
890 // neither making any forward progress until one of them decides to
891 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
892 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -0700893 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -0700894 int64_t manifest_metadata_size = 0;
895 int64_t next_data_offset = 0;
896 int64_t next_data_length = 0;
David Zeuthen8f191b22013-08-06 12:27:50 -0700897 if (system_state_ != NULL &&
David Zeuthen41996ad2013-09-24 15:43:24 -0700898 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
899 &manifest_metadata_size) &&
900 manifest_metadata_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -0700901 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -0700902 &next_data_offset) &&
903 next_data_offset != -1 &&
904 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
905 &next_data_length)) {
906 minimum_size = manifest_metadata_size + next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -0700907 }
908
909 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
910 if (system_state_->p2p_manager() != NULL) {
911 LOG(INFO) << "Checking if payload is available via p2p, file_id="
912 << file_id << " minimum_size=" << minimum_size;
913 system_state_->p2p_manager()->LookupUrlForFile(
914 file_id,
915 minimum_size,
916 TimeDelta::FromHours(kMaxP2PNetworkWaitTimeSeconds),
917 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
918 base::Unretained(this)));
919 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000920}
921
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700922bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -0700923 if (params_->interactive()) {
924 LOG(INFO) << "Not deferring download because update is interactive.";
925 return false;
926 }
927
David Zeuthen8f191b22013-08-06 12:27:50 -0700928 // If we're using p2p to download _and_ we have a p2p URL, we never
929 // defer the download. This is because the download will always
930 // happen from a peer on the LAN and we've been waiting in line for
931 // our turn.
932 if (params_->use_p2p_for_downloading() && !params_->p2p_url().empty()) {
933 LOG(INFO) << "Download not deferred because download "
934 << "will happen from a local peer (via p2p).";
935 return false;
936 }
937
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700938 // We should defer the downloads only if we've first satisfied the
939 // wall-clock-based-waiting period and then the update-check-based waiting
940 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700941 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -0700942 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
943 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700944 return false;
945 }
946
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700947 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700948 case kWallClockWaitNotSatisfied:
949 // We haven't even satisfied the first condition, passing the
950 // wall-clock-based waiting period, so we should defer the downloads
951 // until that happens.
952 LOG(INFO) << "wall-clock-based-wait not satisfied.";
953 return true;
954
955 case kWallClockWaitDoneButUpdateCheckWaitRequired:
956 LOG(INFO) << "wall-clock-based-wait satisfied and "
957 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700958 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700959
960 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
961 // Wall-clock-based waiting period is satisfied, and it's determined
962 // that we do not need the update-check-based wait. so no need to
963 // defer downloads.
964 LOG(INFO) << "wall-clock-based-wait satisfied and "
965 << "update-check-based-wait is not required.";
966 return false;
967
968 default:
969 // Returning false for this default case so we err on the
970 // side of downloading updates than deferring in case of any bugs.
971 NOTREACHED();
972 return false;
973 }
974}
975
976OmahaRequestAction::WallClockWaitResult
977OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700978 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700979 Time update_first_seen_at;
980 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700981
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800982 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
983 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
984 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700985 // Note: This timestamp could be that of ANY update we saw in the past
986 // (not necessarily this particular update we're considering to apply)
987 // but never got to apply because of some reason (e.g. stop AU policy,
988 // updates being pulled out from Omaha, changes in target version prefix,
989 // new update being rolled out, etc.). But for the purposes of scattering
990 // it doesn't matter which update the timestamp corresponds to. i.e.
991 // the clock starts ticking the first time we see an update and we're
992 // ready to apply when the random wait period is satisfied relative to
993 // that first seen timestamp.
994 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
995 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
996 << utils::ToString(update_first_seen_at);
997 } else {
998 // This seems like an unexpected error where the persisted value exists
999 // but it's not readable for some reason. Just skip scattering in this
1000 // case to be safe.
1001 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1002 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1003 }
1004 } else {
1005 update_first_seen_at = Time::Now();
1006 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001007 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1008 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001009 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1010 << utils::ToString(update_first_seen_at);
1011 }
1012 else {
1013 // This seems like an unexpected error where the value cannot be
1014 // persisted for some reason. Just skip scattering in this
1015 // case to be safe.
1016 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1017 << utils::ToString(update_first_seen_at)
1018 << " cannot be persisted";
1019 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1020 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001021 }
1022
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001023 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001024 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001025 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001026
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001027 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001028 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001029 << ", Time Elapsed = "
1030 << utils::FormatSecs(elapsed_time.InSeconds())
1031 << ", MaxDaysToScatter = "
1032 << max_scatter_period.InDays();
1033
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001034 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001035 // The deadline is set for all rules which serve a delta update from a
1036 // previous FSI, which means this update will be applied mostly in OOBE
1037 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1038 // quickly.
1039 LOG(INFO) << "Not scattering as deadline flag is set";
1040 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1041 }
1042
1043 if (max_scatter_period.InDays() == 0) {
1044 // This means the Omaha rule creator decides that this rule
1045 // should not be scattered irrespective of the policy.
1046 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1047 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1048 }
1049
1050 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001051 // This means we've waited more than the upperbound wait in the rule
1052 // from the time we first saw a valid update available to us.
1053 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001054 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1055 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1056 }
1057
1058 // This means we are required to participate in scattering.
1059 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001060 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001061 if (remaining_wait_time.InSeconds() <= 0) {
1062 // Yes, it's our turn now.
1063 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1064
1065 // But we can't download until the update-check-count-based wait is also
1066 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001067 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001068 kWallClockWaitDoneButUpdateCheckWaitRequired :
1069 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1070 }
1071
1072 // Not our turn yet, so we have to wait until our turn to
1073 // help scatter the downloads across all clients of the enterprise.
1074 LOG(INFO) << "Update deferred for another "
1075 << utils::FormatSecs(remaining_wait_time.InSeconds())
1076 << " per policy.";
1077 return kWallClockWaitNotSatisfied;
1078}
1079
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001080bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001081 int64 update_check_count_value;
1082
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001083 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1084 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1085 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001086 // We are unable to read the update check count from file for some reason.
1087 // So let's proceed anyway so as to not stall the update.
1088 LOG(ERROR) << "Unable to read update check count. "
1089 << "Skipping update-check-count-based-wait.";
1090 return true;
1091 }
1092 } else {
1093 // This file does not exist. This means we haven't started our update
1094 // check count down yet, so this is the right time to start the count down.
1095 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001096 params_->min_update_checks_needed(),
1097 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001098
1099 LOG(INFO) << "Randomly picked update check count value = "
1100 << update_check_count_value;
1101
1102 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001103 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1104 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001105 // We weren't able to write the update check count file for some reason.
1106 // So let's proceed anyway so as to not stall the update.
1107 LOG(ERROR) << "Unable to write update check count. "
1108 << "Skipping update-check-count-based-wait.";
1109 return true;
1110 }
1111 }
1112
1113 if (update_check_count_value == 0) {
1114 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1115 return true;
1116 }
1117
1118 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001119 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001120 // We err on the side of skipping scattering logic instead of stalling
1121 // a machine from receiving any updates in case of any unexpected state.
1122 LOG(ERROR) << "Invalid value for update check count detected. "
1123 << "Skipping update-check-count-based-wait.";
1124 return true;
1125 }
1126
1127 // Legal value, we need to wait for more update checks to happen
1128 // until this becomes 0.
1129 LOG(INFO) << "Deferring Omaha updates for another "
1130 << update_check_count_value
1131 << " update checks per policy";
1132 return false;
1133}
1134
1135} // namespace chromeos_update_engine
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001136
1137