blob: b19627b2112bc6f4df4c187f3f0c112bc1ae14d8 [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.
102string GetPingBody(int ping_active_days, int ping_roll_call_days) {
103 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
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700113string FormatRequest(const OmahaEvent* event,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700114 const OmahaRequestParams& params,
Thieu Le116fda32011-04-19 11:01:54 -0700115 bool ping_only,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700116 int ping_active_days,
Darin Petkov95508da2011-01-05 12:42:29 -0800117 int ping_roll_call_days,
118 PrefsInterface* prefs) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700119 string body;
120 if (event == NULL) {
Thieu Le116fda32011-04-19 11:01:54 -0700121 body = GetPingBody(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700122 if (!ping_only) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700123 // not passing update_disabled to Omaha because we want to
124 // get the update and report with UpdateDeferred result so that
125 // borgmon charts show up updates that are deferred. This is also
126 // the expected behavior when we move to Omaha v3.0 protocol, so it'll
127 // be consistent.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700128 body += StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700129 " <updatecheck"
Jay Srinivasan0a708742012-03-20 11:26:12 -0700130 " targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700131 "></updatecheck>\n",
Gilad Arnold8a659d82013-01-24 11:26:00 -0800132 XmlEncode(params.target_version_prefix).c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700133
Darin Petkov265f2902011-05-09 15:17:40 -0700134 // If this is the first update check after a reboot following a previous
135 // update, generate an event containing the previous version number. If
136 // the previous version preference file doesn't exist the event is still
137 // generated with a previous version of 0.0.0.0 -- this is relevant for
138 // older clients or new installs. The previous version event is not sent
139 // for ping-only requests because they come before the client has
140 // rebooted.
141 string prev_version;
142 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
143 prev_version = "0.0.0.0";
144 }
145 if (!prev_version.empty()) {
146 body += StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700147 " <event eventtype=\"%d\" eventresult=\"%d\" "
148 "previousversion=\"%s\"></event>\n",
Darin Petkov265f2902011-05-09 15:17:40 -0700149 OmahaEvent::kTypeUpdateComplete,
150 OmahaEvent::kResultSuccessReboot,
151 XmlEncode(prev_version).c_str());
152 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
153 << "Unable to reset the previous version.";
154 }
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 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700163 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 }
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700167 return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700168 "<request protocol=\"3.0\" "
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700169 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
170 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" "
Gilad Arnold8a659d82013-01-24 11:26:00 -0800171 "installsource=\"" +
172 (params.interactive ? "ondemandupdate" : "scheduler") + "\" "
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700173 "ismachine=\"1\">\n"
174 " <os version=\"" + XmlEncode(params.os_version) + "\" platform=\"" +
rspangler@google.com49fdf182009-10-10 00:57:34 +0000175 XmlEncode(params.os_platform) + "\" sp=\"" +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700176 XmlEncode(params.os_sp) + "\"></os>\n"
177 " <app appid=\"" + XmlEncode(params.app_id) + "\" version=\"" +
rspangler@google.com49fdf182009-10-10 00:57:34 +0000178 XmlEncode(params.app_version) + "\" "
179 "lang=\"" + XmlEncode(params.app_lang) + "\" track=\"" +
Andrew de los Reyes37c20322010-06-30 13:27:19 -0700180 XmlEncode(params.app_track) + "\" board=\"" +
Darin Petkovfbb40092010-07-29 17:05:50 -0700181 XmlEncode(params.os_board) + "\" hardware_class=\"" +
182 XmlEncode(params.hardware_class) + "\" delta_okay=\"" +
Gilad Arnold5e73ad72013-01-18 00:39:49 -0800183 (params.delta_okay ? "true" : "false") + "\">\n" + body +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700184 " </app>\n"
185 "</request>\n";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000186}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700187
rspangler@google.com49fdf182009-10-10 00:57:34 +0000188} // namespace {}
189
190// Encodes XML entities in a given string with libxml2. input must be
191// UTF-8 formatted. Output will be UTF-8 formatted.
192string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700193 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
194 // // cpu, considering creating one and caching it.
195 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
196 // xmlNewDoc(ConstXMLStr("1.0")));
197 // if (!xml_doc.get()) {
198 // LOG(ERROR) << "Unable to create xmlDoc";
199 // return "";
200 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000201 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
202 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
203 return string(reinterpret_cast<const char *>(str.get()));
204}
205
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800206OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700207 OmahaRequestParams* params,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700208 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700209 HttpFetcher* http_fetcher,
210 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800211 : system_state_(system_state),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700212 params_(params),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700213 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700214 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700215 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700216 ping_active_days_(0),
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700217 ping_roll_call_days_(0) {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000218
Darin Petkov6a5b3222010-07-13 14:55:28 -0700219OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000220
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700221// Calculates the value to use for the ping days parameter.
222int OmahaRequestAction::CalculatePingDays(const string& key) {
223 int days = kNeverPinged;
224 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800225 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700226 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
227 if (days < 0) {
228 // If |days| is negative, then the system clock must have jumped
229 // back in time since the ping was sent. Mark the value so that
230 // it doesn't get sent to the server but we still update the
231 // last ping daystart preference. This way the next ping time
232 // will be correct, hopefully.
233 days = kPingTimeJump;
234 LOG(WARNING) <<
235 "System clock jumped back in time. Resetting ping daystarts.";
236 }
237 }
238 return days;
239}
240
241void OmahaRequestAction::InitPingDays() {
242 // We send pings only along with update checks, not with events.
243 if (IsEvent()) {
244 return;
245 }
246 // TODO(petkov): Figure a way to distinguish active use pings
247 // vs. roll call pings. Currently, the two pings are identical. A
248 // fix needs to change this code as well as UpdateLastPingDays.
249 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
250 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
251}
252
Darin Petkov6a5b3222010-07-13 14:55:28 -0700253void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000254 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700255 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700256 if (ping_only_ &&
257 !ShouldPing(ping_active_days_) &&
258 !ShouldPing(ping_roll_call_days_)) {
259 processor_->ActionComplete(this, kActionCodeSuccess);
260 return;
261 }
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700262 string request_post(FormatRequest(event_.get(),
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700263 *params_,
Thieu Le116fda32011-04-19 11:01:54 -0700264 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700265 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800266 ping_roll_call_days_,
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800267 system_state_->prefs()));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700268
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800269 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
270 kHttpContentTypeTextXml);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700271 LOG(INFO) << "Posting an Omaha request to " << params_->update_url;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700272 LOG(INFO) << "Request: " << request_post;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700273 http_fetcher_->BeginTransfer(params_->update_url);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000274}
275
Darin Petkov6a5b3222010-07-13 14:55:28 -0700276void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000277 http_fetcher_->TerminateTransfer();
278}
279
280// We just store the response in the buffer. Once we've received all bytes,
281// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700282void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
283 const char* bytes,
284 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000285 response_buffer_.reserve(response_buffer_.size() + length);
286 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
287}
288
289namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000290// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
291// on the returned object.
292// This code is roughly based on the libxml tutorial at:
293// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700294xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000295 xmlXPathObject* result = NULL;
296
297 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
298 xmlXPathNewContext(doc));
299 if (!context.get()) {
300 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
301 return NULL;
302 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000303
304 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000305 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700306 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000307 return NULL;
308 }
309 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700310 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000311 xmlXPathFreeObject(result);
312 return NULL;
313 }
314 return result;
315}
316
317// Returns the string value of a named attribute on a node, or empty string
318// if no such node exists. If the attribute exists and has a value of
319// empty string, there's no way to distinguish that from the attribute
320// not existing.
321string XmlGetProperty(xmlNode* node, const char* name) {
322 if (!xmlHasProp(node, ConstXMLStr(name)))
323 return "";
324 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
325 xmlGetProp(node, ConstXMLStr(name)));
326 string ret(reinterpret_cast<const char *>(str.get()));
327 return ret;
328}
329
330// Parses a 64 bit base-10 int from a string and returns it. Returns 0
331// on error. If the string contains "0", that's indistinguishable from
332// error.
333off_t ParseInt(const string& str) {
334 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700335 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000336 if (rc < 1) {
337 // failure
338 return 0;
339 }
340 return ret;
341}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700342
343// Update the last ping day preferences based on the server daystart
344// response. Returns true on success, false otherwise.
345bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700346 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700347
348 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700349 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700350 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
351 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
352 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
353 xmlNode* daystart_node = nodeset->nodeTab[0];
354 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
355 ConstXMLStr("elapsed_seconds")));
356
357 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700358 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
359 "elapsed_seconds"),
360 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700361 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
362
363 // Remember the local time that matches the server's last midnight
364 // time.
365 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
366 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
367 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
368 return true;
369}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000370} // namespace {}
371
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700372bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
373 OmahaResponse* output_object,
374 ScopedActionCompleter* completer) {
375 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
376
377 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
378 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
379 if (!xpath_nodeset.get()) {
380 completer->set_code(kActionCodeOmahaResponseInvalid);
381 return false;
382 }
383
384 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
385 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
386 CHECK_GE(nodeset->nodeNr, 1);
387 xmlNode* update_check_node = nodeset->nodeTab[0];
388
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800389 // chromium-os:37289: The PollInterval is not supported by Omaha server
390 // currently. But still keeping this existing code in case we ever decide to
391 // slow down the request rate from the server-side. Note that the
392 // PollInterval is not persisted, so it has to be sent by the server on every
393 // response to guarantee that the UpdateCheckScheduler uses this value
394 // (otherwise, if the device got rebooted after the last server-indicated
395 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
396 // value for the scattering logic is based on the assumption that we perform
397 // an update check every hour so that the max value of 8 will roughly be
398 // equivalent to one work day. If we decide to use PollInterval permanently,
399 // we should update the max_update_checks_allowed to take PollInterval into
400 // account. Note: The parsing for PollInterval happens even before parsing
401 // of the status because we may want to specify the PollInterval even when
402 // there's no update.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700403 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
404 &output_object->poll_interval);
405
406 if (!ParseStatus(update_check_node, output_object, completer))
407 return false;
408
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800409 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
410 // appends the package name to the URLs populated in this method.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700411 if (!ParseUrls(doc, output_object, completer))
412 return false;
413
414 if (!ParsePackage(doc, output_object, completer))
415 return false;
416
417 if (!ParseParams(doc, output_object, completer))
418 return false;
419
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800420 output_object->update_exists = true;
421 SetOutputObject(*output_object);
422 completer->set_code(kActionCodeSuccess);
423
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700424 return true;
425}
426
427bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
428 OmahaResponse* output_object,
429 ScopedActionCompleter* completer) {
430 // Get status.
431 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
432 LOG(ERROR) << "Omaha Response missing status";
433 completer->set_code(kActionCodeOmahaResponseInvalid);
434 return false;
435 }
436
437 const string status(XmlGetProperty(update_check_node, "status"));
438 if (status == "noupdate") {
439 LOG(INFO) << "No update.";
440 output_object->update_exists = false;
441 SetOutputObject(*output_object);
442 completer->set_code(kActionCodeSuccess);
443 return false;
444 }
445
446 if (status != "ok") {
447 LOG(ERROR) << "Unknown Omaha response status: " << status;
448 completer->set_code(kActionCodeOmahaResponseInvalid);
449 return false;
450 }
451
452 return true;
453}
454
455bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
456 OmahaResponse* output_object,
457 ScopedActionCompleter* completer) {
458 // Get the update URL.
459 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
460
461 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
462 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
463 if (!xpath_nodeset.get()) {
464 completer->set_code(kActionCodeOmahaResponseInvalid);
465 return false;
466 }
467
468 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
469 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
470 CHECK_GE(nodeset->nodeNr, 1);
471
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800472 LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)";
473 output_object->payload_urls.clear();
474 for (int i = 0; i < nodeset->nodeNr; i++) {
475 xmlNode* url_node = nodeset->nodeTab[i];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700476
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800477 const string codebase(XmlGetProperty(url_node, "codebase"));
478 if (codebase.empty()) {
479 LOG(ERROR) << "Omaha Response URL has empty codebase";
480 completer->set_code(kActionCodeOmahaResponseInvalid);
481 return false;
482 }
483 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700484 }
485
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700486 return true;
487}
488
489bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
490 OmahaResponse* output_object,
491 ScopedActionCompleter* completer) {
492 // Get the package node.
493 static const char* kPackageNodeXPath(
494 "/response/app/updatecheck/manifest/packages/package");
495
496 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
497 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
498 if (!xpath_nodeset.get()) {
499 completer->set_code(kActionCodeOmahaResponseInvalid);
500 return false;
501 }
502
503 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
504 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
505 CHECK_GE(nodeset->nodeNr, 1);
506
507 // We only care about the first package.
508 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
509 xmlNode* package_node = nodeset->nodeTab[0];
510
511 // Get package properties one by one.
512
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800513 // Parse the payload name to be appended to the base Url value.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700514 const string package_name(XmlGetProperty(package_node, "name"));
515 LOG(INFO) << "Omaha Response package name = " << package_name;
516 if (package_name.empty()) {
517 LOG(ERROR) << "Omaha Response has empty package name";
518 completer->set_code(kActionCodeOmahaResponseInvalid);
519 return false;
520 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800521
522 // Append the package name to each URL in our list so that we don't
523 // propagate the urlBase vs packageName distinctions beyond this point.
524 // From now on, we only need to use payload_urls.
525 for (size_t i = 0; i < output_object->payload_urls.size(); i++) {
526 output_object->payload_urls[i] += package_name;
527 LOG(INFO) << "Url" << i << ": " << output_object->payload_urls[i];
528 }
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700529
530 // Parse the payload size.
531 off_t size = ParseInt(XmlGetProperty(package_node, "size"));
532 if (size <= 0) {
533 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
534 completer->set_code(kActionCodeOmahaResponseInvalid);
535 return false;
536 }
537 output_object->size = size;
538
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800539 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700540
541 return true;
542}
543
544bool OmahaRequestAction::ParseParams(xmlDoc* doc,
545 OmahaResponse* output_object,
546 ScopedActionCompleter* completer) {
547 // Get the action node where parameters are present.
548 static const char* kActionNodeXPath(
549 "/response/app/updatecheck/manifest/actions/action");
550
551 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
552 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
553 if (!xpath_nodeset.get()) {
554 completer->set_code(kActionCodeOmahaResponseInvalid);
555 return false;
556 }
557
558 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
559 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
560
561 // We only care about the action that has event "postinall", because this is
562 // where Omaha puts all the generic name/value pairs in the rule.
563 LOG(INFO) << "Found " << nodeset->nodeNr
564 << " action(s). Processing the postinstall action.";
565
566 // pie_action_node holds the action node corresponding to the
567 // postinstall event action, if present.
568 xmlNode* pie_action_node = NULL;
569 for (int i = 0; i < nodeset->nodeNr; i++) {
570 xmlNode* action_node = nodeset->nodeTab[i];
571 if (XmlGetProperty(action_node, "event") == "postinstall") {
572 pie_action_node = action_node;
573 break;
574 }
575 }
576
577 if (!pie_action_node) {
578 LOG(ERROR) << "Omaha Response has no postinstall event action";
579 completer->set_code(kActionCodeOmahaResponseInvalid);
580 return false;
581 }
582
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800583 output_object->hash = XmlGetProperty(pie_action_node, kTagSha256);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700584 if (output_object->hash.empty()) {
585 LOG(ERROR) << "Omaha Response has empty sha256 value";
586 completer->set_code(kActionCodeOmahaResponseInvalid);
587 return false;
588 }
589
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800590 // Get the optional properties one by one.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700591 output_object->display_version =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800592 XmlGetProperty(pie_action_node, kTagDisplayVersion);
593 output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700594 output_object->metadata_size =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800595 ParseInt(XmlGetProperty(pie_action_node, kTagMetadataSize));
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700596 output_object->metadata_signature =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800597 XmlGetProperty(pie_action_node, kTagMetadataSignatureRsa);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700598 output_object->needs_admin =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800599 XmlGetProperty(pie_action_node, kTagNeedsAdmin) == "true";
600 output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true";
601 output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700602 output_object->max_days_to_scatter =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800603 ParseInt(XmlGetProperty(pie_action_node, kTagMaxDaysToScatter));
604
605 string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl);
Jay Srinivasan08262882012-12-28 19:29:43 -0800606 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800607 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700608
Jay Srinivasan08262882012-12-28 19:29:43 -0800609 output_object->is_delta_payload =
610 XmlGetProperty(pie_action_node, kTagIsDeltaPayload) == "true";
611
612 output_object->disable_payload_backoff =
613 XmlGetProperty(pie_action_node, kTagDisablePayloadBackoff) == "true";
614
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700615 return true;
616}
617
rspangler@google.com49fdf182009-10-10 00:57:34 +0000618// If the transfer was successful, this uses libxml2 to parse the response
619// and fill in the appropriate fields of the output object. Also, notifies
620// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700621void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
622 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000623 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800624 string current_response(response_buffer_.begin(), response_buffer_.end());
625 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700626
627 // Events are best effort transactions -- assume they always succeed.
628 if (IsEvent()) {
629 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800630 if (event_->result == OmahaEvent::kResultError && successful &&
631 utils::IsOfficialBuild()) {
632 LOG(INFO) << "Signalling Crash Reporter.";
633 utils::ScheduleCrashReporterUpload();
634 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700635 completer.set_code(kActionCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700636 return;
637 }
638
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700639 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700640 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700641 int code = GetHTTPResponseCode();
642 // Makes sure we send sane error values.
643 if (code < 0 || code >= 1000) {
644 code = 999;
645 }
646 completer.set_code(static_cast<ActionExitCode>(
647 kActionCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000648 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700649 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000650
651 // parse our response and fill the fields in the output object
652 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
653 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
654 if (!doc.get()) {
655 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700656 completer.set_code(response_buffer_.empty() ?
657 kActionCodeOmahaRequestEmptyResponseError :
658 kActionCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000659 return;
660 }
661
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700662 // If a ping was sent, update the last ping day preferences based on
663 // the server daystart response.
664 if (ShouldPing(ping_active_days_) ||
665 ShouldPing(ping_roll_call_days_) ||
666 ping_active_days_ == kPingTimeJump ||
667 ping_roll_call_days_ == kPingTimeJump) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800668 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700669 << "Failed to update the last ping day preferences!";
670 }
671
Thieu Le116fda32011-04-19 11:01:54 -0700672 if (!HasOutputPipe()) {
673 // Just set success to whether or not the http transfer succeeded,
674 // which must be true at this point in the code.
675 completer.set_code(kActionCodeSuccess);
676 return;
677 }
678
Darin Petkov6a5b3222010-07-13 14:55:28 -0700679 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700680 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000681 return;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000682
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700683 if (params_->update_disabled) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700684 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700685 output_object.update_exists = false;
Jay Srinivasan0a708742012-03-20 11:26:12 -0700686 completer.set_code(kActionCodeOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700687 // Note: We could technically delete the UpdateFirstSeenAt state here.
688 // If we do, it'll mean a device has to restart the UpdateFirstSeenAt
689 // and thus help scattering take effect when the AU is turned on again.
690 // On the other hand, it also increases the chance of update starvation if
691 // an admin turns AU on/off more frequently. We choose to err on the side
692 // of preventing starvation at the cost of not applying scattering in
693 // those cases.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700694 return;
695 }
696
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700697 if (ShouldDeferDownload(&output_object)) {
698 output_object.update_exists = false;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700699 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
700 completer.set_code(kActionCodeOmahaUpdateDeferredPerPolicy);
701 return;
702 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800703
704 // Update the payload state with the current response. The payload state
705 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800706 // from what's stored already. We are updating the payload state as late
707 // as possible in this method so that if a new release gets pushed and then
708 // got pulled back due to some issues, we don't want to clear our internal
709 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800710 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800711 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800712
713 if (payload_state->ShouldBackoffDownload()) {
714 output_object.update_exists = false;
715 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
716 "attempts";
717 completer.set_code(kActionCodeOmahaUpdateDeferredForBackoff);
718 return;
719 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000720}
721
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700722bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700723 // We should defer the downloads only if we've first satisfied the
724 // wall-clock-based-waiting period and then the update-check-based waiting
725 // period, if required.
726
727 if (!params_->wall_clock_based_wait_enabled) {
728 // Wall-clock-based waiting period is not enabled, so no scattering needed.
729 return false;
730 }
731
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700732 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700733 case kWallClockWaitNotSatisfied:
734 // We haven't even satisfied the first condition, passing the
735 // wall-clock-based waiting period, so we should defer the downloads
736 // until that happens.
737 LOG(INFO) << "wall-clock-based-wait not satisfied.";
738 return true;
739
740 case kWallClockWaitDoneButUpdateCheckWaitRequired:
741 LOG(INFO) << "wall-clock-based-wait satisfied and "
742 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700743 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700744
745 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
746 // Wall-clock-based waiting period is satisfied, and it's determined
747 // that we do not need the update-check-based wait. so no need to
748 // defer downloads.
749 LOG(INFO) << "wall-clock-based-wait satisfied and "
750 << "update-check-based-wait is not required.";
751 return false;
752
753 default:
754 // Returning false for this default case so we err on the
755 // side of downloading updates than deferring in case of any bugs.
756 NOTREACHED();
757 return false;
758 }
759}
760
761OmahaRequestAction::WallClockWaitResult
762OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700763 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700764 Time update_first_seen_at;
765 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700766
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800767 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
768 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
769 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700770 // Note: This timestamp could be that of ANY update we saw in the past
771 // (not necessarily this particular update we're considering to apply)
772 // but never got to apply because of some reason (e.g. stop AU policy,
773 // updates being pulled out from Omaha, changes in target version prefix,
774 // new update being rolled out, etc.). But for the purposes of scattering
775 // it doesn't matter which update the timestamp corresponds to. i.e.
776 // the clock starts ticking the first time we see an update and we're
777 // ready to apply when the random wait period is satisfied relative to
778 // that first seen timestamp.
779 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
780 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
781 << utils::ToString(update_first_seen_at);
782 } else {
783 // This seems like an unexpected error where the persisted value exists
784 // but it's not readable for some reason. Just skip scattering in this
785 // case to be safe.
786 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
787 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
788 }
789 } else {
790 update_first_seen_at = Time::Now();
791 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800792 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
793 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700794 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
795 << utils::ToString(update_first_seen_at);
796 }
797 else {
798 // This seems like an unexpected error where the value cannot be
799 // persisted for some reason. Just skip scattering in this
800 // case to be safe.
801 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
802 << utils::ToString(update_first_seen_at)
803 << " cannot be persisted";
804 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
805 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700806 }
807
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700808 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700809 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700810 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700811
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700812 LOG(INFO) << "Waiting Period = "
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700813 << utils::FormatSecs(params_->waiting_period.InSeconds())
814 << ", Time Elapsed = "
815 << utils::FormatSecs(elapsed_time.InSeconds())
816 << ", MaxDaysToScatter = "
817 << max_scatter_period.InDays();
818
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700819 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700820 // The deadline is set for all rules which serve a delta update from a
821 // previous FSI, which means this update will be applied mostly in OOBE
822 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
823 // quickly.
824 LOG(INFO) << "Not scattering as deadline flag is set";
825 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
826 }
827
828 if (max_scatter_period.InDays() == 0) {
829 // This means the Omaha rule creator decides that this rule
830 // should not be scattered irrespective of the policy.
831 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
832 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
833 }
834
835 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700836 // This means we've waited more than the upperbound wait in the rule
837 // from the time we first saw a valid update available to us.
838 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700839 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
840 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
841 }
842
843 // This means we are required to participate in scattering.
844 // See if our turn has arrived now.
845 TimeDelta remaining_wait_time = params_->waiting_period - elapsed_time;
846 if (remaining_wait_time.InSeconds() <= 0) {
847 // Yes, it's our turn now.
848 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
849
850 // But we can't download until the update-check-count-based wait is also
851 // satisfied, so mark it as required now if update checks are enabled.
852 return params_->update_check_count_wait_enabled ?
853 kWallClockWaitDoneButUpdateCheckWaitRequired :
854 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
855 }
856
857 // Not our turn yet, so we have to wait until our turn to
858 // help scatter the downloads across all clients of the enterprise.
859 LOG(INFO) << "Update deferred for another "
860 << utils::FormatSecs(remaining_wait_time.InSeconds())
861 << " per policy.";
862 return kWallClockWaitNotSatisfied;
863}
864
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700865bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700866 int64 update_check_count_value;
867
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800868 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
869 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
870 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700871 // We are unable to read the update check count from file for some reason.
872 // So let's proceed anyway so as to not stall the update.
873 LOG(ERROR) << "Unable to read update check count. "
874 << "Skipping update-check-count-based-wait.";
875 return true;
876 }
877 } else {
878 // This file does not exist. This means we haven't started our update
879 // check count down yet, so this is the right time to start the count down.
880 update_check_count_value = base::RandInt(
881 params_->min_update_checks_needed,
882 params_->max_update_checks_allowed);
883
884 LOG(INFO) << "Randomly picked update check count value = "
885 << update_check_count_value;
886
887 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800888 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
889 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700890 // We weren't able to write the update check count file for some reason.
891 // So let's proceed anyway so as to not stall the update.
892 LOG(ERROR) << "Unable to write update check count. "
893 << "Skipping update-check-count-based-wait.";
894 return true;
895 }
896 }
897
898 if (update_check_count_value == 0) {
899 LOG(INFO) << "Successfully passed the update-check-based-wait.";
900 return true;
901 }
902
903 if (update_check_count_value < 0 ||
904 update_check_count_value > params_->max_update_checks_allowed) {
905 // We err on the side of skipping scattering logic instead of stalling
906 // a machine from receiving any updates in case of any unexpected state.
907 LOG(ERROR) << "Invalid value for update check count detected. "
908 << "Skipping update-check-count-based-wait.";
909 return true;
910 }
911
912 // Legal value, we need to wait for more update checks to happen
913 // until this becomes 0.
914 LOG(INFO) << "Deferring Omaha updates for another "
915 << update_check_count_value
916 << " update checks per policy";
917 return false;
918}
919
920} // namespace chromeos_update_engine
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700921
922