blob: edfea53913c7e36fdf96278a3ccdac059ec57e83 [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 Srinivasan08262882012-12-28 19:29:43 -080037static const char* kTagIsDeltaPayload = "IsDelta";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080038static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
39static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
40// Deprecated: "ManifestSignatureRsa"
41// Deprecated: "ManifestSize"
42static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
43static const char* kTagMetadataSize = "MetadataSize";
44static const char* kTagMoreInfo = "MoreInfo";
45static const char* kTagNeedsAdmin = "needsadmin";
46static const char* kTagPrompt = "Prompt";
47static const char* kTagSha256 = "sha256";
48
rspangler@google.com49fdf182009-10-10 00:57:34 +000049namespace {
50
51const string kGupdateVersion("ChromeOSUpdateEngine-0.1.0.0");
52
53// This is handy for passing strings into libxml2
54#define ConstXMLStr(x) (reinterpret_cast<const xmlChar*>(x))
55
56// These are for scoped_ptr_malloc, which is like scoped_ptr, but allows
57// a custom free() function to be specified.
58class ScopedPtrXmlDocFree {
59 public:
60 inline void operator()(void* x) const {
61 xmlFreeDoc(reinterpret_cast<xmlDoc*>(x));
62 }
63};
64class ScopedPtrXmlFree {
65 public:
66 inline void operator()(void* x) const {
67 xmlFree(x);
68 }
69};
70class ScopedPtrXmlXPathObjectFree {
71 public:
72 inline void operator()(void* x) const {
73 xmlXPathFreeObject(reinterpret_cast<xmlXPathObject*>(x));
74 }
75};
76class ScopedPtrXmlXPathContextFree {
77 public:
78 inline void operator()(void* x) const {
79 xmlXPathFreeContext(reinterpret_cast<xmlXPathContext*>(x));
80 }
81};
82
Darin Petkov1cbd78f2010-07-29 12:38:34 -070083// Returns true if |ping_days| has a value that needs to be sent,
84// false otherwise.
85bool ShouldPing(int ping_days) {
86 return ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged;
87}
88
89// Returns an XML ping element attribute assignment with attribute
90// |name| and value |ping_days| if |ping_days| has a value that needs
91// to be sent, or an empty string otherwise.
92string GetPingAttribute(const string& name, int ping_days) {
93 if (ShouldPing(ping_days)) {
94 return StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
95 }
96 return "";
97}
98
99// Returns an XML ping element if any of the elapsed days need to be
100// sent, or an empty string otherwise.
101string GetPingBody(int ping_active_days, int ping_roll_call_days) {
102 string ping_active = GetPingAttribute("a", ping_active_days);
103 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
104 if (!ping_active.empty() || !ping_roll_call.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700105 return StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700106 ping_active.c_str(),
107 ping_roll_call.c_str());
108 }
109 return "";
110}
111
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700112string FormatRequest(const OmahaEvent* event,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700113 const OmahaRequestParams& params,
Thieu Le116fda32011-04-19 11:01:54 -0700114 bool ping_only,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700115 int ping_active_days,
Darin Petkov95508da2011-01-05 12:42:29 -0800116 int ping_roll_call_days,
117 PrefsInterface* prefs) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700118 string body;
119 if (event == NULL) {
Thieu Le116fda32011-04-19 11:01:54 -0700120 body = GetPingBody(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700121 if (!ping_only) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700122 // not passing update_disabled to Omaha because we want to
123 // get the update and report with UpdateDeferred result so that
124 // borgmon charts show up updates that are deferred. This is also
125 // the expected behavior when we move to Omaha v3.0 protocol, so it'll
126 // be consistent.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700127 body += StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700128 " <updatecheck"
Jay Srinivasan0a708742012-03-20 11:26:12 -0700129 " targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700130 "></updatecheck>\n",
Jay Srinivasan0a708742012-03-20 11:26:12 -0700131 XmlEncode(params.target_version_prefix).c_str());
132
Darin Petkov265f2902011-05-09 15:17:40 -0700133 // If this is the first update check after a reboot following a previous
134 // update, generate an event containing the previous version number. If
135 // the previous version preference file doesn't exist the event is still
136 // generated with a previous version of 0.0.0.0 -- this is relevant for
137 // older clients or new installs. The previous version event is not sent
138 // for ping-only requests because they come before the client has
139 // rebooted.
140 string prev_version;
141 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
142 prev_version = "0.0.0.0";
143 }
144 if (!prev_version.empty()) {
145 body += StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700146 " <event eventtype=\"%d\" eventresult=\"%d\" "
147 "previousversion=\"%s\"></event>\n",
Darin Petkov265f2902011-05-09 15:17:40 -0700148 OmahaEvent::kTypeUpdateComplete,
149 OmahaEvent::kResultSuccessReboot,
150 XmlEncode(prev_version).c_str());
151 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
152 << "Unable to reset the previous version.";
153 }
Darin Petkov95508da2011-01-05 12:42:29 -0800154 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700155 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800156 // The error code is an optional attribute so append it only if the result
157 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700158 string error_code;
159 if (event->result != OmahaEvent::kResultSuccess) {
Darin Petkov18c7bce2011-06-16 14:07:00 -0700160 error_code = StringPrintf(" errorcode=\"%d\"", event->error_code);
Darin Petkove17f86b2010-07-20 09:12:01 -0700161 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700162 body = StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700163 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700164 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700165 }
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700166 return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700167 "<request protocol=\"3.0\" "
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700168 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
169 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" "
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700170 "ismachine=\"1\">\n"
171 " <os version=\"" + XmlEncode(params.os_version) + "\" platform=\"" +
rspangler@google.com49fdf182009-10-10 00:57:34 +0000172 XmlEncode(params.os_platform) + "\" sp=\"" +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700173 XmlEncode(params.os_sp) + "\"></os>\n"
174 " <app appid=\"" + XmlEncode(params.app_id) + "\" version=\"" +
rspangler@google.com49fdf182009-10-10 00:57:34 +0000175 XmlEncode(params.app_version) + "\" "
176 "lang=\"" + XmlEncode(params.app_lang) + "\" track=\"" +
Andrew de los Reyes37c20322010-06-30 13:27:19 -0700177 XmlEncode(params.app_track) + "\" board=\"" +
Darin Petkovfbb40092010-07-29 17:05:50 -0700178 XmlEncode(params.os_board) + "\" hardware_class=\"" +
179 XmlEncode(params.hardware_class) + "\" delta_okay=\"" +
Andrew de los Reyes3f0303a2010-07-15 22:35:35 -0700180 (params.delta_okay ? "true" : "false") + "\">\n" + body +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700181 " </app>\n"
182 "</request>\n";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000183}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700184
rspangler@google.com49fdf182009-10-10 00:57:34 +0000185} // namespace {}
186
187// Encodes XML entities in a given string with libxml2. input must be
188// UTF-8 formatted. Output will be UTF-8 formatted.
189string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700190 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
191 // // cpu, considering creating one and caching it.
192 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
193 // xmlNewDoc(ConstXMLStr("1.0")));
194 // if (!xml_doc.get()) {
195 // LOG(ERROR) << "Unable to create xmlDoc";
196 // return "";
197 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000198 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
199 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
200 return string(reinterpret_cast<const char *>(str.get()));
201}
202
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800203OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700204 OmahaRequestParams* params,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700205 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700206 HttpFetcher* http_fetcher,
207 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800208 : system_state_(system_state),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700209 params_(params),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700210 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700211 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700212 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700213 ping_active_days_(0),
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700214 ping_roll_call_days_(0) {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000215
Darin Petkov6a5b3222010-07-13 14:55:28 -0700216OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000217
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700218// Calculates the value to use for the ping days parameter.
219int OmahaRequestAction::CalculatePingDays(const string& key) {
220 int days = kNeverPinged;
221 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800222 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700223 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
224 if (days < 0) {
225 // If |days| is negative, then the system clock must have jumped
226 // back in time since the ping was sent. Mark the value so that
227 // it doesn't get sent to the server but we still update the
228 // last ping daystart preference. This way the next ping time
229 // will be correct, hopefully.
230 days = kPingTimeJump;
231 LOG(WARNING) <<
232 "System clock jumped back in time. Resetting ping daystarts.";
233 }
234 }
235 return days;
236}
237
238void OmahaRequestAction::InitPingDays() {
239 // We send pings only along with update checks, not with events.
240 if (IsEvent()) {
241 return;
242 }
243 // TODO(petkov): Figure a way to distinguish active use pings
244 // vs. roll call pings. Currently, the two pings are identical. A
245 // fix needs to change this code as well as UpdateLastPingDays.
246 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
247 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
248}
249
Darin Petkov6a5b3222010-07-13 14:55:28 -0700250void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000251 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700252 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700253 if (ping_only_ &&
254 !ShouldPing(ping_active_days_) &&
255 !ShouldPing(ping_roll_call_days_)) {
256 processor_->ActionComplete(this, kActionCodeSuccess);
257 return;
258 }
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700259 string request_post(FormatRequest(event_.get(),
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700260 *params_,
Thieu Le116fda32011-04-19 11:01:54 -0700261 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700262 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800263 ping_roll_call_days_,
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800264 system_state_->prefs()));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700265
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800266 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
267 kHttpContentTypeTextXml);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700268 LOG(INFO) << "Posting an Omaha request to " << params_->update_url;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700269 LOG(INFO) << "Request: " << request_post;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700270 http_fetcher_->BeginTransfer(params_->update_url);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000271}
272
Darin Petkov6a5b3222010-07-13 14:55:28 -0700273void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000274 http_fetcher_->TerminateTransfer();
275}
276
277// We just store the response in the buffer. Once we've received all bytes,
278// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700279void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
280 const char* bytes,
281 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000282 response_buffer_.reserve(response_buffer_.size() + length);
283 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
284}
285
286namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000287// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
288// on the returned object.
289// This code is roughly based on the libxml tutorial at:
290// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700291xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000292 xmlXPathObject* result = NULL;
293
294 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
295 xmlXPathNewContext(doc));
296 if (!context.get()) {
297 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
298 return NULL;
299 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000300
301 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000302 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700303 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000304 return NULL;
305 }
306 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700307 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000308 xmlXPathFreeObject(result);
309 return NULL;
310 }
311 return result;
312}
313
314// Returns the string value of a named attribute on a node, or empty string
315// if no such node exists. If the attribute exists and has a value of
316// empty string, there's no way to distinguish that from the attribute
317// not existing.
318string XmlGetProperty(xmlNode* node, const char* name) {
319 if (!xmlHasProp(node, ConstXMLStr(name)))
320 return "";
321 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
322 xmlGetProp(node, ConstXMLStr(name)));
323 string ret(reinterpret_cast<const char *>(str.get()));
324 return ret;
325}
326
327// Parses a 64 bit base-10 int from a string and returns it. Returns 0
328// on error. If the string contains "0", that's indistinguishable from
329// error.
330off_t ParseInt(const string& str) {
331 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700332 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000333 if (rc < 1) {
334 // failure
335 return 0;
336 }
337 return ret;
338}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700339
340// Update the last ping day preferences based on the server daystart
341// response. Returns true on success, false otherwise.
342bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700343 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700344
345 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700346 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700347 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
348 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
349 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
350 xmlNode* daystart_node = nodeset->nodeTab[0];
351 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
352 ConstXMLStr("elapsed_seconds")));
353
354 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700355 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
356 "elapsed_seconds"),
357 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700358 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
359
360 // Remember the local time that matches the server's last midnight
361 // time.
362 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
363 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
364 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
365 return true;
366}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000367} // namespace {}
368
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700369bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
370 OmahaResponse* output_object,
371 ScopedActionCompleter* completer) {
372 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
373
374 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
375 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
376 if (!xpath_nodeset.get()) {
377 completer->set_code(kActionCodeOmahaResponseInvalid);
378 return false;
379 }
380
381 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
382 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
383 CHECK_GE(nodeset->nodeNr, 1);
384 xmlNode* update_check_node = nodeset->nodeTab[0];
385
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800386 // chromium-os:37289: The PollInterval is not supported by Omaha server
387 // currently. But still keeping this existing code in case we ever decide to
388 // slow down the request rate from the server-side. Note that the
389 // PollInterval is not persisted, so it has to be sent by the server on every
390 // response to guarantee that the UpdateCheckScheduler uses this value
391 // (otherwise, if the device got rebooted after the last server-indicated
392 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
393 // value for the scattering logic is based on the assumption that we perform
394 // an update check every hour so that the max value of 8 will roughly be
395 // equivalent to one work day. If we decide to use PollInterval permanently,
396 // we should update the max_update_checks_allowed to take PollInterval into
397 // account. Note: The parsing for PollInterval happens even before parsing
398 // of the status because we may want to specify the PollInterval even when
399 // there's no update.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700400 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
401 &output_object->poll_interval);
402
403 if (!ParseStatus(update_check_node, output_object, completer))
404 return false;
405
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800406 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
407 // appends the package name to the URLs populated in this method.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700408 if (!ParseUrls(doc, output_object, completer))
409 return false;
410
411 if (!ParsePackage(doc, output_object, completer))
412 return false;
413
414 if (!ParseParams(doc, output_object, completer))
415 return false;
416
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800417 output_object->update_exists = true;
418 SetOutputObject(*output_object);
419 completer->set_code(kActionCodeSuccess);
420
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700421 return true;
422}
423
424bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
425 OmahaResponse* output_object,
426 ScopedActionCompleter* completer) {
427 // Get status.
428 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
429 LOG(ERROR) << "Omaha Response missing status";
430 completer->set_code(kActionCodeOmahaResponseInvalid);
431 return false;
432 }
433
434 const string status(XmlGetProperty(update_check_node, "status"));
435 if (status == "noupdate") {
436 LOG(INFO) << "No update.";
437 output_object->update_exists = false;
438 SetOutputObject(*output_object);
439 completer->set_code(kActionCodeSuccess);
440 return false;
441 }
442
443 if (status != "ok") {
444 LOG(ERROR) << "Unknown Omaha response status: " << status;
445 completer->set_code(kActionCodeOmahaResponseInvalid);
446 return false;
447 }
448
449 return true;
450}
451
452bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
453 OmahaResponse* output_object,
454 ScopedActionCompleter* completer) {
455 // Get the update URL.
456 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
457
458 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
459 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
460 if (!xpath_nodeset.get()) {
461 completer->set_code(kActionCodeOmahaResponseInvalid);
462 return false;
463 }
464
465 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
466 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
467 CHECK_GE(nodeset->nodeNr, 1);
468
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800469 LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)";
470 output_object->payload_urls.clear();
471 for (int i = 0; i < nodeset->nodeNr; i++) {
472 xmlNode* url_node = nodeset->nodeTab[i];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700473
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800474 const string codebase(XmlGetProperty(url_node, "codebase"));
475 if (codebase.empty()) {
476 LOG(ERROR) << "Omaha Response URL has empty codebase";
477 completer->set_code(kActionCodeOmahaResponseInvalid);
478 return false;
479 }
480 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700481 }
482
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700483 return true;
484}
485
486bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
487 OmahaResponse* output_object,
488 ScopedActionCompleter* completer) {
489 // Get the package node.
490 static const char* kPackageNodeXPath(
491 "/response/app/updatecheck/manifest/packages/package");
492
493 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
494 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
495 if (!xpath_nodeset.get()) {
496 completer->set_code(kActionCodeOmahaResponseInvalid);
497 return false;
498 }
499
500 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
501 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
502 CHECK_GE(nodeset->nodeNr, 1);
503
504 // We only care about the first package.
505 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
506 xmlNode* package_node = nodeset->nodeTab[0];
507
508 // Get package properties one by one.
509
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800510 // Parse the payload name to be appended to the base Url value.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700511 const string package_name(XmlGetProperty(package_node, "name"));
512 LOG(INFO) << "Omaha Response package name = " << package_name;
513 if (package_name.empty()) {
514 LOG(ERROR) << "Omaha Response has empty package name";
515 completer->set_code(kActionCodeOmahaResponseInvalid);
516 return false;
517 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800518
519 // Append the package name to each URL in our list so that we don't
520 // propagate the urlBase vs packageName distinctions beyond this point.
521 // From now on, we only need to use payload_urls.
522 for (size_t i = 0; i < output_object->payload_urls.size(); i++) {
523 output_object->payload_urls[i] += package_name;
524 LOG(INFO) << "Url" << i << ": " << output_object->payload_urls[i];
525 }
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700526
527 // Parse the payload size.
528 off_t size = ParseInt(XmlGetProperty(package_node, "size"));
529 if (size <= 0) {
530 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
531 completer->set_code(kActionCodeOmahaResponseInvalid);
532 return false;
533 }
534 output_object->size = size;
535
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800536 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700537
538 return true;
539}
540
541bool OmahaRequestAction::ParseParams(xmlDoc* doc,
542 OmahaResponse* output_object,
543 ScopedActionCompleter* completer) {
544 // Get the action node where parameters are present.
545 static const char* kActionNodeXPath(
546 "/response/app/updatecheck/manifest/actions/action");
547
548 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
549 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
550 if (!xpath_nodeset.get()) {
551 completer->set_code(kActionCodeOmahaResponseInvalid);
552 return false;
553 }
554
555 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
556 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
557
558 // We only care about the action that has event "postinall", because this is
559 // where Omaha puts all the generic name/value pairs in the rule.
560 LOG(INFO) << "Found " << nodeset->nodeNr
561 << " action(s). Processing the postinstall action.";
562
563 // pie_action_node holds the action node corresponding to the
564 // postinstall event action, if present.
565 xmlNode* pie_action_node = NULL;
566 for (int i = 0; i < nodeset->nodeNr; i++) {
567 xmlNode* action_node = nodeset->nodeTab[i];
568 if (XmlGetProperty(action_node, "event") == "postinstall") {
569 pie_action_node = action_node;
570 break;
571 }
572 }
573
574 if (!pie_action_node) {
575 LOG(ERROR) << "Omaha Response has no postinstall event action";
576 completer->set_code(kActionCodeOmahaResponseInvalid);
577 return false;
578 }
579
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800580 output_object->hash = XmlGetProperty(pie_action_node, kTagSha256);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700581 if (output_object->hash.empty()) {
582 LOG(ERROR) << "Omaha Response has empty sha256 value";
583 completer->set_code(kActionCodeOmahaResponseInvalid);
584 return false;
585 }
586
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800587 // Get the optional properties one by one.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700588 output_object->display_version =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800589 XmlGetProperty(pie_action_node, kTagDisplayVersion);
590 output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700591 output_object->metadata_size =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800592 ParseInt(XmlGetProperty(pie_action_node, kTagMetadataSize));
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700593 output_object->metadata_signature =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800594 XmlGetProperty(pie_action_node, kTagMetadataSignatureRsa);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700595 output_object->needs_admin =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800596 XmlGetProperty(pie_action_node, kTagNeedsAdmin) == "true";
597 output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true";
598 output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700599 output_object->max_days_to_scatter =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800600 ParseInt(XmlGetProperty(pie_action_node, kTagMaxDaysToScatter));
601
602 string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl);
Jay Srinivasan08262882012-12-28 19:29:43 -0800603 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800604 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700605
Jay Srinivasan08262882012-12-28 19:29:43 -0800606 output_object->is_delta_payload =
607 XmlGetProperty(pie_action_node, kTagIsDeltaPayload) == "true";
608
609 output_object->disable_payload_backoff =
610 XmlGetProperty(pie_action_node, kTagDisablePayloadBackoff) == "true";
611
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700612 return true;
613}
614
rspangler@google.com49fdf182009-10-10 00:57:34 +0000615// If the transfer was successful, this uses libxml2 to parse the response
616// and fill in the appropriate fields of the output object. Also, notifies
617// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700618void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
619 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000620 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800621 string current_response(response_buffer_.begin(), response_buffer_.end());
622 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700623
624 // Events are best effort transactions -- assume they always succeed.
625 if (IsEvent()) {
626 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800627 if (event_->result == OmahaEvent::kResultError && successful &&
628 utils::IsOfficialBuild()) {
629 LOG(INFO) << "Signalling Crash Reporter.";
630 utils::ScheduleCrashReporterUpload();
631 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700632 completer.set_code(kActionCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700633 return;
634 }
635
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700636 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700637 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700638 int code = GetHTTPResponseCode();
639 // Makes sure we send sane error values.
640 if (code < 0 || code >= 1000) {
641 code = 999;
642 }
643 completer.set_code(static_cast<ActionExitCode>(
644 kActionCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000645 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700646 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000647
648 // parse our response and fill the fields in the output object
649 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
650 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
651 if (!doc.get()) {
652 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700653 completer.set_code(response_buffer_.empty() ?
654 kActionCodeOmahaRequestEmptyResponseError :
655 kActionCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000656 return;
657 }
658
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700659 // If a ping was sent, update the last ping day preferences based on
660 // the server daystart response.
661 if (ShouldPing(ping_active_days_) ||
662 ShouldPing(ping_roll_call_days_) ||
663 ping_active_days_ == kPingTimeJump ||
664 ping_roll_call_days_ == kPingTimeJump) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800665 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700666 << "Failed to update the last ping day preferences!";
667 }
668
Thieu Le116fda32011-04-19 11:01:54 -0700669 if (!HasOutputPipe()) {
670 // Just set success to whether or not the http transfer succeeded,
671 // which must be true at this point in the code.
672 completer.set_code(kActionCodeSuccess);
673 return;
674 }
675
Darin Petkov6a5b3222010-07-13 14:55:28 -0700676 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700677 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000678 return;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000679
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700680 if (params_->update_disabled) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700681 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700682 output_object.update_exists = false;
Jay Srinivasan0a708742012-03-20 11:26:12 -0700683 completer.set_code(kActionCodeOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700684 // Note: We could technically delete the UpdateFirstSeenAt state here.
685 // If we do, it'll mean a device has to restart the UpdateFirstSeenAt
686 // and thus help scattering take effect when the AU is turned on again.
687 // On the other hand, it also increases the chance of update starvation if
688 // an admin turns AU on/off more frequently. We choose to err on the side
689 // of preventing starvation at the cost of not applying scattering in
690 // those cases.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700691 return;
692 }
693
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700694 if (ShouldDeferDownload(&output_object)) {
695 output_object.update_exists = false;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700696 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
697 completer.set_code(kActionCodeOmahaUpdateDeferredPerPolicy);
698 return;
699 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800700
701 // Update the payload state with the current response. The payload state
702 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800703 // from what's stored already. We are updating the payload state as late
704 // as possible in this method so that if a new release gets pushed and then
705 // got pulled back due to some issues, we don't want to clear our internal
706 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800707 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800708 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800709
710 if (payload_state->ShouldBackoffDownload()) {
711 output_object.update_exists = false;
712 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
713 "attempts";
714 completer.set_code(kActionCodeOmahaUpdateDeferredForBackoff);
715 return;
716 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000717}
718
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700719bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700720 // We should defer the downloads only if we've first satisfied the
721 // wall-clock-based-waiting period and then the update-check-based waiting
722 // period, if required.
723
724 if (!params_->wall_clock_based_wait_enabled) {
725 // Wall-clock-based waiting period is not enabled, so no scattering needed.
726 return false;
727 }
728
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700729 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700730 case kWallClockWaitNotSatisfied:
731 // We haven't even satisfied the first condition, passing the
732 // wall-clock-based waiting period, so we should defer the downloads
733 // until that happens.
734 LOG(INFO) << "wall-clock-based-wait not satisfied.";
735 return true;
736
737 case kWallClockWaitDoneButUpdateCheckWaitRequired:
738 LOG(INFO) << "wall-clock-based-wait satisfied and "
739 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700740 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700741
742 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
743 // Wall-clock-based waiting period is satisfied, and it's determined
744 // that we do not need the update-check-based wait. so no need to
745 // defer downloads.
746 LOG(INFO) << "wall-clock-based-wait satisfied and "
747 << "update-check-based-wait is not required.";
748 return false;
749
750 default:
751 // Returning false for this default case so we err on the
752 // side of downloading updates than deferring in case of any bugs.
753 NOTREACHED();
754 return false;
755 }
756}
757
758OmahaRequestAction::WallClockWaitResult
759OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700760 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700761 Time update_first_seen_at;
762 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700763
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800764 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
765 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
766 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700767 // Note: This timestamp could be that of ANY update we saw in the past
768 // (not necessarily this particular update we're considering to apply)
769 // but never got to apply because of some reason (e.g. stop AU policy,
770 // updates being pulled out from Omaha, changes in target version prefix,
771 // new update being rolled out, etc.). But for the purposes of scattering
772 // it doesn't matter which update the timestamp corresponds to. i.e.
773 // the clock starts ticking the first time we see an update and we're
774 // ready to apply when the random wait period is satisfied relative to
775 // that first seen timestamp.
776 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
777 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
778 << utils::ToString(update_first_seen_at);
779 } else {
780 // This seems like an unexpected error where the persisted value exists
781 // but it's not readable for some reason. Just skip scattering in this
782 // case to be safe.
783 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
784 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
785 }
786 } else {
787 update_first_seen_at = Time::Now();
788 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800789 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
790 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700791 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
792 << utils::ToString(update_first_seen_at);
793 }
794 else {
795 // This seems like an unexpected error where the value cannot be
796 // persisted for some reason. Just skip scattering in this
797 // case to be safe.
798 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
799 << utils::ToString(update_first_seen_at)
800 << " cannot be persisted";
801 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
802 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700803 }
804
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700805 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700806 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700807 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700808
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700809 LOG(INFO) << "Waiting Period = "
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700810 << utils::FormatSecs(params_->waiting_period.InSeconds())
811 << ", Time Elapsed = "
812 << utils::FormatSecs(elapsed_time.InSeconds())
813 << ", MaxDaysToScatter = "
814 << max_scatter_period.InDays();
815
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700816 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700817 // The deadline is set for all rules which serve a delta update from a
818 // previous FSI, which means this update will be applied mostly in OOBE
819 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
820 // quickly.
821 LOG(INFO) << "Not scattering as deadline flag is set";
822 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
823 }
824
825 if (max_scatter_period.InDays() == 0) {
826 // This means the Omaha rule creator decides that this rule
827 // should not be scattered irrespective of the policy.
828 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
829 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
830 }
831
832 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700833 // This means we've waited more than the upperbound wait in the rule
834 // from the time we first saw a valid update available to us.
835 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700836 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
837 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
838 }
839
840 // This means we are required to participate in scattering.
841 // See if our turn has arrived now.
842 TimeDelta remaining_wait_time = params_->waiting_period - elapsed_time;
843 if (remaining_wait_time.InSeconds() <= 0) {
844 // Yes, it's our turn now.
845 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
846
847 // But we can't download until the update-check-count-based wait is also
848 // satisfied, so mark it as required now if update checks are enabled.
849 return params_->update_check_count_wait_enabled ?
850 kWallClockWaitDoneButUpdateCheckWaitRequired :
851 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
852 }
853
854 // Not our turn yet, so we have to wait until our turn to
855 // help scatter the downloads across all clients of the enterprise.
856 LOG(INFO) << "Update deferred for another "
857 << utils::FormatSecs(remaining_wait_time.InSeconds())
858 << " per policy.";
859 return kWallClockWaitNotSatisfied;
860}
861
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700862bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700863 int64 update_check_count_value;
864
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800865 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
866 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
867 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700868 // We are unable to read the update check count from file for some reason.
869 // So let's proceed anyway so as to not stall the update.
870 LOG(ERROR) << "Unable to read update check count. "
871 << "Skipping update-check-count-based-wait.";
872 return true;
873 }
874 } else {
875 // This file does not exist. This means we haven't started our update
876 // check count down yet, so this is the right time to start the count down.
877 update_check_count_value = base::RandInt(
878 params_->min_update_checks_needed,
879 params_->max_update_checks_allowed);
880
881 LOG(INFO) << "Randomly picked update check count value = "
882 << update_check_count_value;
883
884 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800885 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
886 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700887 // We weren't able to write the update check count file for some reason.
888 // So let's proceed anyway so as to not stall the update.
889 LOG(ERROR) << "Unable to write update check count. "
890 << "Skipping update-check-count-based-wait.";
891 return true;
892 }
893 }
894
895 if (update_check_count_value == 0) {
896 LOG(INFO) << "Successfully passed the update-check-based-wait.";
897 return true;
898 }
899
900 if (update_check_count_value < 0 ||
901 update_check_count_value > params_->max_update_checks_allowed) {
902 // We err on the side of skipping scattering logic instead of stalling
903 // a machine from receiving any updates in case of any unexpected state.
904 LOG(ERROR) << "Invalid value for update check count detected. "
905 << "Skipping update-check-count-based-wait.";
906 return true;
907 }
908
909 // Legal value, we need to wait for more update checks to happen
910 // until this becomes 0.
911 LOG(INFO) << "Deferring Omaha updates for another "
912 << update_check_count_value
913 << " update checks per policy";
914 return false;
915}
916
917} // namespace chromeos_update_engine
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700918
919