blob: c98357bb408be4504f58e9e36d96dfe9faf72bc8 [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";
34static const char* kTagDisplayVersion = "DisplayVersion";
35static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
36static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
37// Deprecated: "ManifestSignatureRsa"
38// Deprecated: "ManifestSize"
39static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
40static const char* kTagMetadataSize = "MetadataSize";
41static const char* kTagMoreInfo = "MoreInfo";
42static const char* kTagNeedsAdmin = "needsadmin";
43static const char* kTagPrompt = "Prompt";
44static const char* kTagSha256 = "sha256";
45
rspangler@google.com49fdf182009-10-10 00:57:34 +000046namespace {
47
48const string kGupdateVersion("ChromeOSUpdateEngine-0.1.0.0");
49
50// This is handy for passing strings into libxml2
51#define ConstXMLStr(x) (reinterpret_cast<const xmlChar*>(x))
52
53// These are for scoped_ptr_malloc, which is like scoped_ptr, but allows
54// a custom free() function to be specified.
55class ScopedPtrXmlDocFree {
56 public:
57 inline void operator()(void* x) const {
58 xmlFreeDoc(reinterpret_cast<xmlDoc*>(x));
59 }
60};
61class ScopedPtrXmlFree {
62 public:
63 inline void operator()(void* x) const {
64 xmlFree(x);
65 }
66};
67class ScopedPtrXmlXPathObjectFree {
68 public:
69 inline void operator()(void* x) const {
70 xmlXPathFreeObject(reinterpret_cast<xmlXPathObject*>(x));
71 }
72};
73class ScopedPtrXmlXPathContextFree {
74 public:
75 inline void operator()(void* x) const {
76 xmlXPathFreeContext(reinterpret_cast<xmlXPathContext*>(x));
77 }
78};
79
Darin Petkov1cbd78f2010-07-29 12:38:34 -070080// Returns true if |ping_days| has a value that needs to be sent,
81// false otherwise.
82bool ShouldPing(int ping_days) {
83 return ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged;
84}
85
86// Returns an XML ping element attribute assignment with attribute
87// |name| and value |ping_days| if |ping_days| has a value that needs
88// to be sent, or an empty string otherwise.
89string GetPingAttribute(const string& name, int ping_days) {
90 if (ShouldPing(ping_days)) {
91 return StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
92 }
93 return "";
94}
95
96// Returns an XML ping element if any of the elapsed days need to be
97// sent, or an empty string otherwise.
98string GetPingBody(int ping_active_days, int ping_roll_call_days) {
99 string ping_active = GetPingAttribute("a", ping_active_days);
100 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
101 if (!ping_active.empty() || !ping_roll_call.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700102 return StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700103 ping_active.c_str(),
104 ping_roll_call.c_str());
105 }
106 return "";
107}
108
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700109string FormatRequest(const OmahaEvent* event,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700110 const OmahaRequestParams& params,
Thieu Le116fda32011-04-19 11:01:54 -0700111 bool ping_only,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700112 int ping_active_days,
Darin Petkov95508da2011-01-05 12:42:29 -0800113 int ping_roll_call_days,
114 PrefsInterface* prefs) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700115 string body;
116 if (event == NULL) {
Thieu Le116fda32011-04-19 11:01:54 -0700117 body = GetPingBody(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700118 if (!ping_only) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700119 // not passing update_disabled to Omaha because we want to
120 // get the update and report with UpdateDeferred result so that
121 // borgmon charts show up updates that are deferred. This is also
122 // the expected behavior when we move to Omaha v3.0 protocol, so it'll
123 // be consistent.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700124 body += StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700125 " <updatecheck"
Jay Srinivasan0a708742012-03-20 11:26:12 -0700126 " targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700127 "></updatecheck>\n",
Jay Srinivasan0a708742012-03-20 11:26:12 -0700128 XmlEncode(params.target_version_prefix).c_str());
129
Darin Petkov265f2902011-05-09 15:17:40 -0700130 // If this is the first update check after a reboot following a previous
131 // update, generate an event containing the previous version number. If
132 // the previous version preference file doesn't exist the event is still
133 // generated with a previous version of 0.0.0.0 -- this is relevant for
134 // older clients or new installs. The previous version event is not sent
135 // for ping-only requests because they come before the client has
136 // rebooted.
137 string prev_version;
138 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
139 prev_version = "0.0.0.0";
140 }
141 if (!prev_version.empty()) {
142 body += StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700143 " <event eventtype=\"%d\" eventresult=\"%d\" "
144 "previousversion=\"%s\"></event>\n",
Darin Petkov265f2902011-05-09 15:17:40 -0700145 OmahaEvent::kTypeUpdateComplete,
146 OmahaEvent::kResultSuccessReboot,
147 XmlEncode(prev_version).c_str());
148 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
149 << "Unable to reset the previous version.";
150 }
Darin Petkov95508da2011-01-05 12:42:29 -0800151 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700152 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800153 // The error code is an optional attribute so append it only if the result
154 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700155 string error_code;
156 if (event->result != OmahaEvent::kResultSuccess) {
Darin Petkov18c7bce2011-06-16 14:07:00 -0700157 error_code = StringPrintf(" errorcode=\"%d\"", event->error_code);
Darin Petkove17f86b2010-07-20 09:12:01 -0700158 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700159 body = StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700160 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700161 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700162 }
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700163 return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700164 "<request protocol=\"3.0\" "
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700165 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
166 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" "
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700167 "ismachine=\"1\">\n"
168 " <os version=\"" + XmlEncode(params.os_version) + "\" platform=\"" +
rspangler@google.com49fdf182009-10-10 00:57:34 +0000169 XmlEncode(params.os_platform) + "\" sp=\"" +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700170 XmlEncode(params.os_sp) + "\"></os>\n"
171 " <app appid=\"" + XmlEncode(params.app_id) + "\" version=\"" +
rspangler@google.com49fdf182009-10-10 00:57:34 +0000172 XmlEncode(params.app_version) + "\" "
173 "lang=\"" + XmlEncode(params.app_lang) + "\" track=\"" +
Andrew de los Reyes37c20322010-06-30 13:27:19 -0700174 XmlEncode(params.app_track) + "\" board=\"" +
Darin Petkovfbb40092010-07-29 17:05:50 -0700175 XmlEncode(params.os_board) + "\" hardware_class=\"" +
176 XmlEncode(params.hardware_class) + "\" delta_okay=\"" +
Andrew de los Reyes3f0303a2010-07-15 22:35:35 -0700177 (params.delta_okay ? "true" : "false") + "\">\n" + body +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700178 " </app>\n"
179 "</request>\n";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000180}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700181
rspangler@google.com49fdf182009-10-10 00:57:34 +0000182} // namespace {}
183
184// Encodes XML entities in a given string with libxml2. input must be
185// UTF-8 formatted. Output will be UTF-8 formatted.
186string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700187 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
188 // // cpu, considering creating one and caching it.
189 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
190 // xmlNewDoc(ConstXMLStr("1.0")));
191 // if (!xml_doc.get()) {
192 // LOG(ERROR) << "Unable to create xmlDoc";
193 // return "";
194 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000195 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
196 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
197 return string(reinterpret_cast<const char *>(str.get()));
198}
199
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800200OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700201 OmahaRequestParams* params,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700202 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700203 HttpFetcher* http_fetcher,
204 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800205 : system_state_(system_state),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700206 params_(params),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700207 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700208 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700209 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700210 ping_active_days_(0),
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700211 ping_roll_call_days_(0) {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000212
Darin Petkov6a5b3222010-07-13 14:55:28 -0700213OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000214
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700215// Calculates the value to use for the ping days parameter.
216int OmahaRequestAction::CalculatePingDays(const string& key) {
217 int days = kNeverPinged;
218 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800219 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700220 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
221 if (days < 0) {
222 // If |days| is negative, then the system clock must have jumped
223 // back in time since the ping was sent. Mark the value so that
224 // it doesn't get sent to the server but we still update the
225 // last ping daystart preference. This way the next ping time
226 // will be correct, hopefully.
227 days = kPingTimeJump;
228 LOG(WARNING) <<
229 "System clock jumped back in time. Resetting ping daystarts.";
230 }
231 }
232 return days;
233}
234
235void OmahaRequestAction::InitPingDays() {
236 // We send pings only along with update checks, not with events.
237 if (IsEvent()) {
238 return;
239 }
240 // TODO(petkov): Figure a way to distinguish active use pings
241 // vs. roll call pings. Currently, the two pings are identical. A
242 // fix needs to change this code as well as UpdateLastPingDays.
243 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
244 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
245}
246
Darin Petkov6a5b3222010-07-13 14:55:28 -0700247void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000248 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700249 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700250 if (ping_only_ &&
251 !ShouldPing(ping_active_days_) &&
252 !ShouldPing(ping_roll_call_days_)) {
253 processor_->ActionComplete(this, kActionCodeSuccess);
254 return;
255 }
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700256 string request_post(FormatRequest(event_.get(),
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700257 *params_,
Thieu Le116fda32011-04-19 11:01:54 -0700258 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700259 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800260 ping_roll_call_days_,
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800261 system_state_->prefs()));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700262
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800263 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
264 kHttpContentTypeTextXml);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700265 LOG(INFO) << "Posting an Omaha request to " << params_->update_url;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700266 LOG(INFO) << "Request: " << request_post;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700267 http_fetcher_->BeginTransfer(params_->update_url);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000268}
269
Darin Petkov6a5b3222010-07-13 14:55:28 -0700270void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000271 http_fetcher_->TerminateTransfer();
272}
273
274// We just store the response in the buffer. Once we've received all bytes,
275// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700276void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
277 const char* bytes,
278 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000279 response_buffer_.reserve(response_buffer_.size() + length);
280 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
281}
282
283namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000284// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
285// on the returned object.
286// This code is roughly based on the libxml tutorial at:
287// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700288xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000289 xmlXPathObject* result = NULL;
290
291 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
292 xmlXPathNewContext(doc));
293 if (!context.get()) {
294 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
295 return NULL;
296 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000297
298 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000299 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700300 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000301 return NULL;
302 }
303 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700304 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000305 xmlXPathFreeObject(result);
306 return NULL;
307 }
308 return result;
309}
310
311// Returns the string value of a named attribute on a node, or empty string
312// if no such node exists. If the attribute exists and has a value of
313// empty string, there's no way to distinguish that from the attribute
314// not existing.
315string XmlGetProperty(xmlNode* node, const char* name) {
316 if (!xmlHasProp(node, ConstXMLStr(name)))
317 return "";
318 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
319 xmlGetProp(node, ConstXMLStr(name)));
320 string ret(reinterpret_cast<const char *>(str.get()));
321 return ret;
322}
323
324// Parses a 64 bit base-10 int from a string and returns it. Returns 0
325// on error. If the string contains "0", that's indistinguishable from
326// error.
327off_t ParseInt(const string& str) {
328 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700329 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000330 if (rc < 1) {
331 // failure
332 return 0;
333 }
334 return ret;
335}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700336
337// Update the last ping day preferences based on the server daystart
338// response. Returns true on success, false otherwise.
339bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700340 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700341
342 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700343 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700344 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
345 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
346 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
347 xmlNode* daystart_node = nodeset->nodeTab[0];
348 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
349 ConstXMLStr("elapsed_seconds")));
350
351 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700352 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
353 "elapsed_seconds"),
354 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700355 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
356
357 // Remember the local time that matches the server's last midnight
358 // time.
359 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
360 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
361 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
362 return true;
363}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000364} // namespace {}
365
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700366bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
367 OmahaResponse* output_object,
368 ScopedActionCompleter* completer) {
369 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
370
371 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
372 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
373 if (!xpath_nodeset.get()) {
374 completer->set_code(kActionCodeOmahaResponseInvalid);
375 return false;
376 }
377
378 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
379 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
380 CHECK_GE(nodeset->nodeNr, 1);
381 xmlNode* update_check_node = nodeset->nodeTab[0];
382
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800383 // chromium-os:37289: The PollInterval is not supported by Omaha server
384 // currently. But still keeping this existing code in case we ever decide to
385 // slow down the request rate from the server-side. Note that the
386 // PollInterval is not persisted, so it has to be sent by the server on every
387 // response to guarantee that the UpdateCheckScheduler uses this value
388 // (otherwise, if the device got rebooted after the last server-indicated
389 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
390 // value for the scattering logic is based on the assumption that we perform
391 // an update check every hour so that the max value of 8 will roughly be
392 // equivalent to one work day. If we decide to use PollInterval permanently,
393 // we should update the max_update_checks_allowed to take PollInterval into
394 // account. Note: The parsing for PollInterval happens even before parsing
395 // of the status because we may want to specify the PollInterval even when
396 // there's no update.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700397 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
398 &output_object->poll_interval);
399
400 if (!ParseStatus(update_check_node, output_object, completer))
401 return false;
402
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800403 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
404 // appends the package name to the URLs populated in this method.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700405 if (!ParseUrls(doc, output_object, completer))
406 return false;
407
408 if (!ParsePackage(doc, output_object, completer))
409 return false;
410
411 if (!ParseParams(doc, output_object, completer))
412 return false;
413
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800414 output_object->update_exists = true;
415 SetOutputObject(*output_object);
416 completer->set_code(kActionCodeSuccess);
417
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700418 return true;
419}
420
421bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
422 OmahaResponse* output_object,
423 ScopedActionCompleter* completer) {
424 // Get status.
425 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
426 LOG(ERROR) << "Omaha Response missing status";
427 completer->set_code(kActionCodeOmahaResponseInvalid);
428 return false;
429 }
430
431 const string status(XmlGetProperty(update_check_node, "status"));
432 if (status == "noupdate") {
433 LOG(INFO) << "No update.";
434 output_object->update_exists = false;
435 SetOutputObject(*output_object);
436 completer->set_code(kActionCodeSuccess);
437 return false;
438 }
439
440 if (status != "ok") {
441 LOG(ERROR) << "Unknown Omaha response status: " << status;
442 completer->set_code(kActionCodeOmahaResponseInvalid);
443 return false;
444 }
445
446 return true;
447}
448
449bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
450 OmahaResponse* output_object,
451 ScopedActionCompleter* completer) {
452 // Get the update URL.
453 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
454
455 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
456 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
457 if (!xpath_nodeset.get()) {
458 completer->set_code(kActionCodeOmahaResponseInvalid);
459 return false;
460 }
461
462 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
463 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
464 CHECK_GE(nodeset->nodeNr, 1);
465
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800466 LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)";
467 output_object->payload_urls.clear();
468 for (int i = 0; i < nodeset->nodeNr; i++) {
469 xmlNode* url_node = nodeset->nodeTab[i];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700470
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800471 const string codebase(XmlGetProperty(url_node, "codebase"));
472 if (codebase.empty()) {
473 LOG(ERROR) << "Omaha Response URL has empty codebase";
474 completer->set_code(kActionCodeOmahaResponseInvalid);
475 return false;
476 }
477 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700478 }
479
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700480 return true;
481}
482
483bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
484 OmahaResponse* output_object,
485 ScopedActionCompleter* completer) {
486 // Get the package node.
487 static const char* kPackageNodeXPath(
488 "/response/app/updatecheck/manifest/packages/package");
489
490 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
491 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
492 if (!xpath_nodeset.get()) {
493 completer->set_code(kActionCodeOmahaResponseInvalid);
494 return false;
495 }
496
497 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
498 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
499 CHECK_GE(nodeset->nodeNr, 1);
500
501 // We only care about the first package.
502 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
503 xmlNode* package_node = nodeset->nodeTab[0];
504
505 // Get package properties one by one.
506
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800507 // Parse the payload name to be appended to the base Url value.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700508 const string package_name(XmlGetProperty(package_node, "name"));
509 LOG(INFO) << "Omaha Response package name = " << package_name;
510 if (package_name.empty()) {
511 LOG(ERROR) << "Omaha Response has empty package name";
512 completer->set_code(kActionCodeOmahaResponseInvalid);
513 return false;
514 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800515
516 // Append the package name to each URL in our list so that we don't
517 // propagate the urlBase vs packageName distinctions beyond this point.
518 // From now on, we only need to use payload_urls.
519 for (size_t i = 0; i < output_object->payload_urls.size(); i++) {
520 output_object->payload_urls[i] += package_name;
521 LOG(INFO) << "Url" << i << ": " << output_object->payload_urls[i];
522 }
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700523
524 // Parse the payload size.
525 off_t size = ParseInt(XmlGetProperty(package_node, "size"));
526 if (size <= 0) {
527 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
528 completer->set_code(kActionCodeOmahaResponseInvalid);
529 return false;
530 }
531 output_object->size = size;
532
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800533 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700534
535 return true;
536}
537
538bool OmahaRequestAction::ParseParams(xmlDoc* doc,
539 OmahaResponse* output_object,
540 ScopedActionCompleter* completer) {
541 // Get the action node where parameters are present.
542 static const char* kActionNodeXPath(
543 "/response/app/updatecheck/manifest/actions/action");
544
545 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
546 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
547 if (!xpath_nodeset.get()) {
548 completer->set_code(kActionCodeOmahaResponseInvalid);
549 return false;
550 }
551
552 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
553 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
554
555 // We only care about the action that has event "postinall", because this is
556 // where Omaha puts all the generic name/value pairs in the rule.
557 LOG(INFO) << "Found " << nodeset->nodeNr
558 << " action(s). Processing the postinstall action.";
559
560 // pie_action_node holds the action node corresponding to the
561 // postinstall event action, if present.
562 xmlNode* pie_action_node = NULL;
563 for (int i = 0; i < nodeset->nodeNr; i++) {
564 xmlNode* action_node = nodeset->nodeTab[i];
565 if (XmlGetProperty(action_node, "event") == "postinstall") {
566 pie_action_node = action_node;
567 break;
568 }
569 }
570
571 if (!pie_action_node) {
572 LOG(ERROR) << "Omaha Response has no postinstall event action";
573 completer->set_code(kActionCodeOmahaResponseInvalid);
574 return false;
575 }
576
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800577 output_object->hash = XmlGetProperty(pie_action_node, kTagSha256);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700578 if (output_object->hash.empty()) {
579 LOG(ERROR) << "Omaha Response has empty sha256 value";
580 completer->set_code(kActionCodeOmahaResponseInvalid);
581 return false;
582 }
583
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800584 // Get the optional properties one by one.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700585 output_object->display_version =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800586 XmlGetProperty(pie_action_node, kTagDisplayVersion);
587 output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700588 output_object->metadata_size =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800589 ParseInt(XmlGetProperty(pie_action_node, kTagMetadataSize));
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700590 output_object->metadata_signature =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800591 XmlGetProperty(pie_action_node, kTagMetadataSignatureRsa);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700592 output_object->needs_admin =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800593 XmlGetProperty(pie_action_node, kTagNeedsAdmin) == "true";
594 output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true";
595 output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700596 output_object->max_days_to_scatter =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800597 ParseInt(XmlGetProperty(pie_action_node, kTagMaxDaysToScatter));
598
599 string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl);
600 if (!base::StringToInt(max, &output_object->max_failure_count_per_url))
601 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700602
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700603 return true;
604}
605
rspangler@google.com49fdf182009-10-10 00:57:34 +0000606// If the transfer was successful, this uses libxml2 to parse the response
607// and fill in the appropriate fields of the output object. Also, notifies
608// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700609void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
610 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000611 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800612 string current_response(response_buffer_.begin(), response_buffer_.end());
613 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700614
615 // Events are best effort transactions -- assume they always succeed.
616 if (IsEvent()) {
617 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800618 if (event_->result == OmahaEvent::kResultError && successful &&
619 utils::IsOfficialBuild()) {
620 LOG(INFO) << "Signalling Crash Reporter.";
621 utils::ScheduleCrashReporterUpload();
622 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700623 completer.set_code(kActionCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700624 return;
625 }
626
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700627 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700628 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700629 int code = GetHTTPResponseCode();
630 // Makes sure we send sane error values.
631 if (code < 0 || code >= 1000) {
632 code = 999;
633 }
634 completer.set_code(static_cast<ActionExitCode>(
635 kActionCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000636 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700637 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000638
639 // parse our response and fill the fields in the output object
640 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
641 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
642 if (!doc.get()) {
643 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700644 completer.set_code(response_buffer_.empty() ?
645 kActionCodeOmahaRequestEmptyResponseError :
646 kActionCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000647 return;
648 }
649
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700650 // If a ping was sent, update the last ping day preferences based on
651 // the server daystart response.
652 if (ShouldPing(ping_active_days_) ||
653 ShouldPing(ping_roll_call_days_) ||
654 ping_active_days_ == kPingTimeJump ||
655 ping_roll_call_days_ == kPingTimeJump) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800656 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700657 << "Failed to update the last ping day preferences!";
658 }
659
Thieu Le116fda32011-04-19 11:01:54 -0700660 if (!HasOutputPipe()) {
661 // Just set success to whether or not the http transfer succeeded,
662 // which must be true at this point in the code.
663 completer.set_code(kActionCodeSuccess);
664 return;
665 }
666
Darin Petkov6a5b3222010-07-13 14:55:28 -0700667 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700668 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000669 return;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000670
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700671 if (params_->update_disabled) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700672 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700673 output_object.update_exists = false;
Jay Srinivasan0a708742012-03-20 11:26:12 -0700674 completer.set_code(kActionCodeOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700675 // Note: We could technically delete the UpdateFirstSeenAt state here.
676 // If we do, it'll mean a device has to restart the UpdateFirstSeenAt
677 // and thus help scattering take effect when the AU is turned on again.
678 // On the other hand, it also increases the chance of update starvation if
679 // an admin turns AU on/off more frequently. We choose to err on the side
680 // of preventing starvation at the cost of not applying scattering in
681 // those cases.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700682 return;
683 }
684
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700685 if (ShouldDeferDownload(&output_object)) {
686 output_object.update_exists = false;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700687 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
688 completer.set_code(kActionCodeOmahaUpdateDeferredPerPolicy);
689 return;
690 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800691
692 // Update the payload state with the current response. The payload state
693 // will automatically reset all stale state if this response is different
694 // from what's stored already.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800695 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800696 payload_state->SetResponse(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000697}
698
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700699bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700700 // We should defer the downloads only if we've first satisfied the
701 // wall-clock-based-waiting period and then the update-check-based waiting
702 // period, if required.
703
704 if (!params_->wall_clock_based_wait_enabled) {
705 // Wall-clock-based waiting period is not enabled, so no scattering needed.
706 return false;
707 }
708
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700709 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700710 case kWallClockWaitNotSatisfied:
711 // We haven't even satisfied the first condition, passing the
712 // wall-clock-based waiting period, so we should defer the downloads
713 // until that happens.
714 LOG(INFO) << "wall-clock-based-wait not satisfied.";
715 return true;
716
717 case kWallClockWaitDoneButUpdateCheckWaitRequired:
718 LOG(INFO) << "wall-clock-based-wait satisfied and "
719 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700720 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700721
722 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
723 // Wall-clock-based waiting period is satisfied, and it's determined
724 // that we do not need the update-check-based wait. so no need to
725 // defer downloads.
726 LOG(INFO) << "wall-clock-based-wait satisfied and "
727 << "update-check-based-wait is not required.";
728 return false;
729
730 default:
731 // Returning false for this default case so we err on the
732 // side of downloading updates than deferring in case of any bugs.
733 NOTREACHED();
734 return false;
735 }
736}
737
738OmahaRequestAction::WallClockWaitResult
739OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700740 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700741 Time update_first_seen_at;
742 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700743
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800744 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
745 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
746 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700747 // Note: This timestamp could be that of ANY update we saw in the past
748 // (not necessarily this particular update we're considering to apply)
749 // but never got to apply because of some reason (e.g. stop AU policy,
750 // updates being pulled out from Omaha, changes in target version prefix,
751 // new update being rolled out, etc.). But for the purposes of scattering
752 // it doesn't matter which update the timestamp corresponds to. i.e.
753 // the clock starts ticking the first time we see an update and we're
754 // ready to apply when the random wait period is satisfied relative to
755 // that first seen timestamp.
756 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
757 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
758 << utils::ToString(update_first_seen_at);
759 } else {
760 // This seems like an unexpected error where the persisted value exists
761 // but it's not readable for some reason. Just skip scattering in this
762 // case to be safe.
763 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
764 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
765 }
766 } else {
767 update_first_seen_at = Time::Now();
768 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800769 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
770 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700771 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
772 << utils::ToString(update_first_seen_at);
773 }
774 else {
775 // This seems like an unexpected error where the value cannot be
776 // persisted for some reason. Just skip scattering in this
777 // case to be safe.
778 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
779 << utils::ToString(update_first_seen_at)
780 << " cannot be persisted";
781 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
782 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700783 }
784
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700785 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700786 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700787 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700788
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700789 LOG(INFO) << "Waiting Period = "
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700790 << utils::FormatSecs(params_->waiting_period.InSeconds())
791 << ", Time Elapsed = "
792 << utils::FormatSecs(elapsed_time.InSeconds())
793 << ", MaxDaysToScatter = "
794 << max_scatter_period.InDays();
795
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700796 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700797 // The deadline is set for all rules which serve a delta update from a
798 // previous FSI, which means this update will be applied mostly in OOBE
799 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
800 // quickly.
801 LOG(INFO) << "Not scattering as deadline flag is set";
802 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
803 }
804
805 if (max_scatter_period.InDays() == 0) {
806 // This means the Omaha rule creator decides that this rule
807 // should not be scattered irrespective of the policy.
808 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
809 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
810 }
811
812 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700813 // This means we've waited more than the upperbound wait in the rule
814 // from the time we first saw a valid update available to us.
815 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700816 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
817 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
818 }
819
820 // This means we are required to participate in scattering.
821 // See if our turn has arrived now.
822 TimeDelta remaining_wait_time = params_->waiting_period - elapsed_time;
823 if (remaining_wait_time.InSeconds() <= 0) {
824 // Yes, it's our turn now.
825 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
826
827 // But we can't download until the update-check-count-based wait is also
828 // satisfied, so mark it as required now if update checks are enabled.
829 return params_->update_check_count_wait_enabled ?
830 kWallClockWaitDoneButUpdateCheckWaitRequired :
831 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
832 }
833
834 // Not our turn yet, so we have to wait until our turn to
835 // help scatter the downloads across all clients of the enterprise.
836 LOG(INFO) << "Update deferred for another "
837 << utils::FormatSecs(remaining_wait_time.InSeconds())
838 << " per policy.";
839 return kWallClockWaitNotSatisfied;
840}
841
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700842bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700843 int64 update_check_count_value;
844
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800845 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
846 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
847 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700848 // We are unable to read the update check count from file for some reason.
849 // So let's proceed anyway so as to not stall the update.
850 LOG(ERROR) << "Unable to read update check count. "
851 << "Skipping update-check-count-based-wait.";
852 return true;
853 }
854 } else {
855 // This file does not exist. This means we haven't started our update
856 // check count down yet, so this is the right time to start the count down.
857 update_check_count_value = base::RandInt(
858 params_->min_update_checks_needed,
859 params_->max_update_checks_allowed);
860
861 LOG(INFO) << "Randomly picked update check count value = "
862 << update_check_count_value;
863
864 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800865 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
866 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700867 // We weren't able to write the update check count file for some reason.
868 // So let's proceed anyway so as to not stall the update.
869 LOG(ERROR) << "Unable to write update check count. "
870 << "Skipping update-check-count-based-wait.";
871 return true;
872 }
873 }
874
875 if (update_check_count_value == 0) {
876 LOG(INFO) << "Successfully passed the update-check-based-wait.";
877 return true;
878 }
879
880 if (update_check_count_value < 0 ||
881 update_check_count_value > params_->max_update_checks_allowed) {
882 // We err on the side of skipping scattering logic instead of stalling
883 // a machine from receiving any updates in case of any unexpected state.
884 LOG(ERROR) << "Invalid value for update check count detected. "
885 << "Skipping update-check-count-based-wait.";
886 return true;
887 }
888
889 // Legal value, we need to wait for more update checks to happen
890 // until this becomes 0.
891 LOG(INFO) << "Deferring Omaha updates for another "
892 << update_check_count_value
893 << " update checks per policy";
894 return false;
895}
896
897} // namespace chromeos_update_engine
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700898
899