blob: 2c45c7dc205fcb1c4ac88dff2d087c3017c15afc [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
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070012#include <base/logging.h>
13#include <base/rand_util.h>
Darin Petkov85ced132010-09-01 10:20:56 -070014#include <base/string_number_conversions.h>
15#include <base/string_util.h>
Mike Frysinger8155d082012-04-06 15:23:18 -040016#include <base/stringprintf.h>
Darin Petkov85ced132010-09-01 10:20:56 -070017#include <base/time.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000018#include <libxml/xpath.h>
19#include <libxml/xpathInternals.h>
20
21#include "update_engine/action_pipe.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070022#include "update_engine/constants.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070023#include "update_engine/omaha_request_params.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080024#include "update_engine/payload_state_interface.h"
Darin Petkov1cbd78f2010-07-29 12:38:34 -070025#include "update_engine/prefs_interface.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000026#include "update_engine/utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000027
Darin Petkov1cbd78f2010-07-29 12:38:34 -070028using base::Time;
29using base::TimeDelta;
rspangler@google.com49fdf182009-10-10 00:57:34 +000030using std::string;
31
32namespace chromeos_update_engine {
33
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080034// List of custom pair tags that we interpret in the Omaha Response:
35static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080036static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070037static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080038// Deprecated: "IsDelta"
39static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080040static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
41static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
42// Deprecated: "ManifestSignatureRsa"
43// Deprecated: "ManifestSize"
44static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
45static const char* kTagMetadataSize = "MetadataSize";
46static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070047// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080048static const char* kTagPrompt = "Prompt";
49static const char* kTagSha256 = "sha256";
50
rspangler@google.com49fdf182009-10-10 00:57:34 +000051namespace {
52
53const string kGupdateVersion("ChromeOSUpdateEngine-0.1.0.0");
54
55// This is handy for passing strings into libxml2
56#define ConstXMLStr(x) (reinterpret_cast<const xmlChar*>(x))
57
58// These are for scoped_ptr_malloc, which is like scoped_ptr, but allows
59// a custom free() function to be specified.
60class ScopedPtrXmlDocFree {
61 public:
62 inline void operator()(void* x) const {
63 xmlFreeDoc(reinterpret_cast<xmlDoc*>(x));
64 }
65};
66class ScopedPtrXmlFree {
67 public:
68 inline void operator()(void* x) const {
69 xmlFree(x);
70 }
71};
72class ScopedPtrXmlXPathObjectFree {
73 public:
74 inline void operator()(void* x) const {
75 xmlXPathFreeObject(reinterpret_cast<xmlXPathObject*>(x));
76 }
77};
78class ScopedPtrXmlXPathContextFree {
79 public:
80 inline void operator()(void* x) const {
81 xmlXPathFreeContext(reinterpret_cast<xmlXPathContext*>(x));
82 }
83};
84
Darin Petkov1cbd78f2010-07-29 12:38:34 -070085// Returns true if |ping_days| has a value that needs to be sent,
86// false otherwise.
87bool ShouldPing(int ping_days) {
88 return ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged;
89}
90
91// Returns an XML ping element attribute assignment with attribute
92// |name| and value |ping_days| if |ping_days| has a value that needs
93// to be sent, or an empty string otherwise.
94string GetPingAttribute(const string& name, int ping_days) {
95 if (ShouldPing(ping_days)) {
96 return StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
97 }
98 return "";
99}
100
101// Returns an XML ping element if any of the elapsed days need to be
102// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700103string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700104 string ping_active = GetPingAttribute("a", ping_active_days);
105 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
106 if (!ping_active.empty() || !ping_roll_call.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700107 return StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700108 ping_active.c_str(),
109 ping_roll_call.c_str());
110 }
111 return "";
112}
113
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700114// Returns an XML that goes into the body of the <app> element of the Omaha
115// request based on the given parameters.
116string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700117 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700118 bool ping_only,
119 int ping_active_days,
120 int ping_roll_call_days,
121 PrefsInterface* prefs) {
122 string app_body;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700123 if (event == NULL) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700124 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700125 if (!ping_only) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700126 // not passing update_disabled to Omaha because we want to
127 // get the update and report with UpdateDeferred result so that
128 // borgmon charts show up updates that are deferred. This is also
129 // the expected behavior when we move to Omaha v3.0 protocol, so it'll
130 // be consistent.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700131 app_body += StringPrintf(
132 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700133 "></updatecheck>\n",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700134 XmlEncode(params->target_version_prefix()).c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700135
Darin Petkov265f2902011-05-09 15:17:40 -0700136 // If this is the first update check after a reboot following a previous
137 // update, generate an event containing the previous version number. If
138 // the previous version preference file doesn't exist the event is still
139 // generated with a previous version of 0.0.0.0 -- this is relevant for
140 // older clients or new installs. The previous version event is not sent
141 // for ping-only requests because they come before the client has
142 // rebooted.
143 string prev_version;
144 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
145 prev_version = "0.0.0.0";
146 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700147
148 app_body += StringPrintf(
149 " <event eventtype=\"%d\" eventresult=\"%d\" "
150 "previousversion=\"%s\"></event>\n",
151 OmahaEvent::kTypeUpdateComplete,
152 OmahaEvent::kResultSuccessReboot,
153 XmlEncode(prev_version).c_str());
154 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
155 << "Unable to reset the previous version.";
Darin Petkov95508da2011-01-05 12:42:29 -0800156 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700157 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800158 // The error code is an optional attribute so append it only if the result
159 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700160 string error_code;
161 if (event->result != OmahaEvent::kResultSuccess) {
Darin Petkov18c7bce2011-06-16 14:07:00 -0700162 error_code = StringPrintf(" errorcode=\"%d\"", event->error_code);
Darin Petkove17f86b2010-07-20 09:12:01 -0700163 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700164 app_body = StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700165 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700166 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700167 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700168
169 return app_body;
170}
171
172// Returns an XML that corresponds to the entire <app> node of the Omaha
173// request based on the given parameters.
174string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700175 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700176 bool ping_only,
177 int ping_active_days,
178 int ping_roll_call_days,
179 SystemState* system_state) {
180 string app_body = GetAppBody(event, params, ping_only, ping_active_days,
181 ping_roll_call_days, system_state->prefs());
182 string app_versions;
183
184 // If we are upgrading to a more stable channel and we are allowed to do
185 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
186 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700187 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700188 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
189 << "on downgrading to the version in the more stable channel";
190 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700191 XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700192 } else {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700193 app_versions = "version=\"" + XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700194 }
195
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700196 string download_channel = params->download_channel();
197 string app_channels = "track=\"" + XmlEncode(download_channel) + "\" ";
198 if (params->current_channel() != download_channel)
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700199 app_channels +=
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700200 "from_track=\"" + XmlEncode(params->current_channel()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700201
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700202 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700203
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700204 string app_xml =
Jay Srinivasandb0acdf2013-04-02 14:47:45 -0700205 " <app appid=\"" + XmlEncode(params->GetAppId()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700206 app_versions +
207 app_channels +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700208 "lang=\"" + XmlEncode(params->app_lang()) + "\" " +
209 "board=\"" + XmlEncode(params->os_board()) + "\" " +
210 "hardware_class=\"" + XmlEncode(params->hwid()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700211 "delta_okay=\"" + delta_okay_str + "\" "
Chris Sosac1972482013-04-30 22:31:10 -0700212 "fw_version=\"" + XmlEncode(params->fw_version()) + "\" " +
213 "ec_version=\"" + XmlEncode(params->ec_version()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700214 ">\n" +
215 app_body +
216 " </app>\n";
217
218 return app_xml;
219}
220
221// Returns an XML that corresponds to the entire <os> node of the Omaha
222// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700223string GetOsXml(OmahaRequestParams* params) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700224 string os_xml =
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700225 " <os version=\"" + XmlEncode(params->os_version()) + "\" " +
226 "platform=\"" + XmlEncode(params->os_platform()) + "\" " +
227 "sp=\"" + XmlEncode(params->os_sp()) + "\">"
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700228 "</os>\n";
229 return os_xml;
230}
231
232// Returns an XML that corresponds to the entire Omaha request based on the
233// given parameters.
234string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700235 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700236 bool ping_only,
237 int ping_active_days,
238 int ping_roll_call_days,
239 SystemState* system_state) {
240 string os_xml = GetOsXml(params);
241 string app_xml = GetAppXml(event, params, ping_only, ping_active_days,
242 ping_roll_call_days, system_state);
243
244 string install_source = StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700245 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700246
247 string request_xml =
248 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700249 "<request protocol=\"3.0\" "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700250 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
251 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" " +
252 install_source +
253 "ismachine=\"1\">\n" +
254 os_xml +
255 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700256 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700257
258 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000259}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700260
rspangler@google.com49fdf182009-10-10 00:57:34 +0000261} // namespace {}
262
263// Encodes XML entities in a given string with libxml2. input must be
264// UTF-8 formatted. Output will be UTF-8 formatted.
265string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700266 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
267 // // cpu, considering creating one and caching it.
268 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
269 // xmlNewDoc(ConstXMLStr("1.0")));
270 // if (!xml_doc.get()) {
271 // LOG(ERROR) << "Unable to create xmlDoc";
272 // return "";
273 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000274 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
275 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
276 return string(reinterpret_cast<const char *>(str.get()));
277}
278
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800279OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700280 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700281 HttpFetcher* http_fetcher,
282 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800283 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700284 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700285 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700286 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700287 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700288 ping_roll_call_days_(0) {
289 params_ = system_state->request_params();
290}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000291
Darin Petkov6a5b3222010-07-13 14:55:28 -0700292OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000293
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700294// Calculates the value to use for the ping days parameter.
295int OmahaRequestAction::CalculatePingDays(const string& key) {
296 int days = kNeverPinged;
297 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800298 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700299 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
300 if (days < 0) {
301 // If |days| is negative, then the system clock must have jumped
302 // back in time since the ping was sent. Mark the value so that
303 // it doesn't get sent to the server but we still update the
304 // last ping daystart preference. This way the next ping time
305 // will be correct, hopefully.
306 days = kPingTimeJump;
307 LOG(WARNING) <<
308 "System clock jumped back in time. Resetting ping daystarts.";
309 }
310 }
311 return days;
312}
313
314void OmahaRequestAction::InitPingDays() {
315 // We send pings only along with update checks, not with events.
316 if (IsEvent()) {
317 return;
318 }
319 // TODO(petkov): Figure a way to distinguish active use pings
320 // vs. roll call pings. Currently, the two pings are identical. A
321 // fix needs to change this code as well as UpdateLastPingDays.
322 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
323 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
324}
325
Darin Petkov6a5b3222010-07-13 14:55:28 -0700326void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000327 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700328 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700329 if (ping_only_ &&
330 !ShouldPing(ping_active_days_) &&
331 !ShouldPing(ping_roll_call_days_)) {
David Zeuthena99981f2013-04-29 13:42:47 -0700332 processor_->ActionComplete(this, kErrorCodeSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700333 return;
334 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700335 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700336 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700337 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700338 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800339 ping_roll_call_days_,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700340 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700341
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800342 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
343 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700344 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700345 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700346 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000347}
348
Darin Petkov6a5b3222010-07-13 14:55:28 -0700349void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000350 http_fetcher_->TerminateTransfer();
351}
352
353// We just store the response in the buffer. Once we've received all bytes,
354// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700355void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
356 const char* bytes,
357 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000358 response_buffer_.reserve(response_buffer_.size() + length);
359 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
360}
361
362namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000363// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
364// on the returned object.
365// This code is roughly based on the libxml tutorial at:
366// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700367xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000368 xmlXPathObject* result = NULL;
369
370 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
371 xmlXPathNewContext(doc));
372 if (!context.get()) {
373 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
374 return NULL;
375 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000376
377 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000378 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700379 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000380 return NULL;
381 }
382 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700383 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000384 xmlXPathFreeObject(result);
385 return NULL;
386 }
387 return result;
388}
389
390// Returns the string value of a named attribute on a node, or empty string
391// if no such node exists. If the attribute exists and has a value of
392// empty string, there's no way to distinguish that from the attribute
393// not existing.
394string XmlGetProperty(xmlNode* node, const char* name) {
395 if (!xmlHasProp(node, ConstXMLStr(name)))
396 return "";
397 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
398 xmlGetProp(node, ConstXMLStr(name)));
399 string ret(reinterpret_cast<const char *>(str.get()));
400 return ret;
401}
402
403// Parses a 64 bit base-10 int from a string and returns it. Returns 0
404// on error. If the string contains "0", that's indistinguishable from
405// error.
406off_t ParseInt(const string& str) {
407 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700408 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000409 if (rc < 1) {
410 // failure
411 return 0;
412 }
413 return ret;
414}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700415
416// Update the last ping day preferences based on the server daystart
417// response. Returns true on success, false otherwise.
418bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700419 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700420
421 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700422 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700423 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
424 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
425 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
426 xmlNode* daystart_node = nodeset->nodeTab[0];
427 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
428 ConstXMLStr("elapsed_seconds")));
429
430 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700431 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
432 "elapsed_seconds"),
433 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700434 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
435
436 // Remember the local time that matches the server's last midnight
437 // time.
438 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
439 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
440 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
441 return true;
442}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000443} // namespace {}
444
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700445bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
446 OmahaResponse* output_object,
447 ScopedActionCompleter* completer) {
448 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
449
450 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
451 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
452 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700453 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700454 return false;
455 }
456
457 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
458 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
459 CHECK_GE(nodeset->nodeNr, 1);
460 xmlNode* update_check_node = nodeset->nodeTab[0];
461
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800462 // chromium-os:37289: The PollInterval is not supported by Omaha server
463 // currently. But still keeping this existing code in case we ever decide to
464 // slow down the request rate from the server-side. Note that the
465 // PollInterval is not persisted, so it has to be sent by the server on every
466 // response to guarantee that the UpdateCheckScheduler uses this value
467 // (otherwise, if the device got rebooted after the last server-indicated
468 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
469 // value for the scattering logic is based on the assumption that we perform
470 // an update check every hour so that the max value of 8 will roughly be
471 // equivalent to one work day. If we decide to use PollInterval permanently,
472 // we should update the max_update_checks_allowed to take PollInterval into
473 // account. Note: The parsing for PollInterval happens even before parsing
474 // of the status because we may want to specify the PollInterval even when
475 // there's no update.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700476 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
477 &output_object->poll_interval);
478
479 if (!ParseStatus(update_check_node, output_object, completer))
480 return false;
481
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800482 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
483 // appends the package name to the URLs populated in this method.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700484 if (!ParseUrls(doc, output_object, completer))
485 return false;
486
487 if (!ParsePackage(doc, output_object, completer))
488 return false;
489
490 if (!ParseParams(doc, output_object, completer))
491 return false;
492
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800493 output_object->update_exists = true;
494 SetOutputObject(*output_object);
David Zeuthena99981f2013-04-29 13:42:47 -0700495 completer->set_code(kErrorCodeSuccess);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800496
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700497 return true;
498}
499
500bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
501 OmahaResponse* output_object,
502 ScopedActionCompleter* completer) {
503 // Get status.
504 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
505 LOG(ERROR) << "Omaha Response missing status";
David Zeuthena99981f2013-04-29 13:42:47 -0700506 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700507 return false;
508 }
509
510 const string status(XmlGetProperty(update_check_node, "status"));
511 if (status == "noupdate") {
512 LOG(INFO) << "No update.";
513 output_object->update_exists = false;
514 SetOutputObject(*output_object);
David Zeuthena99981f2013-04-29 13:42:47 -0700515 completer->set_code(kErrorCodeSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700516 return false;
517 }
518
519 if (status != "ok") {
520 LOG(ERROR) << "Unknown Omaha response status: " << status;
David Zeuthena99981f2013-04-29 13:42:47 -0700521 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700522 return false;
523 }
524
525 return true;
526}
527
528bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
529 OmahaResponse* output_object,
530 ScopedActionCompleter* completer) {
531 // Get the update URL.
532 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
533
534 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
535 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
536 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700537 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700538 return false;
539 }
540
541 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
542 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
543 CHECK_GE(nodeset->nodeNr, 1);
544
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800545 LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)";
546 output_object->payload_urls.clear();
547 for (int i = 0; i < nodeset->nodeNr; i++) {
548 xmlNode* url_node = nodeset->nodeTab[i];
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800549 const string codebase(XmlGetProperty(url_node, "codebase"));
550 if (codebase.empty()) {
551 LOG(ERROR) << "Omaha Response URL has empty codebase";
David Zeuthena99981f2013-04-29 13:42:47 -0700552 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800553 return false;
554 }
555 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700556 }
557
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700558 return true;
559}
560
561bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
562 OmahaResponse* output_object,
563 ScopedActionCompleter* completer) {
564 // Get the package node.
565 static const char* kPackageNodeXPath(
566 "/response/app/updatecheck/manifest/packages/package");
567
568 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
569 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
570 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700571 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700572 return false;
573 }
574
575 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
576 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
577 CHECK_GE(nodeset->nodeNr, 1);
578
579 // We only care about the first package.
580 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
581 xmlNode* package_node = nodeset->nodeTab[0];
582
583 // Get package properties one by one.
584
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800585 // Parse the payload name to be appended to the base Url value.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700586 const string package_name(XmlGetProperty(package_node, "name"));
587 LOG(INFO) << "Omaha Response package name = " << package_name;
588 if (package_name.empty()) {
589 LOG(ERROR) << "Omaha Response has empty package name";
David Zeuthena99981f2013-04-29 13:42:47 -0700590 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700591 return false;
592 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800593
594 // Append the package name to each URL in our list so that we don't
595 // propagate the urlBase vs packageName distinctions beyond this point.
596 // From now on, we only need to use payload_urls.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700597 for (size_t i = 0; i < output_object->payload_urls.size(); i++)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800598 output_object->payload_urls[i] += package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700599
600 // Parse the payload size.
601 off_t size = ParseInt(XmlGetProperty(package_node, "size"));
602 if (size <= 0) {
603 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
David Zeuthena99981f2013-04-29 13:42:47 -0700604 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700605 return false;
606 }
607 output_object->size = size;
608
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800609 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700610
611 return true;
612}
613
614bool OmahaRequestAction::ParseParams(xmlDoc* doc,
615 OmahaResponse* output_object,
616 ScopedActionCompleter* completer) {
Chris Sosa3b748432013-06-20 16:42:59 -0700617 // XPath location for response elements we care about.
618 static const char* kManifestNodeXPath("/response/app/updatecheck/manifest");\
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700619 static const char* kActionNodeXPath(
Chris Sosa3b748432013-06-20 16:42:59 -0700620 "/response/app/updatecheck/manifest/actions/action");
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700621
Chris Sosa3b748432013-06-20 16:42:59 -0700622 // Get the manifest node where version is present.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700623 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Chris Sosa3b748432013-06-20 16:42:59 -0700624 xpath_manifest_nodeset(GetNodeSet(doc, ConstXMLStr(kManifestNodeXPath)));
625 if (!xpath_manifest_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700626 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700627 return false;
628 }
629
Chris Sosa3b748432013-06-20 16:42:59 -0700630 // Grab the only matching node there should be from the xpath.
631 xmlNodeSet* nodeset = xpath_manifest_nodeset->nodesetval;
632 CHECK(nodeset) << "XPath missing " << kManifestNodeXPath;
633 CHECK_GE(nodeset->nodeNr, 1);
634 xmlNode* manifest_node = nodeset->nodeTab[0];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700635
Chris Sosa3b748432013-06-20 16:42:59 -0700636 // Set the version.
637 output_object->version = XmlGetProperty(manifest_node, kTagVersion);
638 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700639 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Chris Sosa3b748432013-06-20 16:42:59 -0700640 completer->set_code(kErrorCodeOmahaResponseInvalid);
641 return false;
642 }
643
644 LOG(INFO) << "Received omaha response to update to version "
645 << output_object->version;
646
647 // Grab the action nodes.
648 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
649 xpath_action_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
650 if (!xpath_action_nodeset.get()) {
651 completer->set_code(kErrorCodeOmahaResponseInvalid);
652 return false;
653 }
654
655 // We only care about the action that has event "postinstall", because this is
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700656 // where Omaha puts all the generic name/value pairs in the rule.
Chris Sosa3b748432013-06-20 16:42:59 -0700657 nodeset = xpath_action_nodeset->nodesetval;
658 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700659 LOG(INFO) << "Found " << nodeset->nodeNr
660 << " action(s). Processing the postinstall action.";
661
662 // pie_action_node holds the action node corresponding to the
663 // postinstall event action, if present.
664 xmlNode* pie_action_node = NULL;
665 for (int i = 0; i < nodeset->nodeNr; i++) {
666 xmlNode* action_node = nodeset->nodeTab[i];
667 if (XmlGetProperty(action_node, "event") == "postinstall") {
668 pie_action_node = action_node;
669 break;
670 }
671 }
672
673 if (!pie_action_node) {
674 LOG(ERROR) << "Omaha Response has no postinstall event action";
David Zeuthena99981f2013-04-29 13:42:47 -0700675 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700676 return false;
677 }
678
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800679 output_object->hash = XmlGetProperty(pie_action_node, kTagSha256);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700680 if (output_object->hash.empty()) {
681 LOG(ERROR) << "Omaha Response has empty sha256 value";
David Zeuthena99981f2013-04-29 13:42:47 -0700682 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700683 return false;
684 }
685
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800686 // Get the optional properties one by one.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800687 output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700688 output_object->metadata_size =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800689 ParseInt(XmlGetProperty(pie_action_node, kTagMetadataSize));
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700690 output_object->metadata_signature =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800691 XmlGetProperty(pie_action_node, kTagMetadataSignatureRsa);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800692 output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true";
693 output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700694 output_object->max_days_to_scatter =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800695 ParseInt(XmlGetProperty(pie_action_node, kTagMaxDaysToScatter));
696
697 string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl);
Jay Srinivasan08262882012-12-28 19:29:43 -0800698 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800699 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700700
Jay Srinivasan08262882012-12-28 19:29:43 -0800701 output_object->is_delta_payload =
702 XmlGetProperty(pie_action_node, kTagIsDeltaPayload) == "true";
703
704 output_object->disable_payload_backoff =
705 XmlGetProperty(pie_action_node, kTagDisablePayloadBackoff) == "true";
706
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700707 return true;
708}
709
rspangler@google.com49fdf182009-10-10 00:57:34 +0000710// If the transfer was successful, this uses libxml2 to parse the response
711// and fill in the appropriate fields of the output object. Also, notifies
712// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700713void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
714 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000715 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800716 string current_response(response_buffer_.begin(), response_buffer_.end());
717 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700718
719 // Events are best effort transactions -- assume they always succeed.
720 if (IsEvent()) {
721 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800722 if (event_->result == OmahaEvent::kResultError && successful &&
723 utils::IsOfficialBuild()) {
724 LOG(INFO) << "Signalling Crash Reporter.";
725 utils::ScheduleCrashReporterUpload();
726 }
David Zeuthena99981f2013-04-29 13:42:47 -0700727 completer.set_code(kErrorCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700728 return;
729 }
730
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700731 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700732 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700733 int code = GetHTTPResponseCode();
734 // Makes sure we send sane error values.
735 if (code < 0 || code >= 1000) {
736 code = 999;
737 }
David Zeuthena99981f2013-04-29 13:42:47 -0700738 completer.set_code(static_cast<ErrorCode>(
739 kErrorCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000740 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700741 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000742
743 // parse our response and fill the fields in the output object
744 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
745 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
746 if (!doc.get()) {
747 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700748 completer.set_code(response_buffer_.empty() ?
David Zeuthena99981f2013-04-29 13:42:47 -0700749 kErrorCodeOmahaRequestEmptyResponseError :
750 kErrorCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000751 return;
752 }
753
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700754 // If a ping was sent, update the last ping day preferences based on
755 // the server daystart response.
756 if (ShouldPing(ping_active_days_) ||
757 ShouldPing(ping_roll_call_days_) ||
758 ping_active_days_ == kPingTimeJump ||
759 ping_roll_call_days_ == kPingTimeJump) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800760 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700761 << "Failed to update the last ping day preferences!";
762 }
763
Thieu Le116fda32011-04-19 11:01:54 -0700764 if (!HasOutputPipe()) {
765 // Just set success to whether or not the http transfer succeeded,
766 // which must be true at this point in the code.
David Zeuthena99981f2013-04-29 13:42:47 -0700767 completer.set_code(kErrorCodeSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700768 return;
769 }
770
Darin Petkov6a5b3222010-07-13 14:55:28 -0700771 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700772 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000773 return;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000774
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700775 if (params_->update_disabled()) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700776 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700777 output_object.update_exists = false;
David Zeuthena99981f2013-04-29 13:42:47 -0700778 completer.set_code(kErrorCodeOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700779 // Note: We could technically delete the UpdateFirstSeenAt state here.
780 // If we do, it'll mean a device has to restart the UpdateFirstSeenAt
781 // and thus help scattering take effect when the AU is turned on again.
782 // On the other hand, it also increases the chance of update starvation if
783 // an admin turns AU on/off more frequently. We choose to err on the side
784 // of preventing starvation at the cost of not applying scattering in
785 // those cases.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700786 return;
787 }
788
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700789 if (ShouldDeferDownload(&output_object)) {
790 output_object.update_exists = false;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700791 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
David Zeuthena99981f2013-04-29 13:42:47 -0700792 completer.set_code(kErrorCodeOmahaUpdateDeferredPerPolicy);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700793 return;
794 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800795
796 // Update the payload state with the current response. The payload state
797 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800798 // from what's stored already. We are updating the payload state as late
799 // as possible in this method so that if a new release gets pushed and then
800 // got pulled back due to some issues, we don't want to clear our internal
801 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800802 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800803 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800804
805 if (payload_state->ShouldBackoffDownload()) {
806 output_object.update_exists = false;
807 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
808 "attempts";
David Zeuthena99981f2013-04-29 13:42:47 -0700809 completer.set_code(kErrorCodeOmahaUpdateDeferredForBackoff);
Jay Srinivasan08262882012-12-28 19:29:43 -0800810 return;
811 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000812}
813
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700814bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700815 // We should defer the downloads only if we've first satisfied the
816 // wall-clock-based-waiting period and then the update-check-based waiting
817 // period, if required.
818
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700819 if (!params_->wall_clock_based_wait_enabled()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700820 // Wall-clock-based waiting period is not enabled, so no scattering needed.
821 return false;
822 }
823
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700824 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700825 case kWallClockWaitNotSatisfied:
826 // We haven't even satisfied the first condition, passing the
827 // wall-clock-based waiting period, so we should defer the downloads
828 // until that happens.
829 LOG(INFO) << "wall-clock-based-wait not satisfied.";
830 return true;
831
832 case kWallClockWaitDoneButUpdateCheckWaitRequired:
833 LOG(INFO) << "wall-clock-based-wait satisfied and "
834 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700835 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700836
837 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
838 // Wall-clock-based waiting period is satisfied, and it's determined
839 // that we do not need the update-check-based wait. so no need to
840 // defer downloads.
841 LOG(INFO) << "wall-clock-based-wait satisfied and "
842 << "update-check-based-wait is not required.";
843 return false;
844
845 default:
846 // Returning false for this default case so we err on the
847 // side of downloading updates than deferring in case of any bugs.
848 NOTREACHED();
849 return false;
850 }
851}
852
853OmahaRequestAction::WallClockWaitResult
854OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700855 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700856 Time update_first_seen_at;
857 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700858
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800859 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
860 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
861 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700862 // Note: This timestamp could be that of ANY update we saw in the past
863 // (not necessarily this particular update we're considering to apply)
864 // but never got to apply because of some reason (e.g. stop AU policy,
865 // updates being pulled out from Omaha, changes in target version prefix,
866 // new update being rolled out, etc.). But for the purposes of scattering
867 // it doesn't matter which update the timestamp corresponds to. i.e.
868 // the clock starts ticking the first time we see an update and we're
869 // ready to apply when the random wait period is satisfied relative to
870 // that first seen timestamp.
871 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
872 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
873 << utils::ToString(update_first_seen_at);
874 } else {
875 // This seems like an unexpected error where the persisted value exists
876 // but it's not readable for some reason. Just skip scattering in this
877 // case to be safe.
878 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
879 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
880 }
881 } else {
882 update_first_seen_at = Time::Now();
883 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800884 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
885 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700886 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
887 << utils::ToString(update_first_seen_at);
888 }
889 else {
890 // This seems like an unexpected error where the value cannot be
891 // persisted for some reason. Just skip scattering in this
892 // case to be safe.
893 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
894 << utils::ToString(update_first_seen_at)
895 << " cannot be persisted";
896 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
897 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700898 }
899
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700900 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700901 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700902 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700903
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700904 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700905 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700906 << ", Time Elapsed = "
907 << utils::FormatSecs(elapsed_time.InSeconds())
908 << ", MaxDaysToScatter = "
909 << max_scatter_period.InDays();
910
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700911 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700912 // The deadline is set for all rules which serve a delta update from a
913 // previous FSI, which means this update will be applied mostly in OOBE
914 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
915 // quickly.
916 LOG(INFO) << "Not scattering as deadline flag is set";
917 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
918 }
919
920 if (max_scatter_period.InDays() == 0) {
921 // This means the Omaha rule creator decides that this rule
922 // should not be scattered irrespective of the policy.
923 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
924 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
925 }
926
927 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700928 // This means we've waited more than the upperbound wait in the rule
929 // from the time we first saw a valid update available to us.
930 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700931 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
932 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
933 }
934
935 // This means we are required to participate in scattering.
936 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700937 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700938 if (remaining_wait_time.InSeconds() <= 0) {
939 // Yes, it's our turn now.
940 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
941
942 // But we can't download until the update-check-count-based wait is also
943 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700944 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700945 kWallClockWaitDoneButUpdateCheckWaitRequired :
946 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
947 }
948
949 // Not our turn yet, so we have to wait until our turn to
950 // help scatter the downloads across all clients of the enterprise.
951 LOG(INFO) << "Update deferred for another "
952 << utils::FormatSecs(remaining_wait_time.InSeconds())
953 << " per policy.";
954 return kWallClockWaitNotSatisfied;
955}
956
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700957bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700958 int64 update_check_count_value;
959
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800960 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
961 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
962 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700963 // We are unable to read the update check count from file for some reason.
964 // So let's proceed anyway so as to not stall the update.
965 LOG(ERROR) << "Unable to read update check count. "
966 << "Skipping update-check-count-based-wait.";
967 return true;
968 }
969 } else {
970 // This file does not exist. This means we haven't started our update
971 // check count down yet, so this is the right time to start the count down.
972 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700973 params_->min_update_checks_needed(),
974 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700975
976 LOG(INFO) << "Randomly picked update check count value = "
977 << update_check_count_value;
978
979 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800980 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
981 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700982 // We weren't able to write the update check count file for some reason.
983 // So let's proceed anyway so as to not stall the update.
984 LOG(ERROR) << "Unable to write update check count. "
985 << "Skipping update-check-count-based-wait.";
986 return true;
987 }
988 }
989
990 if (update_check_count_value == 0) {
991 LOG(INFO) << "Successfully passed the update-check-based-wait.";
992 return true;
993 }
994
995 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700996 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700997 // We err on the side of skipping scattering logic instead of stalling
998 // a machine from receiving any updates in case of any unexpected state.
999 LOG(ERROR) << "Invalid value for update check count detected. "
1000 << "Skipping update-check-count-based-wait.";
1001 return true;
1002 }
1003
1004 // Legal value, we need to wait for more update checks to happen
1005 // until this becomes 0.
1006 LOG(INFO) << "Deferring Omaha updates for another "
1007 << update_check_count_value
1008 << " update checks per policy";
1009 return false;
1010}
1011
1012} // namespace chromeos_update_engine
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001013
1014