blob: 679d3265df7defdd8dc3f9a01592c9ebe4b839f2 [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"
Darin Petkov1cbd78f2010-07-29 12:38:34 -070023#include "update_engine/prefs_interface.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000024#include "update_engine/utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000025
Darin Petkov1cbd78f2010-07-29 12:38:34 -070026using base::Time;
27using base::TimeDelta;
rspangler@google.com49fdf182009-10-10 00:57:34 +000028using std::string;
29
30namespace chromeos_update_engine {
31
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080032// List of custom pair tags that we interpret in the Omaha Response:
33static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080034static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080035static const char* kTagDisplayVersion = "DisplayVersion";
Jay Srinivasan08262882012-12-28 19:29:43 -080036static const char* kTagIsDeltaPayload = "IsDelta";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080037static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
38static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
39// Deprecated: "ManifestSignatureRsa"
40// Deprecated: "ManifestSize"
41static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
42static const char* kTagMetadataSize = "MetadataSize";
43static const char* kTagMoreInfo = "MoreInfo";
44static const char* kTagNeedsAdmin = "needsadmin";
45static const char* kTagPrompt = "Prompt";
46static const char* kTagSha256 = "sha256";
47
rspangler@google.com49fdf182009-10-10 00:57:34 +000048namespace {
49
50const string kGupdateVersion("ChromeOSUpdateEngine-0.1.0.0");
51
52// This is handy for passing strings into libxml2
53#define ConstXMLStr(x) (reinterpret_cast<const xmlChar*>(x))
54
55// These are for scoped_ptr_malloc, which is like scoped_ptr, but allows
56// a custom free() function to be specified.
57class ScopedPtrXmlDocFree {
58 public:
59 inline void operator()(void* x) const {
60 xmlFreeDoc(reinterpret_cast<xmlDoc*>(x));
61 }
62};
63class ScopedPtrXmlFree {
64 public:
65 inline void operator()(void* x) const {
66 xmlFree(x);
67 }
68};
69class ScopedPtrXmlXPathObjectFree {
70 public:
71 inline void operator()(void* x) const {
72 xmlXPathFreeObject(reinterpret_cast<xmlXPathObject*>(x));
73 }
74};
75class ScopedPtrXmlXPathContextFree {
76 public:
77 inline void operator()(void* x) const {
78 xmlXPathFreeContext(reinterpret_cast<xmlXPathContext*>(x));
79 }
80};
81
Darin Petkov1cbd78f2010-07-29 12:38:34 -070082// Returns true if |ping_days| has a value that needs to be sent,
83// false otherwise.
84bool ShouldPing(int ping_days) {
85 return ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged;
86}
87
88// Returns an XML ping element attribute assignment with attribute
89// |name| and value |ping_days| if |ping_days| has a value that needs
90// to be sent, or an empty string otherwise.
91string GetPingAttribute(const string& name, int ping_days) {
92 if (ShouldPing(ping_days)) {
93 return StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
94 }
95 return "";
96}
97
98// Returns an XML ping element if any of the elapsed days need to be
99// sent, or an empty string otherwise.
100string GetPingBody(int ping_active_days, int ping_roll_call_days) {
101 string ping_active = GetPingAttribute("a", ping_active_days);
102 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
103 if (!ping_active.empty() || !ping_roll_call.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700104 return StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700105 ping_active.c_str(),
106 ping_roll_call.c_str());
107 }
108 return "";
109}
110
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700111string FormatRequest(const OmahaEvent* event,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700112 const OmahaRequestParams& params,
Thieu Le116fda32011-04-19 11:01:54 -0700113 bool ping_only,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700114 int ping_active_days,
Darin Petkov95508da2011-01-05 12:42:29 -0800115 int ping_roll_call_days,
116 PrefsInterface* prefs) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700117 string body;
118 if (event == NULL) {
Thieu Le116fda32011-04-19 11:01:54 -0700119 body = GetPingBody(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700120 if (!ping_only) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700121 // not passing update_disabled to Omaha because we want to
122 // get the update and report with UpdateDeferred result so that
123 // borgmon charts show up updates that are deferred. This is also
124 // the expected behavior when we move to Omaha v3.0 protocol, so it'll
125 // be consistent.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700126 body += StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700127 " <updatecheck"
Jay Srinivasan0a708742012-03-20 11:26:12 -0700128 " targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700129 "></updatecheck>\n",
Jay Srinivasan0a708742012-03-20 11:26:12 -0700130 XmlEncode(params.target_version_prefix).c_str());
131
Darin Petkov265f2902011-05-09 15:17:40 -0700132 // If this is the first update check after a reboot following a previous
133 // update, generate an event containing the previous version number. If
134 // the previous version preference file doesn't exist the event is still
135 // generated with a previous version of 0.0.0.0 -- this is relevant for
136 // older clients or new installs. The previous version event is not sent
137 // for ping-only requests because they come before the client has
138 // rebooted.
139 string prev_version;
140 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
141 prev_version = "0.0.0.0";
142 }
143 if (!prev_version.empty()) {
144 body += StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700145 " <event eventtype=\"%d\" eventresult=\"%d\" "
146 "previousversion=\"%s\"></event>\n",
Darin Petkov265f2902011-05-09 15:17:40 -0700147 OmahaEvent::kTypeUpdateComplete,
148 OmahaEvent::kResultSuccessReboot,
149 XmlEncode(prev_version).c_str());
150 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
151 << "Unable to reset the previous version.";
152 }
Darin Petkov95508da2011-01-05 12:42:29 -0800153 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700154 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800155 // The error code is an optional attribute so append it only if the result
156 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700157 string error_code;
158 if (event->result != OmahaEvent::kResultSuccess) {
Darin Petkov18c7bce2011-06-16 14:07:00 -0700159 error_code = StringPrintf(" errorcode=\"%d\"", event->error_code);
Darin Petkove17f86b2010-07-20 09:12:01 -0700160 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700161 body = StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700162 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700163 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700164 }
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700165 return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700166 "<request protocol=\"3.0\" "
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700167 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
168 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" "
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700169 "ismachine=\"1\">\n"
170 " <os version=\"" + XmlEncode(params.os_version) + "\" platform=\"" +
rspangler@google.com49fdf182009-10-10 00:57:34 +0000171 XmlEncode(params.os_platform) + "\" sp=\"" +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700172 XmlEncode(params.os_sp) + "\"></os>\n"
173 " <app appid=\"" + XmlEncode(params.app_id) + "\" version=\"" +
rspangler@google.com49fdf182009-10-10 00:57:34 +0000174 XmlEncode(params.app_version) + "\" "
175 "lang=\"" + XmlEncode(params.app_lang) + "\" track=\"" +
Andrew de los Reyes37c20322010-06-30 13:27:19 -0700176 XmlEncode(params.app_track) + "\" board=\"" +
Darin Petkovfbb40092010-07-29 17:05:50 -0700177 XmlEncode(params.os_board) + "\" hardware_class=\"" +
178 XmlEncode(params.hardware_class) + "\" delta_okay=\"" +
Andrew de los Reyes3f0303a2010-07-15 22:35:35 -0700179 (params.delta_okay ? "true" : "false") + "\">\n" + body +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700180 " </app>\n"
181 "</request>\n";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000182}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700183
rspangler@google.com49fdf182009-10-10 00:57:34 +0000184} // namespace {}
185
186// Encodes XML entities in a given string with libxml2. input must be
187// UTF-8 formatted. Output will be UTF-8 formatted.
188string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700189 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
190 // // cpu, considering creating one and caching it.
191 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
192 // xmlNewDoc(ConstXMLStr("1.0")));
193 // if (!xml_doc.get()) {
194 // LOG(ERROR) << "Unable to create xmlDoc";
195 // return "";
196 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000197 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
198 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
199 return string(reinterpret_cast<const char *>(str.get()));
200}
201
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800202OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700203 OmahaRequestParams* params,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700204 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700205 HttpFetcher* http_fetcher,
206 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800207 : system_state_(system_state),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700208 params_(params),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700209 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700210 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700211 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700212 ping_active_days_(0),
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700213 ping_roll_call_days_(0) {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000214
Darin Petkov6a5b3222010-07-13 14:55:28 -0700215OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000216
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700217// Calculates the value to use for the ping days parameter.
218int OmahaRequestAction::CalculatePingDays(const string& key) {
219 int days = kNeverPinged;
220 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800221 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700222 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
223 if (days < 0) {
224 // If |days| is negative, then the system clock must have jumped
225 // back in time since the ping was sent. Mark the value so that
226 // it doesn't get sent to the server but we still update the
227 // last ping daystart preference. This way the next ping time
228 // will be correct, hopefully.
229 days = kPingTimeJump;
230 LOG(WARNING) <<
231 "System clock jumped back in time. Resetting ping daystarts.";
232 }
233 }
234 return days;
235}
236
237void OmahaRequestAction::InitPingDays() {
238 // We send pings only along with update checks, not with events.
239 if (IsEvent()) {
240 return;
241 }
242 // TODO(petkov): Figure a way to distinguish active use pings
243 // vs. roll call pings. Currently, the two pings are identical. A
244 // fix needs to change this code as well as UpdateLastPingDays.
245 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
246 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
247}
248
Darin Petkov6a5b3222010-07-13 14:55:28 -0700249void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000250 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700251 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700252 if (ping_only_ &&
253 !ShouldPing(ping_active_days_) &&
254 !ShouldPing(ping_roll_call_days_)) {
255 processor_->ActionComplete(this, kActionCodeSuccess);
256 return;
257 }
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700258 string request_post(FormatRequest(event_.get(),
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700259 *params_,
Thieu Le116fda32011-04-19 11:01:54 -0700260 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700261 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800262 ping_roll_call_days_,
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800263 system_state_->prefs()));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700264
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800265 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
266 kHttpContentTypeTextXml);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700267 LOG(INFO) << "Posting an Omaha request to " << params_->update_url;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700268 LOG(INFO) << "Request: " << request_post;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700269 http_fetcher_->BeginTransfer(params_->update_url);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000270}
271
Darin Petkov6a5b3222010-07-13 14:55:28 -0700272void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000273 http_fetcher_->TerminateTransfer();
274}
275
276// We just store the response in the buffer. Once we've received all bytes,
277// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700278void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
279 const char* bytes,
280 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000281 response_buffer_.reserve(response_buffer_.size() + length);
282 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
283}
284
285namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000286// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
287// on the returned object.
288// This code is roughly based on the libxml tutorial at:
289// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700290xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000291 xmlXPathObject* result = NULL;
292
293 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
294 xmlXPathNewContext(doc));
295 if (!context.get()) {
296 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
297 return NULL;
298 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000299
300 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000301 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700302 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000303 return NULL;
304 }
305 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700306 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000307 xmlXPathFreeObject(result);
308 return NULL;
309 }
310 return result;
311}
312
313// Returns the string value of a named attribute on a node, or empty string
314// if no such node exists. If the attribute exists and has a value of
315// empty string, there's no way to distinguish that from the attribute
316// not existing.
317string XmlGetProperty(xmlNode* node, const char* name) {
318 if (!xmlHasProp(node, ConstXMLStr(name)))
319 return "";
320 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
321 xmlGetProp(node, ConstXMLStr(name)));
322 string ret(reinterpret_cast<const char *>(str.get()));
323 return ret;
324}
325
326// Parses a 64 bit base-10 int from a string and returns it. Returns 0
327// on error. If the string contains "0", that's indistinguishable from
328// error.
329off_t ParseInt(const string& str) {
330 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700331 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000332 if (rc < 1) {
333 // failure
334 return 0;
335 }
336 return ret;
337}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700338
339// Update the last ping day preferences based on the server daystart
340// response. Returns true on success, false otherwise.
341bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700342 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700343
344 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700345 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700346 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
347 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
348 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
349 xmlNode* daystart_node = nodeset->nodeTab[0];
350 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
351 ConstXMLStr("elapsed_seconds")));
352
353 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700354 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
355 "elapsed_seconds"),
356 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700357 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
358
359 // Remember the local time that matches the server's last midnight
360 // time.
361 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
362 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
363 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
364 return true;
365}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000366} // namespace {}
367
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700368bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
369 OmahaResponse* output_object,
370 ScopedActionCompleter* completer) {
371 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
372
373 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
374 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
375 if (!xpath_nodeset.get()) {
376 completer->set_code(kActionCodeOmahaResponseInvalid);
377 return false;
378 }
379
380 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
381 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
382 CHECK_GE(nodeset->nodeNr, 1);
383 xmlNode* update_check_node = nodeset->nodeTab[0];
384
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800385 // chromium-os:37289: The PollInterval is not supported by Omaha server
386 // currently. But still keeping this existing code in case we ever decide to
387 // slow down the request rate from the server-side. Note that the
388 // PollInterval is not persisted, so it has to be sent by the server on every
389 // response to guarantee that the UpdateCheckScheduler uses this value
390 // (otherwise, if the device got rebooted after the last server-indicated
391 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
392 // value for the scattering logic is based on the assumption that we perform
393 // an update check every hour so that the max value of 8 will roughly be
394 // equivalent to one work day. If we decide to use PollInterval permanently,
395 // we should update the max_update_checks_allowed to take PollInterval into
396 // account. Note: The parsing for PollInterval happens even before parsing
397 // of the status because we may want to specify the PollInterval even when
398 // there's no update.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700399 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
400 &output_object->poll_interval);
401
402 if (!ParseStatus(update_check_node, output_object, completer))
403 return false;
404
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800405 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
406 // appends the package name to the URLs populated in this method.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700407 if (!ParseUrls(doc, output_object, completer))
408 return false;
409
410 if (!ParsePackage(doc, output_object, completer))
411 return false;
412
413 if (!ParseParams(doc, output_object, completer))
414 return false;
415
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800416 output_object->update_exists = true;
417 SetOutputObject(*output_object);
418 completer->set_code(kActionCodeSuccess);
419
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700420 return true;
421}
422
423bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
424 OmahaResponse* output_object,
425 ScopedActionCompleter* completer) {
426 // Get status.
427 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
428 LOG(ERROR) << "Omaha Response missing status";
429 completer->set_code(kActionCodeOmahaResponseInvalid);
430 return false;
431 }
432
433 const string status(XmlGetProperty(update_check_node, "status"));
434 if (status == "noupdate") {
435 LOG(INFO) << "No update.";
436 output_object->update_exists = false;
437 SetOutputObject(*output_object);
438 completer->set_code(kActionCodeSuccess);
439 return false;
440 }
441
442 if (status != "ok") {
443 LOG(ERROR) << "Unknown Omaha response status: " << status;
444 completer->set_code(kActionCodeOmahaResponseInvalid);
445 return false;
446 }
447
448 return true;
449}
450
451bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
452 OmahaResponse* output_object,
453 ScopedActionCompleter* completer) {
454 // Get the update URL.
455 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
456
457 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
458 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
459 if (!xpath_nodeset.get()) {
460 completer->set_code(kActionCodeOmahaResponseInvalid);
461 return false;
462 }
463
464 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
465 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
466 CHECK_GE(nodeset->nodeNr, 1);
467
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800468 LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)";
469 output_object->payload_urls.clear();
470 for (int i = 0; i < nodeset->nodeNr; i++) {
471 xmlNode* url_node = nodeset->nodeTab[i];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700472
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800473 const string codebase(XmlGetProperty(url_node, "codebase"));
474 if (codebase.empty()) {
475 LOG(ERROR) << "Omaha Response URL has empty codebase";
476 completer->set_code(kActionCodeOmahaResponseInvalid);
477 return false;
478 }
479 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700480 }
481
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700482 return true;
483}
484
485bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
486 OmahaResponse* output_object,
487 ScopedActionCompleter* completer) {
488 // Get the package node.
489 static const char* kPackageNodeXPath(
490 "/response/app/updatecheck/manifest/packages/package");
491
492 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
493 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
494 if (!xpath_nodeset.get()) {
495 completer->set_code(kActionCodeOmahaResponseInvalid);
496 return false;
497 }
498
499 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
500 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
501 CHECK_GE(nodeset->nodeNr, 1);
502
503 // We only care about the first package.
504 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
505 xmlNode* package_node = nodeset->nodeTab[0];
506
507 // Get package properties one by one.
508
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800509 // Parse the payload name to be appended to the base Url value.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700510 const string package_name(XmlGetProperty(package_node, "name"));
511 LOG(INFO) << "Omaha Response package name = " << package_name;
512 if (package_name.empty()) {
513 LOG(ERROR) << "Omaha Response has empty package name";
514 completer->set_code(kActionCodeOmahaResponseInvalid);
515 return false;
516 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800517
518 // Append the package name to each URL in our list so that we don't
519 // propagate the urlBase vs packageName distinctions beyond this point.
520 // From now on, we only need to use payload_urls.
521 for (size_t i = 0; i < output_object->payload_urls.size(); i++) {
522 output_object->payload_urls[i] += package_name;
523 LOG(INFO) << "Url" << i << ": " << output_object->payload_urls[i];
524 }
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700525
526 // Parse the payload size.
527 off_t size = ParseInt(XmlGetProperty(package_node, "size"));
528 if (size <= 0) {
529 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
530 completer->set_code(kActionCodeOmahaResponseInvalid);
531 return false;
532 }
533 output_object->size = size;
534
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800535 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700536
537 return true;
538}
539
540bool OmahaRequestAction::ParseParams(xmlDoc* doc,
541 OmahaResponse* output_object,
542 ScopedActionCompleter* completer) {
543 // Get the action node where parameters are present.
544 static const char* kActionNodeXPath(
545 "/response/app/updatecheck/manifest/actions/action");
546
547 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
548 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
549 if (!xpath_nodeset.get()) {
550 completer->set_code(kActionCodeOmahaResponseInvalid);
551 return false;
552 }
553
554 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
555 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
556
557 // We only care about the action that has event "postinall", because this is
558 // where Omaha puts all the generic name/value pairs in the rule.
559 LOG(INFO) << "Found " << nodeset->nodeNr
560 << " action(s). Processing the postinstall action.";
561
562 // pie_action_node holds the action node corresponding to the
563 // postinstall event action, if present.
564 xmlNode* pie_action_node = NULL;
565 for (int i = 0; i < nodeset->nodeNr; i++) {
566 xmlNode* action_node = nodeset->nodeTab[i];
567 if (XmlGetProperty(action_node, "event") == "postinstall") {
568 pie_action_node = action_node;
569 break;
570 }
571 }
572
573 if (!pie_action_node) {
574 LOG(ERROR) << "Omaha Response has no postinstall event action";
575 completer->set_code(kActionCodeOmahaResponseInvalid);
576 return false;
577 }
578
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800579 output_object->hash = XmlGetProperty(pie_action_node, kTagSha256);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700580 if (output_object->hash.empty()) {
581 LOG(ERROR) << "Omaha Response has empty sha256 value";
582 completer->set_code(kActionCodeOmahaResponseInvalid);
583 return false;
584 }
585
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800586 // Get the optional properties one by one.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700587 output_object->display_version =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800588 XmlGetProperty(pie_action_node, kTagDisplayVersion);
589 output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700590 output_object->metadata_size =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800591 ParseInt(XmlGetProperty(pie_action_node, kTagMetadataSize));
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700592 output_object->metadata_signature =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800593 XmlGetProperty(pie_action_node, kTagMetadataSignatureRsa);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700594 output_object->needs_admin =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800595 XmlGetProperty(pie_action_node, kTagNeedsAdmin) == "true";
596 output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true";
597 output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700598 output_object->max_days_to_scatter =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800599 ParseInt(XmlGetProperty(pie_action_node, kTagMaxDaysToScatter));
600
601 string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl);
Jay Srinivasan08262882012-12-28 19:29:43 -0800602 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800603 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700604
Jay Srinivasan08262882012-12-28 19:29:43 -0800605 output_object->is_delta_payload =
606 XmlGetProperty(pie_action_node, kTagIsDeltaPayload) == "true";
607
608 output_object->disable_payload_backoff =
609 XmlGetProperty(pie_action_node, kTagDisablePayloadBackoff) == "true";
610
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700611 return true;
612}
613
rspangler@google.com49fdf182009-10-10 00:57:34 +0000614// If the transfer was successful, this uses libxml2 to parse the response
615// and fill in the appropriate fields of the output object. Also, notifies
616// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700617void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
618 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000619 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800620 string current_response(response_buffer_.begin(), response_buffer_.end());
621 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700622
623 // Events are best effort transactions -- assume they always succeed.
624 if (IsEvent()) {
625 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800626 if (event_->result == OmahaEvent::kResultError && successful &&
627 utils::IsOfficialBuild()) {
628 LOG(INFO) << "Signalling Crash Reporter.";
629 utils::ScheduleCrashReporterUpload();
630 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700631 completer.set_code(kActionCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700632 return;
633 }
634
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700635 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700636 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700637 int code = GetHTTPResponseCode();
638 // Makes sure we send sane error values.
639 if (code < 0 || code >= 1000) {
640 code = 999;
641 }
642 completer.set_code(static_cast<ActionExitCode>(
643 kActionCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000644 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700645 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000646
647 // parse our response and fill the fields in the output object
648 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
649 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
650 if (!doc.get()) {
651 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700652 completer.set_code(response_buffer_.empty() ?
653 kActionCodeOmahaRequestEmptyResponseError :
654 kActionCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000655 return;
656 }
657
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700658 // If a ping was sent, update the last ping day preferences based on
659 // the server daystart response.
660 if (ShouldPing(ping_active_days_) ||
661 ShouldPing(ping_roll_call_days_) ||
662 ping_active_days_ == kPingTimeJump ||
663 ping_roll_call_days_ == kPingTimeJump) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800664 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700665 << "Failed to update the last ping day preferences!";
666 }
667
Thieu Le116fda32011-04-19 11:01:54 -0700668 if (!HasOutputPipe()) {
669 // Just set success to whether or not the http transfer succeeded,
670 // which must be true at this point in the code.
671 completer.set_code(kActionCodeSuccess);
672 return;
673 }
674
Darin Petkov6a5b3222010-07-13 14:55:28 -0700675 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700676 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000677 return;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000678
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700679 if (params_->update_disabled) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700680 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700681 output_object.update_exists = false;
Jay Srinivasan0a708742012-03-20 11:26:12 -0700682 completer.set_code(kActionCodeOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700683 // Note: We could technically delete the UpdateFirstSeenAt state here.
684 // If we do, it'll mean a device has to restart the UpdateFirstSeenAt
685 // and thus help scattering take effect when the AU is turned on again.
686 // On the other hand, it also increases the chance of update starvation if
687 // an admin turns AU on/off more frequently. We choose to err on the side
688 // of preventing starvation at the cost of not applying scattering in
689 // those cases.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700690 return;
691 }
692
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700693 if (ShouldDeferDownload(&output_object)) {
694 output_object.update_exists = false;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700695 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
696 completer.set_code(kActionCodeOmahaUpdateDeferredPerPolicy);
697 return;
698 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800699
700 // Update the payload state with the current response. The payload state
701 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800702 // from what's stored already. We are updating the payload state as late
703 // as possible in this method so that if a new release gets pushed and then
704 // got pulled back due to some issues, we don't want to clear our internal
705 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800706 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800707 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800708
709 if (payload_state->ShouldBackoffDownload()) {
710 output_object.update_exists = false;
711 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
712 "attempts";
713 completer.set_code(kActionCodeOmahaUpdateDeferredForBackoff);
714 return;
715 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000716}
717
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700718bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700719 // We should defer the downloads only if we've first satisfied the
720 // wall-clock-based-waiting period and then the update-check-based waiting
721 // period, if required.
722
723 if (!params_->wall_clock_based_wait_enabled) {
724 // Wall-clock-based waiting period is not enabled, so no scattering needed.
725 return false;
726 }
727
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700728 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700729 case kWallClockWaitNotSatisfied:
730 // We haven't even satisfied the first condition, passing the
731 // wall-clock-based waiting period, so we should defer the downloads
732 // until that happens.
733 LOG(INFO) << "wall-clock-based-wait not satisfied.";
734 return true;
735
736 case kWallClockWaitDoneButUpdateCheckWaitRequired:
737 LOG(INFO) << "wall-clock-based-wait satisfied and "
738 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700739 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700740
741 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
742 // Wall-clock-based waiting period is satisfied, and it's determined
743 // that we do not need the update-check-based wait. so no need to
744 // defer downloads.
745 LOG(INFO) << "wall-clock-based-wait satisfied and "
746 << "update-check-based-wait is not required.";
747 return false;
748
749 default:
750 // Returning false for this default case so we err on the
751 // side of downloading updates than deferring in case of any bugs.
752 NOTREACHED();
753 return false;
754 }
755}
756
757OmahaRequestAction::WallClockWaitResult
758OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700759 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700760 Time update_first_seen_at;
761 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700762
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800763 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
764 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
765 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700766 // Note: This timestamp could be that of ANY update we saw in the past
767 // (not necessarily this particular update we're considering to apply)
768 // but never got to apply because of some reason (e.g. stop AU policy,
769 // updates being pulled out from Omaha, changes in target version prefix,
770 // new update being rolled out, etc.). But for the purposes of scattering
771 // it doesn't matter which update the timestamp corresponds to. i.e.
772 // the clock starts ticking the first time we see an update and we're
773 // ready to apply when the random wait period is satisfied relative to
774 // that first seen timestamp.
775 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
776 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
777 << utils::ToString(update_first_seen_at);
778 } else {
779 // This seems like an unexpected error where the persisted value exists
780 // but it's not readable for some reason. Just skip scattering in this
781 // case to be safe.
782 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
783 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
784 }
785 } else {
786 update_first_seen_at = Time::Now();
787 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800788 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
789 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700790 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
791 << utils::ToString(update_first_seen_at);
792 }
793 else {
794 // This seems like an unexpected error where the value cannot be
795 // persisted for some reason. Just skip scattering in this
796 // case to be safe.
797 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
798 << utils::ToString(update_first_seen_at)
799 << " cannot be persisted";
800 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
801 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700802 }
803
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700804 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700805 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700806 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700807
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700808 LOG(INFO) << "Waiting Period = "
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700809 << utils::FormatSecs(params_->waiting_period.InSeconds())
810 << ", Time Elapsed = "
811 << utils::FormatSecs(elapsed_time.InSeconds())
812 << ", MaxDaysToScatter = "
813 << max_scatter_period.InDays();
814
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700815 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700816 // The deadline is set for all rules which serve a delta update from a
817 // previous FSI, which means this update will be applied mostly in OOBE
818 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
819 // quickly.
820 LOG(INFO) << "Not scattering as deadline flag is set";
821 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
822 }
823
824 if (max_scatter_period.InDays() == 0) {
825 // This means the Omaha rule creator decides that this rule
826 // should not be scattered irrespective of the policy.
827 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
828 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
829 }
830
831 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700832 // This means we've waited more than the upperbound wait in the rule
833 // from the time we first saw a valid update available to us.
834 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700835 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
836 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
837 }
838
839 // This means we are required to participate in scattering.
840 // See if our turn has arrived now.
841 TimeDelta remaining_wait_time = params_->waiting_period - elapsed_time;
842 if (remaining_wait_time.InSeconds() <= 0) {
843 // Yes, it's our turn now.
844 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
845
846 // But we can't download until the update-check-count-based wait is also
847 // satisfied, so mark it as required now if update checks are enabled.
848 return params_->update_check_count_wait_enabled ?
849 kWallClockWaitDoneButUpdateCheckWaitRequired :
850 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
851 }
852
853 // Not our turn yet, so we have to wait until our turn to
854 // help scatter the downloads across all clients of the enterprise.
855 LOG(INFO) << "Update deferred for another "
856 << utils::FormatSecs(remaining_wait_time.InSeconds())
857 << " per policy.";
858 return kWallClockWaitNotSatisfied;
859}
860
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700861bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700862 int64 update_check_count_value;
863
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800864 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
865 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
866 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700867 // We are unable to read the update check count from file for some reason.
868 // So let's proceed anyway so as to not stall the update.
869 LOG(ERROR) << "Unable to read update check count. "
870 << "Skipping update-check-count-based-wait.";
871 return true;
872 }
873 } else {
874 // This file does not exist. This means we haven't started our update
875 // check count down yet, so this is the right time to start the count down.
876 update_check_count_value = base::RandInt(
877 params_->min_update_checks_needed,
878 params_->max_update_checks_allowed);
879
880 LOG(INFO) << "Randomly picked update check count value = "
881 << update_check_count_value;
882
883 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800884 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
885 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700886 // We weren't able to write the update check count file for some reason.
887 // So let's proceed anyway so as to not stall the update.
888 LOG(ERROR) << "Unable to write update check count. "
889 << "Skipping update-check-count-based-wait.";
890 return true;
891 }
892 }
893
894 if (update_check_count_value == 0) {
895 LOG(INFO) << "Successfully passed the update-check-based-wait.";
896 return true;
897 }
898
899 if (update_check_count_value < 0 ||
900 update_check_count_value > params_->max_update_checks_allowed) {
901 // We err on the side of skipping scattering logic instead of stalling
902 // a machine from receiving any updates in case of any unexpected state.
903 LOG(ERROR) << "Invalid value for update check count detected. "
904 << "Skipping update-check-count-based-wait.";
905 return true;
906 }
907
908 // Legal value, we need to wait for more update checks to happen
909 // until this becomes 0.
910 LOG(INFO) << "Deferring Omaha updates for another "
911 << update_check_count_value
912 << " update checks per policy";
913 return false;
914}
915
916} // namespace chromeos_update_engine
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700917
918