blob: e9943355d12af62129ef45f0ce9842803ba39ed4 [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",
Jay Srinivasan0a708742012-03-20 11:26:12 -0700132 XmlEncode(params.target_version_prefix).c_str());
133
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) + "\" "
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700171 "ismachine=\"1\">\n"
172 " <os version=\"" + XmlEncode(params.os_version) + "\" platform=\"" +
rspangler@google.com49fdf182009-10-10 00:57:34 +0000173 XmlEncode(params.os_platform) + "\" sp=\"" +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700174 XmlEncode(params.os_sp) + "\"></os>\n"
175 " <app appid=\"" + XmlEncode(params.app_id) + "\" version=\"" +
rspangler@google.com49fdf182009-10-10 00:57:34 +0000176 XmlEncode(params.app_version) + "\" "
177 "lang=\"" + XmlEncode(params.app_lang) + "\" track=\"" +
Andrew de los Reyes37c20322010-06-30 13:27:19 -0700178 XmlEncode(params.app_track) + "\" board=\"" +
Darin Petkovfbb40092010-07-29 17:05:50 -0700179 XmlEncode(params.os_board) + "\" hardware_class=\"" +
180 XmlEncode(params.hardware_class) + "\" delta_okay=\"" +
Andrew de los Reyes3f0303a2010-07-15 22:35:35 -0700181 (params.delta_okay ? "true" : "false") + "\">\n" + body +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700182 " </app>\n"
183 "</request>\n";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000184}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700185
rspangler@google.com49fdf182009-10-10 00:57:34 +0000186} // namespace {}
187
188// Encodes XML entities in a given string with libxml2. input must be
189// UTF-8 formatted. Output will be UTF-8 formatted.
190string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700191 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
192 // // cpu, considering creating one and caching it.
193 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
194 // xmlNewDoc(ConstXMLStr("1.0")));
195 // if (!xml_doc.get()) {
196 // LOG(ERROR) << "Unable to create xmlDoc";
197 // return "";
198 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000199 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
200 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
201 return string(reinterpret_cast<const char *>(str.get()));
202}
203
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800204OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700205 OmahaRequestParams* params,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700206 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700207 HttpFetcher* http_fetcher,
208 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800209 : system_state_(system_state),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700210 params_(params),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700211 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700212 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700213 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700214 ping_active_days_(0),
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700215 ping_roll_call_days_(0) {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000216
Darin Petkov6a5b3222010-07-13 14:55:28 -0700217OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000218
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700219// Calculates the value to use for the ping days parameter.
220int OmahaRequestAction::CalculatePingDays(const string& key) {
221 int days = kNeverPinged;
222 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800223 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700224 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
225 if (days < 0) {
226 // If |days| is negative, then the system clock must have jumped
227 // back in time since the ping was sent. Mark the value so that
228 // it doesn't get sent to the server but we still update the
229 // last ping daystart preference. This way the next ping time
230 // will be correct, hopefully.
231 days = kPingTimeJump;
232 LOG(WARNING) <<
233 "System clock jumped back in time. Resetting ping daystarts.";
234 }
235 }
236 return days;
237}
238
239void OmahaRequestAction::InitPingDays() {
240 // We send pings only along with update checks, not with events.
241 if (IsEvent()) {
242 return;
243 }
244 // TODO(petkov): Figure a way to distinguish active use pings
245 // vs. roll call pings. Currently, the two pings are identical. A
246 // fix needs to change this code as well as UpdateLastPingDays.
247 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
248 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
249}
250
Darin Petkov6a5b3222010-07-13 14:55:28 -0700251void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000252 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700253 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700254 if (ping_only_ &&
255 !ShouldPing(ping_active_days_) &&
256 !ShouldPing(ping_roll_call_days_)) {
257 processor_->ActionComplete(this, kActionCodeSuccess);
258 return;
259 }
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700260 string request_post(FormatRequest(event_.get(),
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700261 *params_,
Thieu Le116fda32011-04-19 11:01:54 -0700262 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700263 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800264 ping_roll_call_days_,
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800265 system_state_->prefs()));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700266
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800267 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
268 kHttpContentTypeTextXml);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700269 LOG(INFO) << "Posting an Omaha request to " << params_->update_url;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700270 LOG(INFO) << "Request: " << request_post;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700271 http_fetcher_->BeginTransfer(params_->update_url);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000272}
273
Darin Petkov6a5b3222010-07-13 14:55:28 -0700274void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000275 http_fetcher_->TerminateTransfer();
276}
277
278// We just store the response in the buffer. Once we've received all bytes,
279// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700280void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
281 const char* bytes,
282 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000283 response_buffer_.reserve(response_buffer_.size() + length);
284 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
285}
286
287namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000288// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
289// on the returned object.
290// This code is roughly based on the libxml tutorial at:
291// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700292xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000293 xmlXPathObject* result = NULL;
294
295 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
296 xmlXPathNewContext(doc));
297 if (!context.get()) {
298 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
299 return NULL;
300 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000301
302 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000303 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700304 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000305 return NULL;
306 }
307 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700308 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000309 xmlXPathFreeObject(result);
310 return NULL;
311 }
312 return result;
313}
314
315// Returns the string value of a named attribute on a node, or empty string
316// if no such node exists. If the attribute exists and has a value of
317// empty string, there's no way to distinguish that from the attribute
318// not existing.
319string XmlGetProperty(xmlNode* node, const char* name) {
320 if (!xmlHasProp(node, ConstXMLStr(name)))
321 return "";
322 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
323 xmlGetProp(node, ConstXMLStr(name)));
324 string ret(reinterpret_cast<const char *>(str.get()));
325 return ret;
326}
327
328// Parses a 64 bit base-10 int from a string and returns it. Returns 0
329// on error. If the string contains "0", that's indistinguishable from
330// error.
331off_t ParseInt(const string& str) {
332 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700333 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000334 if (rc < 1) {
335 // failure
336 return 0;
337 }
338 return ret;
339}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700340
341// Update the last ping day preferences based on the server daystart
342// response. Returns true on success, false otherwise.
343bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700344 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700345
346 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700347 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700348 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
349 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
350 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
351 xmlNode* daystart_node = nodeset->nodeTab[0];
352 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
353 ConstXMLStr("elapsed_seconds")));
354
355 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700356 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
357 "elapsed_seconds"),
358 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700359 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
360
361 // Remember the local time that matches the server's last midnight
362 // time.
363 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
364 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
365 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
366 return true;
367}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000368} // namespace {}
369
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700370bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
371 OmahaResponse* output_object,
372 ScopedActionCompleter* completer) {
373 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
374
375 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
376 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
377 if (!xpath_nodeset.get()) {
378 completer->set_code(kActionCodeOmahaResponseInvalid);
379 return false;
380 }
381
382 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
383 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
384 CHECK_GE(nodeset->nodeNr, 1);
385 xmlNode* update_check_node = nodeset->nodeTab[0];
386
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800387 // chromium-os:37289: The PollInterval is not supported by Omaha server
388 // currently. But still keeping this existing code in case we ever decide to
389 // slow down the request rate from the server-side. Note that the
390 // PollInterval is not persisted, so it has to be sent by the server on every
391 // response to guarantee that the UpdateCheckScheduler uses this value
392 // (otherwise, if the device got rebooted after the last server-indicated
393 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
394 // value for the scattering logic is based on the assumption that we perform
395 // an update check every hour so that the max value of 8 will roughly be
396 // equivalent to one work day. If we decide to use PollInterval permanently,
397 // we should update the max_update_checks_allowed to take PollInterval into
398 // account. Note: The parsing for PollInterval happens even before parsing
399 // of the status because we may want to specify the PollInterval even when
400 // there's no update.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700401 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
402 &output_object->poll_interval);
403
404 if (!ParseStatus(update_check_node, output_object, completer))
405 return false;
406
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800407 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
408 // appends the package name to the URLs populated in this method.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700409 if (!ParseUrls(doc, output_object, completer))
410 return false;
411
412 if (!ParsePackage(doc, output_object, completer))
413 return false;
414
415 if (!ParseParams(doc, output_object, completer))
416 return false;
417
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800418 output_object->update_exists = true;
419 SetOutputObject(*output_object);
420 completer->set_code(kActionCodeSuccess);
421
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700422 return true;
423}
424
425bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
426 OmahaResponse* output_object,
427 ScopedActionCompleter* completer) {
428 // Get status.
429 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
430 LOG(ERROR) << "Omaha Response missing status";
431 completer->set_code(kActionCodeOmahaResponseInvalid);
432 return false;
433 }
434
435 const string status(XmlGetProperty(update_check_node, "status"));
436 if (status == "noupdate") {
437 LOG(INFO) << "No update.";
438 output_object->update_exists = false;
439 SetOutputObject(*output_object);
440 completer->set_code(kActionCodeSuccess);
441 return false;
442 }
443
444 if (status != "ok") {
445 LOG(ERROR) << "Unknown Omaha response status: " << status;
446 completer->set_code(kActionCodeOmahaResponseInvalid);
447 return false;
448 }
449
450 return true;
451}
452
453bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
454 OmahaResponse* output_object,
455 ScopedActionCompleter* completer) {
456 // Get the update URL.
457 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
458
459 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
460 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
461 if (!xpath_nodeset.get()) {
462 completer->set_code(kActionCodeOmahaResponseInvalid);
463 return false;
464 }
465
466 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
467 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
468 CHECK_GE(nodeset->nodeNr, 1);
469
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800470 LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)";
471 output_object->payload_urls.clear();
472 for (int i = 0; i < nodeset->nodeNr; i++) {
473 xmlNode* url_node = nodeset->nodeTab[i];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700474
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800475 const string codebase(XmlGetProperty(url_node, "codebase"));
476 if (codebase.empty()) {
477 LOG(ERROR) << "Omaha Response URL has empty codebase";
478 completer->set_code(kActionCodeOmahaResponseInvalid);
479 return false;
480 }
481 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700482 }
483
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700484 return true;
485}
486
487bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
488 OmahaResponse* output_object,
489 ScopedActionCompleter* completer) {
490 // Get the package node.
491 static const char* kPackageNodeXPath(
492 "/response/app/updatecheck/manifest/packages/package");
493
494 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
495 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
496 if (!xpath_nodeset.get()) {
497 completer->set_code(kActionCodeOmahaResponseInvalid);
498 return false;
499 }
500
501 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
502 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
503 CHECK_GE(nodeset->nodeNr, 1);
504
505 // We only care about the first package.
506 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
507 xmlNode* package_node = nodeset->nodeTab[0];
508
509 // Get package properties one by one.
510
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800511 // Parse the payload name to be appended to the base Url value.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700512 const string package_name(XmlGetProperty(package_node, "name"));
513 LOG(INFO) << "Omaha Response package name = " << package_name;
514 if (package_name.empty()) {
515 LOG(ERROR) << "Omaha Response has empty package name";
516 completer->set_code(kActionCodeOmahaResponseInvalid);
517 return false;
518 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800519
520 // Append the package name to each URL in our list so that we don't
521 // propagate the urlBase vs packageName distinctions beyond this point.
522 // From now on, we only need to use payload_urls.
523 for (size_t i = 0; i < output_object->payload_urls.size(); i++) {
524 output_object->payload_urls[i] += package_name;
525 LOG(INFO) << "Url" << i << ": " << output_object->payload_urls[i];
526 }
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700527
528 // Parse the payload size.
529 off_t size = ParseInt(XmlGetProperty(package_node, "size"));
530 if (size <= 0) {
531 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
532 completer->set_code(kActionCodeOmahaResponseInvalid);
533 return false;
534 }
535 output_object->size = size;
536
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800537 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700538
539 return true;
540}
541
542bool OmahaRequestAction::ParseParams(xmlDoc* doc,
543 OmahaResponse* output_object,
544 ScopedActionCompleter* completer) {
545 // Get the action node where parameters are present.
546 static const char* kActionNodeXPath(
547 "/response/app/updatecheck/manifest/actions/action");
548
549 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
550 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
551 if (!xpath_nodeset.get()) {
552 completer->set_code(kActionCodeOmahaResponseInvalid);
553 return false;
554 }
555
556 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
557 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
558
559 // We only care about the action that has event "postinall", because this is
560 // where Omaha puts all the generic name/value pairs in the rule.
561 LOG(INFO) << "Found " << nodeset->nodeNr
562 << " action(s). Processing the postinstall action.";
563
564 // pie_action_node holds the action node corresponding to the
565 // postinstall event action, if present.
566 xmlNode* pie_action_node = NULL;
567 for (int i = 0; i < nodeset->nodeNr; i++) {
568 xmlNode* action_node = nodeset->nodeTab[i];
569 if (XmlGetProperty(action_node, "event") == "postinstall") {
570 pie_action_node = action_node;
571 break;
572 }
573 }
574
575 if (!pie_action_node) {
576 LOG(ERROR) << "Omaha Response has no postinstall event action";
577 completer->set_code(kActionCodeOmahaResponseInvalid);
578 return false;
579 }
580
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800581 output_object->hash = XmlGetProperty(pie_action_node, kTagSha256);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700582 if (output_object->hash.empty()) {
583 LOG(ERROR) << "Omaha Response has empty sha256 value";
584 completer->set_code(kActionCodeOmahaResponseInvalid);
585 return false;
586 }
587
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800588 // Get the optional properties one by one.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700589 output_object->display_version =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800590 XmlGetProperty(pie_action_node, kTagDisplayVersion);
591 output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700592 output_object->metadata_size =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800593 ParseInt(XmlGetProperty(pie_action_node, kTagMetadataSize));
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700594 output_object->metadata_signature =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800595 XmlGetProperty(pie_action_node, kTagMetadataSignatureRsa);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700596 output_object->needs_admin =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800597 XmlGetProperty(pie_action_node, kTagNeedsAdmin) == "true";
598 output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true";
599 output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700600 output_object->max_days_to_scatter =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800601 ParseInt(XmlGetProperty(pie_action_node, kTagMaxDaysToScatter));
602
603 string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl);
Jay Srinivasan08262882012-12-28 19:29:43 -0800604 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800605 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700606
Jay Srinivasan08262882012-12-28 19:29:43 -0800607 output_object->is_delta_payload =
608 XmlGetProperty(pie_action_node, kTagIsDeltaPayload) == "true";
609
610 output_object->disable_payload_backoff =
611 XmlGetProperty(pie_action_node, kTagDisablePayloadBackoff) == "true";
612
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700613 return true;
614}
615
rspangler@google.com49fdf182009-10-10 00:57:34 +0000616// If the transfer was successful, this uses libxml2 to parse the response
617// and fill in the appropriate fields of the output object. Also, notifies
618// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700619void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
620 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000621 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800622 string current_response(response_buffer_.begin(), response_buffer_.end());
623 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700624
625 // Events are best effort transactions -- assume they always succeed.
626 if (IsEvent()) {
627 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800628 if (event_->result == OmahaEvent::kResultError && successful &&
629 utils::IsOfficialBuild()) {
630 LOG(INFO) << "Signalling Crash Reporter.";
631 utils::ScheduleCrashReporterUpload();
632 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700633 completer.set_code(kActionCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700634 return;
635 }
636
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700637 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700638 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700639 int code = GetHTTPResponseCode();
640 // Makes sure we send sane error values.
641 if (code < 0 || code >= 1000) {
642 code = 999;
643 }
644 completer.set_code(static_cast<ActionExitCode>(
645 kActionCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000646 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700647 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000648
649 // parse our response and fill the fields in the output object
650 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
651 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
652 if (!doc.get()) {
653 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700654 completer.set_code(response_buffer_.empty() ?
655 kActionCodeOmahaRequestEmptyResponseError :
656 kActionCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000657 return;
658 }
659
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700660 // If a ping was sent, update the last ping day preferences based on
661 // the server daystart response.
662 if (ShouldPing(ping_active_days_) ||
663 ShouldPing(ping_roll_call_days_) ||
664 ping_active_days_ == kPingTimeJump ||
665 ping_roll_call_days_ == kPingTimeJump) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800666 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700667 << "Failed to update the last ping day preferences!";
668 }
669
Thieu Le116fda32011-04-19 11:01:54 -0700670 if (!HasOutputPipe()) {
671 // Just set success to whether or not the http transfer succeeded,
672 // which must be true at this point in the code.
673 completer.set_code(kActionCodeSuccess);
674 return;
675 }
676
Darin Petkov6a5b3222010-07-13 14:55:28 -0700677 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700678 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000679 return;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000680
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700681 if (params_->update_disabled) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700682 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700683 output_object.update_exists = false;
Jay Srinivasan0a708742012-03-20 11:26:12 -0700684 completer.set_code(kActionCodeOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700685 // Note: We could technically delete the UpdateFirstSeenAt state here.
686 // If we do, it'll mean a device has to restart the UpdateFirstSeenAt
687 // and thus help scattering take effect when the AU is turned on again.
688 // On the other hand, it also increases the chance of update starvation if
689 // an admin turns AU on/off more frequently. We choose to err on the side
690 // of preventing starvation at the cost of not applying scattering in
691 // those cases.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700692 return;
693 }
694
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700695 if (ShouldDeferDownload(&output_object)) {
696 output_object.update_exists = false;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700697 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
698 completer.set_code(kActionCodeOmahaUpdateDeferredPerPolicy);
699 return;
700 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800701
702 // Update the payload state with the current response. The payload state
703 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800704 // from what's stored already. We are updating the payload state as late
705 // as possible in this method so that if a new release gets pushed and then
706 // got pulled back due to some issues, we don't want to clear our internal
707 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800708 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800709 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800710
711 if (payload_state->ShouldBackoffDownload()) {
712 output_object.update_exists = false;
713 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
714 "attempts";
715 completer.set_code(kActionCodeOmahaUpdateDeferredForBackoff);
716 return;
717 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000718}
719
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700720bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700721 // We should defer the downloads only if we've first satisfied the
722 // wall-clock-based-waiting period and then the update-check-based waiting
723 // period, if required.
724
725 if (!params_->wall_clock_based_wait_enabled) {
726 // Wall-clock-based waiting period is not enabled, so no scattering needed.
727 return false;
728 }
729
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700730 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700731 case kWallClockWaitNotSatisfied:
732 // We haven't even satisfied the first condition, passing the
733 // wall-clock-based waiting period, so we should defer the downloads
734 // until that happens.
735 LOG(INFO) << "wall-clock-based-wait not satisfied.";
736 return true;
737
738 case kWallClockWaitDoneButUpdateCheckWaitRequired:
739 LOG(INFO) << "wall-clock-based-wait satisfied and "
740 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700741 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700742
743 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
744 // Wall-clock-based waiting period is satisfied, and it's determined
745 // that we do not need the update-check-based wait. so no need to
746 // defer downloads.
747 LOG(INFO) << "wall-clock-based-wait satisfied and "
748 << "update-check-based-wait is not required.";
749 return false;
750
751 default:
752 // Returning false for this default case so we err on the
753 // side of downloading updates than deferring in case of any bugs.
754 NOTREACHED();
755 return false;
756 }
757}
758
759OmahaRequestAction::WallClockWaitResult
760OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700761 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700762 Time update_first_seen_at;
763 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700764
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800765 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
766 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
767 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700768 // Note: This timestamp could be that of ANY update we saw in the past
769 // (not necessarily this particular update we're considering to apply)
770 // but never got to apply because of some reason (e.g. stop AU policy,
771 // updates being pulled out from Omaha, changes in target version prefix,
772 // new update being rolled out, etc.). But for the purposes of scattering
773 // it doesn't matter which update the timestamp corresponds to. i.e.
774 // the clock starts ticking the first time we see an update and we're
775 // ready to apply when the random wait period is satisfied relative to
776 // that first seen timestamp.
777 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
778 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
779 << utils::ToString(update_first_seen_at);
780 } else {
781 // This seems like an unexpected error where the persisted value exists
782 // but it's not readable for some reason. Just skip scattering in this
783 // case to be safe.
784 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
785 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
786 }
787 } else {
788 update_first_seen_at = Time::Now();
789 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800790 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
791 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700792 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
793 << utils::ToString(update_first_seen_at);
794 }
795 else {
796 // This seems like an unexpected error where the value cannot be
797 // persisted for some reason. Just skip scattering in this
798 // case to be safe.
799 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
800 << utils::ToString(update_first_seen_at)
801 << " cannot be persisted";
802 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
803 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700804 }
805
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700806 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700807 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700808 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700809
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700810 LOG(INFO) << "Waiting Period = "
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700811 << utils::FormatSecs(params_->waiting_period.InSeconds())
812 << ", Time Elapsed = "
813 << utils::FormatSecs(elapsed_time.InSeconds())
814 << ", MaxDaysToScatter = "
815 << max_scatter_period.InDays();
816
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700817 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700818 // The deadline is set for all rules which serve a delta update from a
819 // previous FSI, which means this update will be applied mostly in OOBE
820 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
821 // quickly.
822 LOG(INFO) << "Not scattering as deadline flag is set";
823 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
824 }
825
826 if (max_scatter_period.InDays() == 0) {
827 // This means the Omaha rule creator decides that this rule
828 // should not be scattered irrespective of the policy.
829 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
830 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
831 }
832
833 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700834 // This means we've waited more than the upperbound wait in the rule
835 // from the time we first saw a valid update available to us.
836 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700837 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
838 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
839 }
840
841 // This means we are required to participate in scattering.
842 // See if our turn has arrived now.
843 TimeDelta remaining_wait_time = params_->waiting_period - elapsed_time;
844 if (remaining_wait_time.InSeconds() <= 0) {
845 // Yes, it's our turn now.
846 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
847
848 // But we can't download until the update-check-count-based wait is also
849 // satisfied, so mark it as required now if update checks are enabled.
850 return params_->update_check_count_wait_enabled ?
851 kWallClockWaitDoneButUpdateCheckWaitRequired :
852 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
853 }
854
855 // Not our turn yet, so we have to wait until our turn to
856 // help scatter the downloads across all clients of the enterprise.
857 LOG(INFO) << "Update deferred for another "
858 << utils::FormatSecs(remaining_wait_time.InSeconds())
859 << " per policy.";
860 return kWallClockWaitNotSatisfied;
861}
862
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700863bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700864 int64 update_check_count_value;
865
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800866 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
867 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
868 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700869 // We are unable to read the update check count from file for some reason.
870 // So let's proceed anyway so as to not stall the update.
871 LOG(ERROR) << "Unable to read update check count. "
872 << "Skipping update-check-count-based-wait.";
873 return true;
874 }
875 } else {
876 // This file does not exist. This means we haven't started our update
877 // check count down yet, so this is the right time to start the count down.
878 update_check_count_value = base::RandInt(
879 params_->min_update_checks_needed,
880 params_->max_update_checks_allowed);
881
882 LOG(INFO) << "Randomly picked update check count value = "
883 << update_check_count_value;
884
885 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800886 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
887 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700888 // We weren't able to write the update check count file for some reason.
889 // So let's proceed anyway so as to not stall the update.
890 LOG(ERROR) << "Unable to write update check count. "
891 << "Skipping update-check-count-based-wait.";
892 return true;
893 }
894 }
895
896 if (update_check_count_value == 0) {
897 LOG(INFO) << "Successfully passed the update-check-based-wait.";
898 return true;
899 }
900
901 if (update_check_count_value < 0 ||
902 update_check_count_value > params_->max_update_checks_allowed) {
903 // We err on the side of skipping scattering logic instead of stalling
904 // a machine from receiving any updates in case of any unexpected state.
905 LOG(ERROR) << "Invalid value for update check count detected. "
906 << "Skipping update-check-count-based-wait.";
907 return true;
908 }
909
910 // Legal value, we need to wait for more update checks to happen
911 // until this becomes 0.
912 LOG(INFO) << "Deferring Omaha updates for another "
913 << update_check_count_value
914 << " update checks per policy";
915 return false;
916}
917
918} // namespace chromeos_update_engine
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700919
920