blob: ad1f95e98e0e3fddeba600b9f5efffa71c9cc44c [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"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070022#include "update_engine/omaha_request_params.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080023#include "update_engine/payload_state_interface.h"
Darin Petkov1cbd78f2010-07-29 12:38:34 -070024#include "update_engine/prefs_interface.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000025#include "update_engine/utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000026
Darin Petkov1cbd78f2010-07-29 12:38:34 -070027using base::Time;
28using base::TimeDelta;
rspangler@google.com49fdf182009-10-10 00:57:34 +000029using std::string;
30
31namespace chromeos_update_engine {
32
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080033// List of custom pair tags that we interpret in the Omaha Response:
34static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080035static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080036static const char* kTagDisplayVersion = "DisplayVersion";
Jay Srinivasand671e972013-01-11 17:17:19 -080037// Deprecated: "IsDelta"
38static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080039static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
40static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
41// Deprecated: "ManifestSignatureRsa"
42// Deprecated: "ManifestSize"
43static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
44static const char* kTagMetadataSize = "MetadataSize";
45static const char* kTagMoreInfo = "MoreInfo";
46static const char* kTagNeedsAdmin = "needsadmin";
47static const char* kTagPrompt = "Prompt";
48static const char* kTagSha256 = "sha256";
49
rspangler@google.com49fdf182009-10-10 00:57:34 +000050namespace {
51
52const string kGupdateVersion("ChromeOSUpdateEngine-0.1.0.0");
53
54// This is handy for passing strings into libxml2
55#define ConstXMLStr(x) (reinterpret_cast<const xmlChar*>(x))
56
57// These are for scoped_ptr_malloc, which is like scoped_ptr, but allows
58// a custom free() function to be specified.
59class ScopedPtrXmlDocFree {
60 public:
61 inline void operator()(void* x) const {
62 xmlFreeDoc(reinterpret_cast<xmlDoc*>(x));
63 }
64};
65class ScopedPtrXmlFree {
66 public:
67 inline void operator()(void* x) const {
68 xmlFree(x);
69 }
70};
71class ScopedPtrXmlXPathObjectFree {
72 public:
73 inline void operator()(void* x) const {
74 xmlXPathFreeObject(reinterpret_cast<xmlXPathObject*>(x));
75 }
76};
77class ScopedPtrXmlXPathContextFree {
78 public:
79 inline void operator()(void* x) const {
80 xmlXPathFreeContext(reinterpret_cast<xmlXPathContext*>(x));
81 }
82};
83
Darin Petkov1cbd78f2010-07-29 12:38:34 -070084// Returns true if |ping_days| has a value that needs to be sent,
85// false otherwise.
86bool ShouldPing(int ping_days) {
87 return ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged;
88}
89
90// Returns an XML ping element attribute assignment with attribute
91// |name| and value |ping_days| if |ping_days| has a value that needs
92// to be sent, or an empty string otherwise.
93string GetPingAttribute(const string& name, int ping_days) {
94 if (ShouldPing(ping_days)) {
95 return StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
96 }
97 return "";
98}
99
100// Returns an XML ping element if any of the elapsed days need to be
101// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700102string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700103 string ping_active = GetPingAttribute("a", ping_active_days);
104 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
105 if (!ping_active.empty() || !ping_roll_call.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700106 return StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700107 ping_active.c_str(),
108 ping_roll_call.c_str());
109 }
110 return "";
111}
112
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700113// Returns an XML that goes into the body of the <app> element of the Omaha
114// request based on the given parameters.
115string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700116 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700117 bool ping_only,
118 int ping_active_days,
119 int ping_roll_call_days,
120 PrefsInterface* prefs) {
121 string app_body;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700122 if (event == NULL) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700123 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700124 if (!ping_only) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700125 // not passing update_disabled to Omaha because we want to
126 // get the update and report with UpdateDeferred result so that
127 // borgmon charts show up updates that are deferred. This is also
128 // the expected behavior when we move to Omaha v3.0 protocol, so it'll
129 // be consistent.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700130 app_body += StringPrintf(
131 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700132 "></updatecheck>\n",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700133 XmlEncode(params->target_version_prefix()).c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700134
Darin Petkov265f2902011-05-09 15:17:40 -0700135 // If this is the first update check after a reboot following a previous
136 // update, generate an event containing the previous version number. If
137 // the previous version preference file doesn't exist the event is still
138 // generated with a previous version of 0.0.0.0 -- this is relevant for
139 // older clients or new installs. The previous version event is not sent
140 // for ping-only requests because they come before the client has
141 // rebooted.
142 string prev_version;
143 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
144 prev_version = "0.0.0.0";
145 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700146
147 app_body += StringPrintf(
148 " <event eventtype=\"%d\" eventresult=\"%d\" "
149 "previousversion=\"%s\"></event>\n",
150 OmahaEvent::kTypeUpdateComplete,
151 OmahaEvent::kResultSuccessReboot,
152 XmlEncode(prev_version).c_str());
153 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
154 << "Unable to reset the previous version.";
Darin Petkov95508da2011-01-05 12:42:29 -0800155 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700156 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800157 // The error code is an optional attribute so append it only if the result
158 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700159 string error_code;
160 if (event->result != OmahaEvent::kResultSuccess) {
Darin Petkov18c7bce2011-06-16 14:07:00 -0700161 error_code = StringPrintf(" errorcode=\"%d\"", event->error_code);
Darin Petkove17f86b2010-07-20 09:12:01 -0700162 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700163 app_body = StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700164 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700165 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700166 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700167
168 return app_body;
169}
170
171// Returns an XML that corresponds to the entire <app> node of the Omaha
172// request based on the given parameters.
173string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700174 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700175 bool ping_only,
176 int ping_active_days,
177 int ping_roll_call_days,
178 SystemState* system_state) {
179 string app_body = GetAppBody(event, params, ping_only, ping_active_days,
180 ping_roll_call_days, system_state->prefs());
181 string app_versions;
182
183 // If we are upgrading to a more stable channel and we are allowed to do
184 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
185 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700186 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700187 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
188 << "on downgrading to the version in the more stable channel";
189 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700190 XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700191 } else {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700192 app_versions = "version=\"" + XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700193 }
194
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700195 string download_channel = params->download_channel();
196 string app_channels = "track=\"" + XmlEncode(download_channel) + "\" ";
197 if (params->current_channel() != download_channel)
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700198 app_channels +=
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700199 "from_track=\"" + XmlEncode(params->current_channel()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700200
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700201 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700202
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700203 string app_xml =
Jay Srinivasandb0acdf2013-04-02 14:47:45 -0700204 " <app appid=\"" + XmlEncode(params->GetAppId()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700205 app_versions +
206 app_channels +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700207 "lang=\"" + XmlEncode(params->app_lang()) + "\" " +
208 "board=\"" + XmlEncode(params->os_board()) + "\" " +
209 "hardware_class=\"" + XmlEncode(params->hwid()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700210 "delta_okay=\"" + delta_okay_str + "\" "
211 ">\n" +
212 app_body +
213 " </app>\n";
214
215 return app_xml;
216}
217
218// Returns an XML that corresponds to the entire <os> node of the Omaha
219// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700220string GetOsXml(OmahaRequestParams* params) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700221 string os_xml =
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700222 " <os version=\"" + XmlEncode(params->os_version()) + "\" " +
223 "platform=\"" + XmlEncode(params->os_platform()) + "\" " +
224 "sp=\"" + XmlEncode(params->os_sp()) + "\">"
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700225 "</os>\n";
226 return os_xml;
227}
228
229// Returns an XML that corresponds to the entire Omaha request based on the
230// given parameters.
231string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700232 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700233 bool ping_only,
234 int ping_active_days,
235 int ping_roll_call_days,
236 SystemState* system_state) {
237 string os_xml = GetOsXml(params);
238 string app_xml = GetAppXml(event, params, ping_only, ping_active_days,
239 ping_roll_call_days, system_state);
240
241 string install_source = StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700242 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700243
244 string request_xml =
245 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700246 "<request protocol=\"3.0\" "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700247 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
248 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" " +
249 install_source +
250 "ismachine=\"1\">\n" +
251 os_xml +
252 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700253 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700254
255 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000256}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700257
rspangler@google.com49fdf182009-10-10 00:57:34 +0000258} // namespace {}
259
260// Encodes XML entities in a given string with libxml2. input must be
261// UTF-8 formatted. Output will be UTF-8 formatted.
262string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700263 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
264 // // cpu, considering creating one and caching it.
265 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
266 // xmlNewDoc(ConstXMLStr("1.0")));
267 // if (!xml_doc.get()) {
268 // LOG(ERROR) << "Unable to create xmlDoc";
269 // return "";
270 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000271 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
272 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
273 return string(reinterpret_cast<const char *>(str.get()));
274}
275
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800276OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700277 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700278 HttpFetcher* http_fetcher,
279 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800280 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700281 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700282 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700283 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700284 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700285 ping_roll_call_days_(0) {
286 params_ = system_state->request_params();
287}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000288
Darin Petkov6a5b3222010-07-13 14:55:28 -0700289OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000290
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700291// Calculates the value to use for the ping days parameter.
292int OmahaRequestAction::CalculatePingDays(const string& key) {
293 int days = kNeverPinged;
294 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800295 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700296 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
297 if (days < 0) {
298 // If |days| is negative, then the system clock must have jumped
299 // back in time since the ping was sent. Mark the value so that
300 // it doesn't get sent to the server but we still update the
301 // last ping daystart preference. This way the next ping time
302 // will be correct, hopefully.
303 days = kPingTimeJump;
304 LOG(WARNING) <<
305 "System clock jumped back in time. Resetting ping daystarts.";
306 }
307 }
308 return days;
309}
310
311void OmahaRequestAction::InitPingDays() {
312 // We send pings only along with update checks, not with events.
313 if (IsEvent()) {
314 return;
315 }
316 // TODO(petkov): Figure a way to distinguish active use pings
317 // vs. roll call pings. Currently, the two pings are identical. A
318 // fix needs to change this code as well as UpdateLastPingDays.
319 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
320 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
321}
322
Darin Petkov6a5b3222010-07-13 14:55:28 -0700323void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000324 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700325 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700326 if (ping_only_ &&
327 !ShouldPing(ping_active_days_) &&
328 !ShouldPing(ping_roll_call_days_)) {
329 processor_->ActionComplete(this, kActionCodeSuccess);
330 return;
331 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700332 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700333 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700334 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700335 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800336 ping_roll_call_days_,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700337 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700338
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800339 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
340 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700341 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700342 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700343 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000344}
345
Darin Petkov6a5b3222010-07-13 14:55:28 -0700346void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000347 http_fetcher_->TerminateTransfer();
348}
349
350// We just store the response in the buffer. Once we've received all bytes,
351// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700352void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
353 const char* bytes,
354 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000355 response_buffer_.reserve(response_buffer_.size() + length);
356 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
357}
358
359namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000360// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
361// on the returned object.
362// This code is roughly based on the libxml tutorial at:
363// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700364xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000365 xmlXPathObject* result = NULL;
366
367 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
368 xmlXPathNewContext(doc));
369 if (!context.get()) {
370 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
371 return NULL;
372 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000373
374 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000375 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700376 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000377 return NULL;
378 }
379 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700380 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000381 xmlXPathFreeObject(result);
382 return NULL;
383 }
384 return result;
385}
386
387// Returns the string value of a named attribute on a node, or empty string
388// if no such node exists. If the attribute exists and has a value of
389// empty string, there's no way to distinguish that from the attribute
390// not existing.
391string XmlGetProperty(xmlNode* node, const char* name) {
392 if (!xmlHasProp(node, ConstXMLStr(name)))
393 return "";
394 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
395 xmlGetProp(node, ConstXMLStr(name)));
396 string ret(reinterpret_cast<const char *>(str.get()));
397 return ret;
398}
399
400// Parses a 64 bit base-10 int from a string and returns it. Returns 0
401// on error. If the string contains "0", that's indistinguishable from
402// error.
403off_t ParseInt(const string& str) {
404 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700405 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000406 if (rc < 1) {
407 // failure
408 return 0;
409 }
410 return ret;
411}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700412
413// Update the last ping day preferences based on the server daystart
414// response. Returns true on success, false otherwise.
415bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700416 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700417
418 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700419 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700420 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
421 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
422 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
423 xmlNode* daystart_node = nodeset->nodeTab[0];
424 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
425 ConstXMLStr("elapsed_seconds")));
426
427 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700428 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
429 "elapsed_seconds"),
430 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700431 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
432
433 // Remember the local time that matches the server's last midnight
434 // time.
435 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
436 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
437 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
438 return true;
439}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000440} // namespace {}
441
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700442bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
443 OmahaResponse* output_object,
444 ScopedActionCompleter* completer) {
445 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
446
447 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
448 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
449 if (!xpath_nodeset.get()) {
450 completer->set_code(kActionCodeOmahaResponseInvalid);
451 return false;
452 }
453
454 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
455 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
456 CHECK_GE(nodeset->nodeNr, 1);
457 xmlNode* update_check_node = nodeset->nodeTab[0];
458
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800459 // chromium-os:37289: The PollInterval is not supported by Omaha server
460 // currently. But still keeping this existing code in case we ever decide to
461 // slow down the request rate from the server-side. Note that the
462 // PollInterval is not persisted, so it has to be sent by the server on every
463 // response to guarantee that the UpdateCheckScheduler uses this value
464 // (otherwise, if the device got rebooted after the last server-indicated
465 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
466 // value for the scattering logic is based on the assumption that we perform
467 // an update check every hour so that the max value of 8 will roughly be
468 // equivalent to one work day. If we decide to use PollInterval permanently,
469 // we should update the max_update_checks_allowed to take PollInterval into
470 // account. Note: The parsing for PollInterval happens even before parsing
471 // of the status because we may want to specify the PollInterval even when
472 // there's no update.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700473 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
474 &output_object->poll_interval);
475
476 if (!ParseStatus(update_check_node, output_object, completer))
477 return false;
478
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800479 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
480 // appends the package name to the URLs populated in this method.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700481 if (!ParseUrls(doc, output_object, completer))
482 return false;
483
484 if (!ParsePackage(doc, output_object, completer))
485 return false;
486
487 if (!ParseParams(doc, output_object, completer))
488 return false;
489
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800490 output_object->update_exists = true;
491 SetOutputObject(*output_object);
492 completer->set_code(kActionCodeSuccess);
493
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700494 return true;
495}
496
497bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
498 OmahaResponse* output_object,
499 ScopedActionCompleter* completer) {
500 // Get status.
501 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
502 LOG(ERROR) << "Omaha Response missing status";
503 completer->set_code(kActionCodeOmahaResponseInvalid);
504 return false;
505 }
506
507 const string status(XmlGetProperty(update_check_node, "status"));
508 if (status == "noupdate") {
509 LOG(INFO) << "No update.";
510 output_object->update_exists = false;
511 SetOutputObject(*output_object);
512 completer->set_code(kActionCodeSuccess);
513 return false;
514 }
515
516 if (status != "ok") {
517 LOG(ERROR) << "Unknown Omaha response status: " << status;
518 completer->set_code(kActionCodeOmahaResponseInvalid);
519 return false;
520 }
521
522 return true;
523}
524
525bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
526 OmahaResponse* output_object,
527 ScopedActionCompleter* completer) {
528 // Get the update URL.
529 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
530
531 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
532 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
533 if (!xpath_nodeset.get()) {
534 completer->set_code(kActionCodeOmahaResponseInvalid);
535 return false;
536 }
537
538 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
539 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
540 CHECK_GE(nodeset->nodeNr, 1);
541
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800542 LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)";
543 output_object->payload_urls.clear();
544 for (int i = 0; i < nodeset->nodeNr; i++) {
545 xmlNode* url_node = nodeset->nodeTab[i];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700546
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800547 const string codebase(XmlGetProperty(url_node, "codebase"));
548 if (codebase.empty()) {
549 LOG(ERROR) << "Omaha Response URL has empty codebase";
550 completer->set_code(kActionCodeOmahaResponseInvalid);
551 return false;
552 }
553 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700554 }
555
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700556 return true;
557}
558
559bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
560 OmahaResponse* output_object,
561 ScopedActionCompleter* completer) {
562 // Get the package node.
563 static const char* kPackageNodeXPath(
564 "/response/app/updatecheck/manifest/packages/package");
565
566 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
567 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
568 if (!xpath_nodeset.get()) {
569 completer->set_code(kActionCodeOmahaResponseInvalid);
570 return false;
571 }
572
573 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
574 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
575 CHECK_GE(nodeset->nodeNr, 1);
576
577 // We only care about the first package.
578 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
579 xmlNode* package_node = nodeset->nodeTab[0];
580
581 // Get package properties one by one.
582
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800583 // Parse the payload name to be appended to the base Url value.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700584 const string package_name(XmlGetProperty(package_node, "name"));
585 LOG(INFO) << "Omaha Response package name = " << package_name;
586 if (package_name.empty()) {
587 LOG(ERROR) << "Omaha Response has empty package name";
588 completer->set_code(kActionCodeOmahaResponseInvalid);
589 return false;
590 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800591
592 // Append the package name to each URL in our list so that we don't
593 // propagate the urlBase vs packageName distinctions beyond this point.
594 // From now on, we only need to use payload_urls.
595 for (size_t i = 0; i < output_object->payload_urls.size(); i++) {
596 output_object->payload_urls[i] += package_name;
597 LOG(INFO) << "Url" << i << ": " << output_object->payload_urls[i];
598 }
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;
604 completer->set_code(kActionCodeOmahaResponseInvalid);
605 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) {
617 // Get the action node where parameters are present.
618 static const char* kActionNodeXPath(
619 "/response/app/updatecheck/manifest/actions/action");
620
621 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
622 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
623 if (!xpath_nodeset.get()) {
624 completer->set_code(kActionCodeOmahaResponseInvalid);
625 return false;
626 }
627
628 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
629 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
630
631 // We only care about the action that has event "postinall", because this is
632 // where Omaha puts all the generic name/value pairs in the rule.
633 LOG(INFO) << "Found " << nodeset->nodeNr
634 << " action(s). Processing the postinstall action.";
635
636 // pie_action_node holds the action node corresponding to the
637 // postinstall event action, if present.
638 xmlNode* pie_action_node = NULL;
639 for (int i = 0; i < nodeset->nodeNr; i++) {
640 xmlNode* action_node = nodeset->nodeTab[i];
641 if (XmlGetProperty(action_node, "event") == "postinstall") {
642 pie_action_node = action_node;
643 break;
644 }
645 }
646
647 if (!pie_action_node) {
648 LOG(ERROR) << "Omaha Response has no postinstall event action";
649 completer->set_code(kActionCodeOmahaResponseInvalid);
650 return false;
651 }
652
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800653 output_object->hash = XmlGetProperty(pie_action_node, kTagSha256);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700654 if (output_object->hash.empty()) {
655 LOG(ERROR) << "Omaha Response has empty sha256 value";
656 completer->set_code(kActionCodeOmahaResponseInvalid);
657 return false;
658 }
659
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800660 // Get the optional properties one by one.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700661 output_object->display_version =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800662 XmlGetProperty(pie_action_node, kTagDisplayVersion);
663 output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700664 output_object->metadata_size =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800665 ParseInt(XmlGetProperty(pie_action_node, kTagMetadataSize));
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700666 output_object->metadata_signature =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800667 XmlGetProperty(pie_action_node, kTagMetadataSignatureRsa);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700668 output_object->needs_admin =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800669 XmlGetProperty(pie_action_node, kTagNeedsAdmin) == "true";
670 output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true";
671 output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700672 output_object->max_days_to_scatter =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800673 ParseInt(XmlGetProperty(pie_action_node, kTagMaxDaysToScatter));
674
675 string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl);
Jay Srinivasan08262882012-12-28 19:29:43 -0800676 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800677 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700678
Jay Srinivasan08262882012-12-28 19:29:43 -0800679 output_object->is_delta_payload =
680 XmlGetProperty(pie_action_node, kTagIsDeltaPayload) == "true";
681
682 output_object->disable_payload_backoff =
683 XmlGetProperty(pie_action_node, kTagDisablePayloadBackoff) == "true";
684
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700685 return true;
686}
687
rspangler@google.com49fdf182009-10-10 00:57:34 +0000688// If the transfer was successful, this uses libxml2 to parse the response
689// and fill in the appropriate fields of the output object. Also, notifies
690// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700691void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
692 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000693 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800694 string current_response(response_buffer_.begin(), response_buffer_.end());
695 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700696
697 // Events are best effort transactions -- assume they always succeed.
698 if (IsEvent()) {
699 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800700 if (event_->result == OmahaEvent::kResultError && successful &&
701 utils::IsOfficialBuild()) {
702 LOG(INFO) << "Signalling Crash Reporter.";
703 utils::ScheduleCrashReporterUpload();
704 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700705 completer.set_code(kActionCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700706 return;
707 }
708
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700709 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700710 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700711 int code = GetHTTPResponseCode();
712 // Makes sure we send sane error values.
713 if (code < 0 || code >= 1000) {
714 code = 999;
715 }
716 completer.set_code(static_cast<ActionExitCode>(
717 kActionCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000718 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700719 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000720
721 // parse our response and fill the fields in the output object
722 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
723 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
724 if (!doc.get()) {
725 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700726 completer.set_code(response_buffer_.empty() ?
727 kActionCodeOmahaRequestEmptyResponseError :
728 kActionCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000729 return;
730 }
731
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700732 // If a ping was sent, update the last ping day preferences based on
733 // the server daystart response.
734 if (ShouldPing(ping_active_days_) ||
735 ShouldPing(ping_roll_call_days_) ||
736 ping_active_days_ == kPingTimeJump ||
737 ping_roll_call_days_ == kPingTimeJump) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800738 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700739 << "Failed to update the last ping day preferences!";
740 }
741
Thieu Le116fda32011-04-19 11:01:54 -0700742 if (!HasOutputPipe()) {
743 // Just set success to whether or not the http transfer succeeded,
744 // which must be true at this point in the code.
745 completer.set_code(kActionCodeSuccess);
746 return;
747 }
748
Darin Petkov6a5b3222010-07-13 14:55:28 -0700749 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700750 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000751 return;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000752
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700753 if (params_->update_disabled()) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700754 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700755 output_object.update_exists = false;
Jay Srinivasan0a708742012-03-20 11:26:12 -0700756 completer.set_code(kActionCodeOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700757 // Note: We could technically delete the UpdateFirstSeenAt state here.
758 // If we do, it'll mean a device has to restart the UpdateFirstSeenAt
759 // and thus help scattering take effect when the AU is turned on again.
760 // On the other hand, it also increases the chance of update starvation if
761 // an admin turns AU on/off more frequently. We choose to err on the side
762 // of preventing starvation at the cost of not applying scattering in
763 // those cases.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700764 return;
765 }
766
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700767 if (ShouldDeferDownload(&output_object)) {
768 output_object.update_exists = false;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700769 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
770 completer.set_code(kActionCodeOmahaUpdateDeferredPerPolicy);
771 return;
772 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800773
774 // Update the payload state with the current response. The payload state
775 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800776 // from what's stored already. We are updating the payload state as late
777 // as possible in this method so that if a new release gets pushed and then
778 // got pulled back due to some issues, we don't want to clear our internal
779 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800780 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800781 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800782
783 if (payload_state->ShouldBackoffDownload()) {
784 output_object.update_exists = false;
785 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
786 "attempts";
787 completer.set_code(kActionCodeOmahaUpdateDeferredForBackoff);
788 return;
789 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000790}
791
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700792bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700793 // We should defer the downloads only if we've first satisfied the
794 // wall-clock-based-waiting period and then the update-check-based waiting
795 // period, if required.
796
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700797 if (!params_->wall_clock_based_wait_enabled()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700798 // Wall-clock-based waiting period is not enabled, so no scattering needed.
799 return false;
800 }
801
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700802 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700803 case kWallClockWaitNotSatisfied:
804 // We haven't even satisfied the first condition, passing the
805 // wall-clock-based waiting period, so we should defer the downloads
806 // until that happens.
807 LOG(INFO) << "wall-clock-based-wait not satisfied.";
808 return true;
809
810 case kWallClockWaitDoneButUpdateCheckWaitRequired:
811 LOG(INFO) << "wall-clock-based-wait satisfied and "
812 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700813 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700814
815 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
816 // Wall-clock-based waiting period is satisfied, and it's determined
817 // that we do not need the update-check-based wait. so no need to
818 // defer downloads.
819 LOG(INFO) << "wall-clock-based-wait satisfied and "
820 << "update-check-based-wait is not required.";
821 return false;
822
823 default:
824 // Returning false for this default case so we err on the
825 // side of downloading updates than deferring in case of any bugs.
826 NOTREACHED();
827 return false;
828 }
829}
830
831OmahaRequestAction::WallClockWaitResult
832OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700833 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700834 Time update_first_seen_at;
835 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700836
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800837 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
838 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
839 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700840 // Note: This timestamp could be that of ANY update we saw in the past
841 // (not necessarily this particular update we're considering to apply)
842 // but never got to apply because of some reason (e.g. stop AU policy,
843 // updates being pulled out from Omaha, changes in target version prefix,
844 // new update being rolled out, etc.). But for the purposes of scattering
845 // it doesn't matter which update the timestamp corresponds to. i.e.
846 // the clock starts ticking the first time we see an update and we're
847 // ready to apply when the random wait period is satisfied relative to
848 // that first seen timestamp.
849 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
850 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
851 << utils::ToString(update_first_seen_at);
852 } else {
853 // This seems like an unexpected error where the persisted value exists
854 // but it's not readable for some reason. Just skip scattering in this
855 // case to be safe.
856 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
857 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
858 }
859 } else {
860 update_first_seen_at = Time::Now();
861 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800862 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
863 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700864 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
865 << utils::ToString(update_first_seen_at);
866 }
867 else {
868 // This seems like an unexpected error where the value cannot be
869 // persisted for some reason. Just skip scattering in this
870 // case to be safe.
871 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
872 << utils::ToString(update_first_seen_at)
873 << " cannot be persisted";
874 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
875 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700876 }
877
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700878 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700879 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700880 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700881
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700882 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700883 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700884 << ", Time Elapsed = "
885 << utils::FormatSecs(elapsed_time.InSeconds())
886 << ", MaxDaysToScatter = "
887 << max_scatter_period.InDays();
888
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700889 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700890 // The deadline is set for all rules which serve a delta update from a
891 // previous FSI, which means this update will be applied mostly in OOBE
892 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
893 // quickly.
894 LOG(INFO) << "Not scattering as deadline flag is set";
895 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
896 }
897
898 if (max_scatter_period.InDays() == 0) {
899 // This means the Omaha rule creator decides that this rule
900 // should not be scattered irrespective of the policy.
901 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
902 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
903 }
904
905 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700906 // This means we've waited more than the upperbound wait in the rule
907 // from the time we first saw a valid update available to us.
908 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700909 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
910 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
911 }
912
913 // This means we are required to participate in scattering.
914 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700915 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700916 if (remaining_wait_time.InSeconds() <= 0) {
917 // Yes, it's our turn now.
918 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
919
920 // But we can't download until the update-check-count-based wait is also
921 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700922 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700923 kWallClockWaitDoneButUpdateCheckWaitRequired :
924 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
925 }
926
927 // Not our turn yet, so we have to wait until our turn to
928 // help scatter the downloads across all clients of the enterprise.
929 LOG(INFO) << "Update deferred for another "
930 << utils::FormatSecs(remaining_wait_time.InSeconds())
931 << " per policy.";
932 return kWallClockWaitNotSatisfied;
933}
934
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700935bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700936 int64 update_check_count_value;
937
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800938 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
939 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
940 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700941 // We are unable to read the update check count from file for some reason.
942 // So let's proceed anyway so as to not stall the update.
943 LOG(ERROR) << "Unable to read update check count. "
944 << "Skipping update-check-count-based-wait.";
945 return true;
946 }
947 } else {
948 // This file does not exist. This means we haven't started our update
949 // check count down yet, so this is the right time to start the count down.
950 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700951 params_->min_update_checks_needed(),
952 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700953
954 LOG(INFO) << "Randomly picked update check count value = "
955 << update_check_count_value;
956
957 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800958 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
959 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700960 // We weren't able to write the update check count file for some reason.
961 // So let's proceed anyway so as to not stall the update.
962 LOG(ERROR) << "Unable to write update check count. "
963 << "Skipping update-check-count-based-wait.";
964 return true;
965 }
966 }
967
968 if (update_check_count_value == 0) {
969 LOG(INFO) << "Successfully passed the update-check-based-wait.";
970 return true;
971 }
972
973 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700974 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700975 // We err on the side of skipping scattering logic instead of stalling
976 // a machine from receiving any updates in case of any unexpected state.
977 LOG(ERROR) << "Invalid value for update check count detected. "
978 << "Skipping update-check-count-based-wait.";
979 return true;
980 }
981
982 // Legal value, we need to wait for more update checks to happen
983 // until this becomes 0.
984 LOG(INFO) << "Deferring Omaha updates for another "
985 << update_check_count_value
986 << " update checks per policy";
987 return false;
988}
989
990} // namespace chromeos_update_engine
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700991
992