blob: 016b5a827ad39a38bc055569e41d9ad4865f2c5e [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"
David Zeuthen8f191b22013-08-06 12:27:50 -070024#include "update_engine/omaha_hash_calculator.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070025#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070026#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080027#include "update_engine/payload_state_interface.h"
Darin Petkov1cbd78f2010-07-29 12:38:34 -070028#include "update_engine/prefs_interface.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000029#include "update_engine/utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000030
Darin Petkov1cbd78f2010-07-29 12:38:34 -070031using base::Time;
32using base::TimeDelta;
rspangler@google.com49fdf182009-10-10 00:57:34 +000033using std::string;
34
35namespace chromeos_update_engine {
36
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080037// List of custom pair tags that we interpret in the Omaha Response:
38static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080039static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070040static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080041// Deprecated: "IsDelta"
42static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080043static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
44static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
45// Deprecated: "ManifestSignatureRsa"
46// Deprecated: "ManifestSize"
47static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
48static const char* kTagMetadataSize = "MetadataSize";
49static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070050// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080051static const char* kTagPrompt = "Prompt";
52static const char* kTagSha256 = "sha256";
David Zeuthen8f191b22013-08-06 12:27:50 -070053static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
54static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080055
rspangler@google.com49fdf182009-10-10 00:57:34 +000056namespace {
57
58const string kGupdateVersion("ChromeOSUpdateEngine-0.1.0.0");
59
60// This is handy for passing strings into libxml2
61#define ConstXMLStr(x) (reinterpret_cast<const xmlChar*>(x))
62
63// These are for scoped_ptr_malloc, which is like scoped_ptr, but allows
64// a custom free() function to be specified.
65class ScopedPtrXmlDocFree {
66 public:
67 inline void operator()(void* x) const {
68 xmlFreeDoc(reinterpret_cast<xmlDoc*>(x));
69 }
70};
71class ScopedPtrXmlFree {
72 public:
73 inline void operator()(void* x) const {
74 xmlFree(x);
75 }
76};
77class ScopedPtrXmlXPathObjectFree {
78 public:
79 inline void operator()(void* x) const {
80 xmlXPathFreeObject(reinterpret_cast<xmlXPathObject*>(x));
81 }
82};
83class ScopedPtrXmlXPathContextFree {
84 public:
85 inline void operator()(void* x) const {
86 xmlXPathFreeContext(reinterpret_cast<xmlXPathContext*>(x));
87 }
88};
89
Darin Petkov1cbd78f2010-07-29 12:38:34 -070090// Returns true if |ping_days| has a value that needs to be sent,
91// false otherwise.
92bool ShouldPing(int ping_days) {
93 return ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged;
94}
95
96// Returns an XML ping element attribute assignment with attribute
97// |name| and value |ping_days| if |ping_days| has a value that needs
98// to be sent, or an empty string otherwise.
99string GetPingAttribute(const string& name, int ping_days) {
100 if (ShouldPing(ping_days)) {
101 return StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
102 }
103 return "";
104}
105
106// Returns an XML ping element if any of the elapsed days need to be
107// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700108string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700109 string ping_active = GetPingAttribute("a", ping_active_days);
110 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
111 if (!ping_active.empty() || !ping_roll_call.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700112 return StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700113 ping_active.c_str(),
114 ping_roll_call.c_str());
115 }
116 return "";
117}
118
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700119// Returns an XML that goes into the body of the <app> element of the Omaha
120// request based on the given parameters.
121string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700122 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700123 bool ping_only,
124 int ping_active_days,
125 int ping_roll_call_days,
126 PrefsInterface* prefs) {
127 string app_body;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700128 if (event == NULL) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700129 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700130 if (!ping_only) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700131 // not passing update_disabled to Omaha because we want to
132 // get the update and report with UpdateDeferred result so that
133 // borgmon charts show up updates that are deferred. This is also
134 // the expected behavior when we move to Omaha v3.0 protocol, so it'll
135 // be consistent.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700136 app_body += StringPrintf(
137 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700138 "></updatecheck>\n",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700139 XmlEncode(params->target_version_prefix()).c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700140
Darin Petkov265f2902011-05-09 15:17:40 -0700141 // If this is the first update check after a reboot following a previous
142 // update, generate an event containing the previous version number. If
143 // the previous version preference file doesn't exist the event is still
144 // generated with a previous version of 0.0.0.0 -- this is relevant for
145 // older clients or new installs. The previous version event is not sent
146 // for ping-only requests because they come before the client has
147 // rebooted.
148 string prev_version;
149 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
150 prev_version = "0.0.0.0";
151 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700152
153 app_body += StringPrintf(
154 " <event eventtype=\"%d\" eventresult=\"%d\" "
155 "previousversion=\"%s\"></event>\n",
156 OmahaEvent::kTypeUpdateComplete,
157 OmahaEvent::kResultSuccessReboot,
158 XmlEncode(prev_version).c_str());
159 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
160 << "Unable to reset the previous version.";
Darin Petkov95508da2011-01-05 12:42:29 -0800161 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700162 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800163 // The error code is an optional attribute so append it only if the result
164 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700165 string error_code;
166 if (event->result != OmahaEvent::kResultSuccess) {
Darin Petkov18c7bce2011-06-16 14:07:00 -0700167 error_code = StringPrintf(" errorcode=\"%d\"", event->error_code);
Darin Petkove17f86b2010-07-20 09:12:01 -0700168 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700169 app_body = StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700170 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700171 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700172 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700173
174 return app_body;
175}
176
177// Returns an XML that corresponds to the entire <app> node of the Omaha
178// request based on the given parameters.
179string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700180 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700181 bool ping_only,
182 int ping_active_days,
183 int ping_roll_call_days,
184 SystemState* system_state) {
185 string app_body = GetAppBody(event, params, ping_only, ping_active_days,
186 ping_roll_call_days, system_state->prefs());
187 string app_versions;
188
189 // If we are upgrading to a more stable channel and we are allowed to do
190 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
191 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700192 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700193 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
194 << "on downgrading to the version in the more stable channel";
195 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700196 XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700197 } else {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700198 app_versions = "version=\"" + XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700199 }
200
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700201 string download_channel = params->download_channel();
202 string app_channels = "track=\"" + XmlEncode(download_channel) + "\" ";
203 if (params->current_channel() != download_channel)
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700204 app_channels +=
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700205 "from_track=\"" + XmlEncode(params->current_channel()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700206
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700207 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700208
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700209 string app_xml =
Jay Srinivasandb0acdf2013-04-02 14:47:45 -0700210 " <app appid=\"" + XmlEncode(params->GetAppId()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700211 app_versions +
212 app_channels +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700213 "lang=\"" + XmlEncode(params->app_lang()) + "\" " +
214 "board=\"" + XmlEncode(params->os_board()) + "\" " +
215 "hardware_class=\"" + XmlEncode(params->hwid()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700216 "delta_okay=\"" + delta_okay_str + "\" "
Chris Sosac1972482013-04-30 22:31:10 -0700217 "fw_version=\"" + XmlEncode(params->fw_version()) + "\" " +
218 "ec_version=\"" + XmlEncode(params->ec_version()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700219 ">\n" +
220 app_body +
221 " </app>\n";
222
223 return app_xml;
224}
225
226// Returns an XML that corresponds to the entire <os> node of the Omaha
227// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700228string GetOsXml(OmahaRequestParams* params) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700229 string os_xml =
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700230 " <os version=\"" + XmlEncode(params->os_version()) + "\" " +
231 "platform=\"" + XmlEncode(params->os_platform()) + "\" " +
232 "sp=\"" + XmlEncode(params->os_sp()) + "\">"
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700233 "</os>\n";
234 return os_xml;
235}
236
237// Returns an XML that corresponds to the entire Omaha request based on the
238// given parameters.
239string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700240 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700241 bool ping_only,
242 int ping_active_days,
243 int ping_roll_call_days,
244 SystemState* system_state) {
245 string os_xml = GetOsXml(params);
246 string app_xml = GetAppXml(event, params, ping_only, ping_active_days,
247 ping_roll_call_days, system_state);
248
249 string install_source = StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700250 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700251
252 string request_xml =
253 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700254 "<request protocol=\"3.0\" "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700255 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
256 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" " +
257 install_source +
258 "ismachine=\"1\">\n" +
259 os_xml +
260 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700261 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700262
263 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000264}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700265
rspangler@google.com49fdf182009-10-10 00:57:34 +0000266} // namespace {}
267
268// Encodes XML entities in a given string with libxml2. input must be
269// UTF-8 formatted. Output will be UTF-8 formatted.
270string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700271 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
272 // // cpu, considering creating one and caching it.
273 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
274 // xmlNewDoc(ConstXMLStr("1.0")));
275 // if (!xml_doc.get()) {
276 // LOG(ERROR) << "Unable to create xmlDoc";
277 // return "";
278 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000279 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
280 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
281 return string(reinterpret_cast<const char *>(str.get()));
282}
283
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800284OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700285 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700286 HttpFetcher* http_fetcher,
287 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800288 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700289 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700290 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700291 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700292 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700293 ping_roll_call_days_(0) {
294 params_ = system_state->request_params();
295}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000296
Darin Petkov6a5b3222010-07-13 14:55:28 -0700297OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000298
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700299// Calculates the value to use for the ping days parameter.
300int OmahaRequestAction::CalculatePingDays(const string& key) {
301 int days = kNeverPinged;
302 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800303 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700304 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
305 if (days < 0) {
306 // If |days| is negative, then the system clock must have jumped
307 // back in time since the ping was sent. Mark the value so that
308 // it doesn't get sent to the server but we still update the
309 // last ping daystart preference. This way the next ping time
310 // will be correct, hopefully.
311 days = kPingTimeJump;
312 LOG(WARNING) <<
313 "System clock jumped back in time. Resetting ping daystarts.";
314 }
315 }
316 return days;
317}
318
319void OmahaRequestAction::InitPingDays() {
320 // We send pings only along with update checks, not with events.
321 if (IsEvent()) {
322 return;
323 }
324 // TODO(petkov): Figure a way to distinguish active use pings
325 // vs. roll call pings. Currently, the two pings are identical. A
326 // fix needs to change this code as well as UpdateLastPingDays.
327 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
328 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
329}
330
Darin Petkov6a5b3222010-07-13 14:55:28 -0700331void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000332 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700333 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700334 if (ping_only_ &&
335 !ShouldPing(ping_active_days_) &&
336 !ShouldPing(ping_roll_call_days_)) {
David Zeuthena99981f2013-04-29 13:42:47 -0700337 processor_->ActionComplete(this, kErrorCodeSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700338 return;
339 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700340 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700341 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700342 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700343 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800344 ping_roll_call_days_,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700345 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700346
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800347 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
348 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700349 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700350 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700351 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000352}
353
Darin Petkov6a5b3222010-07-13 14:55:28 -0700354void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000355 http_fetcher_->TerminateTransfer();
356}
357
358// We just store the response in the buffer. Once we've received all bytes,
359// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700360void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
361 const char* bytes,
362 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000363 response_buffer_.reserve(response_buffer_.size() + length);
364 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
365}
366
367namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000368// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
369// on the returned object.
370// This code is roughly based on the libxml tutorial at:
371// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700372xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000373 xmlXPathObject* result = NULL;
374
375 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
376 xmlXPathNewContext(doc));
377 if (!context.get()) {
378 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
379 return NULL;
380 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000381
382 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000383 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700384 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000385 return NULL;
386 }
387 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700388 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000389 xmlXPathFreeObject(result);
390 return NULL;
391 }
392 return result;
393}
394
395// Returns the string value of a named attribute on a node, or empty string
396// if no such node exists. If the attribute exists and has a value of
397// empty string, there's no way to distinguish that from the attribute
398// not existing.
399string XmlGetProperty(xmlNode* node, const char* name) {
400 if (!xmlHasProp(node, ConstXMLStr(name)))
401 return "";
402 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
403 xmlGetProp(node, ConstXMLStr(name)));
404 string ret(reinterpret_cast<const char *>(str.get()));
405 return ret;
406}
407
408// Parses a 64 bit base-10 int from a string and returns it. Returns 0
409// on error. If the string contains "0", that's indistinguishable from
410// error.
411off_t ParseInt(const string& str) {
412 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700413 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000414 if (rc < 1) {
415 // failure
416 return 0;
417 }
418 return ret;
419}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700420
421// Update the last ping day preferences based on the server daystart
422// response. Returns true on success, false otherwise.
423bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700424 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700425
426 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700427 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700428 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
429 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
430 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
431 xmlNode* daystart_node = nodeset->nodeTab[0];
432 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
433 ConstXMLStr("elapsed_seconds")));
434
435 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700436 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
437 "elapsed_seconds"),
438 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700439 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
440
441 // Remember the local time that matches the server's last midnight
442 // time.
443 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
444 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
445 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
446 return true;
447}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000448} // namespace {}
449
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700450bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
451 OmahaResponse* output_object,
452 ScopedActionCompleter* completer) {
453 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
454
455 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
456 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
457 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700458 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700459 return false;
460 }
461
462 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
463 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
464 CHECK_GE(nodeset->nodeNr, 1);
465 xmlNode* update_check_node = nodeset->nodeTab[0];
466
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800467 // chromium-os:37289: The PollInterval is not supported by Omaha server
468 // currently. But still keeping this existing code in case we ever decide to
469 // slow down the request rate from the server-side. Note that the
470 // PollInterval is not persisted, so it has to be sent by the server on every
471 // response to guarantee that the UpdateCheckScheduler uses this value
472 // (otherwise, if the device got rebooted after the last server-indicated
473 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
474 // value for the scattering logic is based on the assumption that we perform
475 // an update check every hour so that the max value of 8 will roughly be
476 // equivalent to one work day. If we decide to use PollInterval permanently,
477 // we should update the max_update_checks_allowed to take PollInterval into
478 // account. Note: The parsing for PollInterval happens even before parsing
479 // of the status because we may want to specify the PollInterval even when
480 // there's no update.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700481 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
482 &output_object->poll_interval);
483
484 if (!ParseStatus(update_check_node, output_object, completer))
485 return false;
486
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800487 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
488 // appends the package name to the URLs populated in this method.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700489 if (!ParseUrls(doc, output_object, completer))
490 return false;
491
492 if (!ParsePackage(doc, output_object, completer))
493 return false;
494
495 if (!ParseParams(doc, output_object, completer))
496 return false;
497
498 return true;
499}
500
501bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
502 OmahaResponse* output_object,
503 ScopedActionCompleter* completer) {
504 // Get status.
505 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
506 LOG(ERROR) << "Omaha Response missing status";
David Zeuthena99981f2013-04-29 13:42:47 -0700507 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700508 return false;
509 }
510
511 const string status(XmlGetProperty(update_check_node, "status"));
512 if (status == "noupdate") {
513 LOG(INFO) << "No update.";
514 output_object->update_exists = false;
515 SetOutputObject(*output_object);
David Zeuthena99981f2013-04-29 13:42:47 -0700516 completer->set_code(kErrorCodeSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700517 return false;
518 }
519
520 if (status != "ok") {
521 LOG(ERROR) << "Unknown Omaha response status: " << status;
David Zeuthena99981f2013-04-29 13:42:47 -0700522 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700523 return false;
524 }
525
526 return true;
527}
528
529bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
530 OmahaResponse* output_object,
531 ScopedActionCompleter* completer) {
532 // Get the update URL.
533 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
534
535 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
536 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
537 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700538 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700539 return false;
540 }
541
542 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
543 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
544 CHECK_GE(nodeset->nodeNr, 1);
545
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800546 LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)";
547 output_object->payload_urls.clear();
548 for (int i = 0; i < nodeset->nodeNr; i++) {
549 xmlNode* url_node = nodeset->nodeTab[i];
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800550 const string codebase(XmlGetProperty(url_node, "codebase"));
551 if (codebase.empty()) {
552 LOG(ERROR) << "Omaha Response URL has empty codebase";
David Zeuthena99981f2013-04-29 13:42:47 -0700553 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800554 return false;
555 }
556 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700557 }
558
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700559 return true;
560}
561
562bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
563 OmahaResponse* output_object,
564 ScopedActionCompleter* completer) {
565 // Get the package node.
566 static const char* kPackageNodeXPath(
567 "/response/app/updatecheck/manifest/packages/package");
568
569 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
570 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
571 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700572 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700573 return false;
574 }
575
576 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
577 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
578 CHECK_GE(nodeset->nodeNr, 1);
579
580 // We only care about the first package.
581 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
582 xmlNode* package_node = nodeset->nodeTab[0];
583
584 // Get package properties one by one.
585
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800586 // Parse the payload name to be appended to the base Url value.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700587 const string package_name(XmlGetProperty(package_node, "name"));
588 LOG(INFO) << "Omaha Response package name = " << package_name;
589 if (package_name.empty()) {
590 LOG(ERROR) << "Omaha Response has empty package name";
David Zeuthena99981f2013-04-29 13:42:47 -0700591 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700592 return false;
593 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800594
595 // Append the package name to each URL in our list so that we don't
596 // propagate the urlBase vs packageName distinctions beyond this point.
597 // From now on, we only need to use payload_urls.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700598 for (size_t i = 0; i < output_object->payload_urls.size(); i++)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800599 output_object->payload_urls[i] += package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700600
601 // Parse the payload size.
602 off_t size = ParseInt(XmlGetProperty(package_node, "size"));
603 if (size <= 0) {
604 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
David Zeuthena99981f2013-04-29 13:42:47 -0700605 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700606 return false;
607 }
608 output_object->size = size;
609
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800610 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700611
612 return true;
613}
614
615bool OmahaRequestAction::ParseParams(xmlDoc* doc,
616 OmahaResponse* output_object,
617 ScopedActionCompleter* completer) {
Chris Sosa3b748432013-06-20 16:42:59 -0700618 // XPath location for response elements we care about.
619 static const char* kManifestNodeXPath("/response/app/updatecheck/manifest");\
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700620 static const char* kActionNodeXPath(
Chris Sosa3b748432013-06-20 16:42:59 -0700621 "/response/app/updatecheck/manifest/actions/action");
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700622
Chris Sosa3b748432013-06-20 16:42:59 -0700623 // Get the manifest node where version is present.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700624 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Chris Sosa3b748432013-06-20 16:42:59 -0700625 xpath_manifest_nodeset(GetNodeSet(doc, ConstXMLStr(kManifestNodeXPath)));
626 if (!xpath_manifest_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700627 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700628 return false;
629 }
630
Chris Sosa3b748432013-06-20 16:42:59 -0700631 // Grab the only matching node there should be from the xpath.
632 xmlNodeSet* nodeset = xpath_manifest_nodeset->nodesetval;
633 CHECK(nodeset) << "XPath missing " << kManifestNodeXPath;
634 CHECK_GE(nodeset->nodeNr, 1);
635 xmlNode* manifest_node = nodeset->nodeTab[0];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700636
Chris Sosa3b748432013-06-20 16:42:59 -0700637 // Set the version.
638 output_object->version = XmlGetProperty(manifest_node, kTagVersion);
639 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700640 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Chris Sosa3b748432013-06-20 16:42:59 -0700641 completer->set_code(kErrorCodeOmahaResponseInvalid);
642 return false;
643 }
644
645 LOG(INFO) << "Received omaha response to update to version "
646 << output_object->version;
647
648 // Grab the action nodes.
649 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
650 xpath_action_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
651 if (!xpath_action_nodeset.get()) {
652 completer->set_code(kErrorCodeOmahaResponseInvalid);
653 return false;
654 }
655
656 // We only care about the action that has event "postinstall", because this is
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700657 // where Omaha puts all the generic name/value pairs in the rule.
Chris Sosa3b748432013-06-20 16:42:59 -0700658 nodeset = xpath_action_nodeset->nodesetval;
659 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700660 LOG(INFO) << "Found " << nodeset->nodeNr
661 << " action(s). Processing the postinstall action.";
662
663 // pie_action_node holds the action node corresponding to the
664 // postinstall event action, if present.
665 xmlNode* pie_action_node = NULL;
666 for (int i = 0; i < nodeset->nodeNr; i++) {
667 xmlNode* action_node = nodeset->nodeTab[i];
668 if (XmlGetProperty(action_node, "event") == "postinstall") {
669 pie_action_node = action_node;
670 break;
671 }
672 }
673
674 if (!pie_action_node) {
675 LOG(ERROR) << "Omaha Response has no postinstall event action";
David Zeuthena99981f2013-04-29 13:42:47 -0700676 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700677 return false;
678 }
679
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800680 output_object->hash = XmlGetProperty(pie_action_node, kTagSha256);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700681 if (output_object->hash.empty()) {
682 LOG(ERROR) << "Omaha Response has empty sha256 value";
David Zeuthena99981f2013-04-29 13:42:47 -0700683 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700684 return false;
685 }
686
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800687 // Get the optional properties one by one.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800688 output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700689 output_object->metadata_size =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800690 ParseInt(XmlGetProperty(pie_action_node, kTagMetadataSize));
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700691 output_object->metadata_signature =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800692 XmlGetProperty(pie_action_node, kTagMetadataSignatureRsa);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800693 output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true";
694 output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700695 output_object->max_days_to_scatter =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800696 ParseInt(XmlGetProperty(pie_action_node, kTagMaxDaysToScatter));
David Zeuthen8f191b22013-08-06 12:27:50 -0700697 output_object->disable_p2p_for_downloading =
698 (XmlGetProperty(pie_action_node, kTagDisableP2PForDownloading) == "true");
699 output_object->disable_p2p_for_sharing =
700 (XmlGetProperty(pie_action_node, kTagDisableP2PForSharing) == "true");
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800701
702 string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl);
Jay Srinivasan08262882012-12-28 19:29:43 -0800703 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800704 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700705
Jay Srinivasan08262882012-12-28 19:29:43 -0800706 output_object->is_delta_payload =
707 XmlGetProperty(pie_action_node, kTagIsDeltaPayload) == "true";
708
709 output_object->disable_payload_backoff =
710 XmlGetProperty(pie_action_node, kTagDisablePayloadBackoff) == "true";
711
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700712 return true;
713}
714
rspangler@google.com49fdf182009-10-10 00:57:34 +0000715// If the transfer was successful, this uses libxml2 to parse the response
716// and fill in the appropriate fields of the output object. Also, notifies
717// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700718void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
719 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000720 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800721 string current_response(response_buffer_.begin(), response_buffer_.end());
722 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700723
724 // Events are best effort transactions -- assume they always succeed.
725 if (IsEvent()) {
726 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800727 if (event_->result == OmahaEvent::kResultError && successful &&
728 utils::IsOfficialBuild()) {
729 LOG(INFO) << "Signalling Crash Reporter.";
730 utils::ScheduleCrashReporterUpload();
731 }
David Zeuthena99981f2013-04-29 13:42:47 -0700732 completer.set_code(kErrorCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700733 return;
734 }
735
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700736 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700737 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700738 int code = GetHTTPResponseCode();
739 // Makes sure we send sane error values.
740 if (code < 0 || code >= 1000) {
741 code = 999;
742 }
David Zeuthena99981f2013-04-29 13:42:47 -0700743 completer.set_code(static_cast<ErrorCode>(
744 kErrorCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000745 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700746 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000747
748 // parse our response and fill the fields in the output object
749 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
750 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
751 if (!doc.get()) {
752 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700753 completer.set_code(response_buffer_.empty() ?
David Zeuthena99981f2013-04-29 13:42:47 -0700754 kErrorCodeOmahaRequestEmptyResponseError :
755 kErrorCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000756 return;
757 }
758
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700759 // If a ping was sent, update the last ping day preferences based on
760 // the server daystart response.
761 if (ShouldPing(ping_active_days_) ||
762 ShouldPing(ping_roll_call_days_) ||
763 ping_active_days_ == kPingTimeJump ||
764 ping_roll_call_days_ == kPingTimeJump) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800765 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700766 << "Failed to update the last ping day preferences!";
767 }
768
Thieu Le116fda32011-04-19 11:01:54 -0700769 if (!HasOutputPipe()) {
770 // Just set success to whether or not the http transfer succeeded,
771 // which must be true at this point in the code.
David Zeuthena99981f2013-04-29 13:42:47 -0700772 completer.set_code(kErrorCodeSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700773 return;
774 }
775
Darin Petkov6a5b3222010-07-13 14:55:28 -0700776 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700777 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000778 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700779 output_object.update_exists = true;
780 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000781
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700782 if (params_->update_disabled()) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700783 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700784 output_object.update_exists = false;
David Zeuthena99981f2013-04-29 13:42:47 -0700785 completer.set_code(kErrorCodeOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700786 // Note: We could technically delete the UpdateFirstSeenAt state here.
787 // If we do, it'll mean a device has to restart the UpdateFirstSeenAt
788 // and thus help scattering take effect when the AU is turned on again.
789 // On the other hand, it also increases the chance of update starvation if
790 // an admin turns AU on/off more frequently. We choose to err on the side
791 // of preventing starvation at the cost of not applying scattering in
792 // those cases.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700793 return;
794 }
795
David Zeuthen8f191b22013-08-06 12:27:50 -0700796 // If Omaha says to disable p2p, respect that
797 if (output_object.disable_p2p_for_downloading) {
798 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
799 << "requested by Omaha.";
800 params_->set_use_p2p_for_downloading(false);
801 }
802 if (output_object.disable_p2p_for_sharing) {
803 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
804 << "requested by Omaha.";
805 params_->set_use_p2p_for_sharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700806 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800807
808 // Update the payload state with the current response. The payload state
809 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800810 // from what's stored already. We are updating the payload state as late
811 // as possible in this method so that if a new release gets pushed and then
812 // got pulled back due to some issues, we don't want to clear our internal
813 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800814 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800815 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800816
David Zeuthen8f191b22013-08-06 12:27:50 -0700817 // It could be we've already exceeded the deadline for when p2p is
818 // allowed or that we've tried too many times with p2p. Check that.
819 if (params_->use_p2p_for_downloading()) {
820 payload_state->P2PNewAttempt();
821 if (!payload_state->P2PAttemptAllowed()) {
822 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
823 << "of previous failures when using p2p.";
824 params_->set_use_p2p_for_downloading(false);
825 }
826 }
827
828 // From here on, we'll complete stuff in CompleteProcessing() so
829 // disable |completer| since we'll create a new one in that
830 // function.
831 completer.set_should_complete(false);
832
833 // If we're allowed to use p2p for downloading we do not pay
834 // attention to wall-clock-based waiting if the URL is indeed
835 // available via p2p. Therefore, check if the file is available via
836 // p2p before deferring...
837 if (params_->use_p2p_for_downloading()) {
838 LookupPayloadViaP2P(output_object);
839 } else {
840 CompleteProcessing();
841 }
842}
843
844void OmahaRequestAction::CompleteProcessing() {
845 ScopedActionCompleter completer(processor_, this);
846 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
847 PayloadStateInterface* payload_state = system_state_->payload_state();
848
849 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800850 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -0700851 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
852 completer.set_code(kErrorCodeOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -0800853 return;
854 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700855
Chris Sosa20f005c2013-09-05 13:53:08 -0700856 if (payload_state->ShouldBackoffDownload()) {
857 output_object.update_exists = false;
858 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
859 << "attempts";
860 completer.set_code(kErrorCodeOmahaUpdateDeferredForBackoff);
861 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700862 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700863 completer.set_code(kErrorCodeSuccess);
864}
865
866void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
867 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
868 if (!url.empty()) {
869 params_->set_p2p_url(url);
870 } else {
871 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
872 << "because no suitable peer could be found.";
873 params_->set_use_p2p_for_downloading(false);
874 }
875 CompleteProcessing();
876}
877
878void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -0700879 // If the device is in the middle of an update, the state variables
880 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
881 // tracks the offset and length of the operation currently in
882 // progress. The offset is based from the end of the manifest which
883 // is kPrefsManifestMetadataSize bytes long.
884 //
885 // To make forward progress and avoid deadlocks, we need to find a
886 // peer that has at least the entire operation we're currently
887 // working on. Otherwise we may end up in a situation where two
888 // devices bounce back and forth downloading from each other,
889 // neither making any forward progress until one of them decides to
890 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
891 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -0700892 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -0700893 int64_t manifest_metadata_size = 0;
894 int64_t next_data_offset = 0;
895 int64_t next_data_length = 0;
David Zeuthen8f191b22013-08-06 12:27:50 -0700896 if (system_state_ != NULL &&
David Zeuthen41996ad2013-09-24 15:43:24 -0700897 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
898 &manifest_metadata_size) &&
899 manifest_metadata_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -0700900 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -0700901 &next_data_offset) &&
902 next_data_offset != -1 &&
903 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
904 &next_data_length)) {
905 minimum_size = manifest_metadata_size + next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -0700906 }
907
908 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
909 if (system_state_->p2p_manager() != NULL) {
910 LOG(INFO) << "Checking if payload is available via p2p, file_id="
911 << file_id << " minimum_size=" << minimum_size;
912 system_state_->p2p_manager()->LookupUrlForFile(
913 file_id,
914 minimum_size,
915 TimeDelta::FromHours(kMaxP2PNetworkWaitTimeSeconds),
916 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
917 base::Unretained(this)));
918 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000919}
920
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700921bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -0700922 if (params_->interactive()) {
923 LOG(INFO) << "Not deferring download because update is interactive.";
924 return false;
925 }
926
David Zeuthen8f191b22013-08-06 12:27:50 -0700927 // If we're using p2p to download _and_ we have a p2p URL, we never
928 // defer the download. This is because the download will always
929 // happen from a peer on the LAN and we've been waiting in line for
930 // our turn.
931 if (params_->use_p2p_for_downloading() && !params_->p2p_url().empty()) {
932 LOG(INFO) << "Download not deferred because download "
933 << "will happen from a local peer (via p2p).";
934 return false;
935 }
936
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700937 // We should defer the downloads only if we've first satisfied the
938 // wall-clock-based-waiting period and then the update-check-based waiting
939 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700940 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -0700941 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
942 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700943 return false;
944 }
945
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700946 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700947 case kWallClockWaitNotSatisfied:
948 // We haven't even satisfied the first condition, passing the
949 // wall-clock-based waiting period, so we should defer the downloads
950 // until that happens.
951 LOG(INFO) << "wall-clock-based-wait not satisfied.";
952 return true;
953
954 case kWallClockWaitDoneButUpdateCheckWaitRequired:
955 LOG(INFO) << "wall-clock-based-wait satisfied and "
956 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700957 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700958
959 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
960 // Wall-clock-based waiting period is satisfied, and it's determined
961 // that we do not need the update-check-based wait. so no need to
962 // defer downloads.
963 LOG(INFO) << "wall-clock-based-wait satisfied and "
964 << "update-check-based-wait is not required.";
965 return false;
966
967 default:
968 // Returning false for this default case so we err on the
969 // side of downloading updates than deferring in case of any bugs.
970 NOTREACHED();
971 return false;
972 }
973}
974
975OmahaRequestAction::WallClockWaitResult
976OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700977 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700978 Time update_first_seen_at;
979 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700980
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800981 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
982 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
983 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700984 // Note: This timestamp could be that of ANY update we saw in the past
985 // (not necessarily this particular update we're considering to apply)
986 // but never got to apply because of some reason (e.g. stop AU policy,
987 // updates being pulled out from Omaha, changes in target version prefix,
988 // new update being rolled out, etc.). But for the purposes of scattering
989 // it doesn't matter which update the timestamp corresponds to. i.e.
990 // the clock starts ticking the first time we see an update and we're
991 // ready to apply when the random wait period is satisfied relative to
992 // that first seen timestamp.
993 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
994 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
995 << utils::ToString(update_first_seen_at);
996 } else {
997 // This seems like an unexpected error where the persisted value exists
998 // but it's not readable for some reason. Just skip scattering in this
999 // case to be safe.
1000 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1001 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1002 }
1003 } else {
1004 update_first_seen_at = Time::Now();
1005 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001006 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1007 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001008 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1009 << utils::ToString(update_first_seen_at);
1010 }
1011 else {
1012 // This seems like an unexpected error where the value cannot be
1013 // persisted for some reason. Just skip scattering in this
1014 // case to be safe.
1015 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1016 << utils::ToString(update_first_seen_at)
1017 << " cannot be persisted";
1018 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1019 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001020 }
1021
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001022 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001023 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001024 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001025
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001026 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001027 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001028 << ", Time Elapsed = "
1029 << utils::FormatSecs(elapsed_time.InSeconds())
1030 << ", MaxDaysToScatter = "
1031 << max_scatter_period.InDays();
1032
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001033 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001034 // The deadline is set for all rules which serve a delta update from a
1035 // previous FSI, which means this update will be applied mostly in OOBE
1036 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1037 // quickly.
1038 LOG(INFO) << "Not scattering as deadline flag is set";
1039 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1040 }
1041
1042 if (max_scatter_period.InDays() == 0) {
1043 // This means the Omaha rule creator decides that this rule
1044 // should not be scattered irrespective of the policy.
1045 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1046 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1047 }
1048
1049 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001050 // This means we've waited more than the upperbound wait in the rule
1051 // from the time we first saw a valid update available to us.
1052 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001053 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1054 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1055 }
1056
1057 // This means we are required to participate in scattering.
1058 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001059 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001060 if (remaining_wait_time.InSeconds() <= 0) {
1061 // Yes, it's our turn now.
1062 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1063
1064 // But we can't download until the update-check-count-based wait is also
1065 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001066 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001067 kWallClockWaitDoneButUpdateCheckWaitRequired :
1068 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1069 }
1070
1071 // Not our turn yet, so we have to wait until our turn to
1072 // help scatter the downloads across all clients of the enterprise.
1073 LOG(INFO) << "Update deferred for another "
1074 << utils::FormatSecs(remaining_wait_time.InSeconds())
1075 << " per policy.";
1076 return kWallClockWaitNotSatisfied;
1077}
1078
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001079bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001080 int64 update_check_count_value;
1081
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001082 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1083 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1084 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001085 // We are unable to read the update check count from file for some reason.
1086 // So let's proceed anyway so as to not stall the update.
1087 LOG(ERROR) << "Unable to read update check count. "
1088 << "Skipping update-check-count-based-wait.";
1089 return true;
1090 }
1091 } else {
1092 // This file does not exist. This means we haven't started our update
1093 // check count down yet, so this is the right time to start the count down.
1094 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001095 params_->min_update_checks_needed(),
1096 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001097
1098 LOG(INFO) << "Randomly picked update check count value = "
1099 << update_check_count_value;
1100
1101 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001102 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1103 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001104 // We weren't able to write the update check count file for some reason.
1105 // So let's proceed anyway so as to not stall the update.
1106 LOG(ERROR) << "Unable to write update check count. "
1107 << "Skipping update-check-count-based-wait.";
1108 return true;
1109 }
1110 }
1111
1112 if (update_check_count_value == 0) {
1113 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1114 return true;
1115 }
1116
1117 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001118 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001119 // We err on the side of skipping scattering logic instead of stalling
1120 // a machine from receiving any updates in case of any unexpected state.
1121 LOG(ERROR) << "Invalid value for update check count detected. "
1122 << "Skipping update-check-count-based-wait.";
1123 return true;
1124 }
1125
1126 // Legal value, we need to wait for more update checks to happen
1127 // until this becomes 0.
1128 LOG(INFO) << "Deferring Omaha updates for another "
1129 << update_check_count_value
1130 << " update checks per policy";
1131 return false;
1132}
1133
1134} // namespace chromeos_update_engine
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001135
1136