blob: 14ec8f6378943427daa14eb34f333823791f8ecd [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.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700102string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700103 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
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700113// Returns an XML that goes into the body of the <app> element of the Omaha
114// request based on the given parameters.
115string GetAppBody(const OmahaEvent* event,
116 const OmahaRequestParams& params,
117 bool ping_only,
118 int ping_active_days,
119 int ping_roll_call_days,
120 PrefsInterface* prefs) {
121 string app_body;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700122 if (event == NULL) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700123 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700124 if (!ping_only) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700125 // not passing update_disabled to Omaha because we want to
126 // get the update and report with UpdateDeferred result so that
127 // borgmon charts show up updates that are deferred. This is also
128 // the expected behavior when we move to Omaha v3.0 protocol, so it'll
129 // be consistent.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700130 app_body += StringPrintf(
131 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700132 "></updatecheck>\n",
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700133 XmlEncode(params.target_version_prefix()).c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700134
Darin Petkov265f2902011-05-09 15:17:40 -0700135 // If this is the first update check after a reboot following a previous
136 // update, generate an event containing the previous version number. If
137 // the previous version preference file doesn't exist the event is still
138 // generated with a previous version of 0.0.0.0 -- this is relevant for
139 // older clients or new installs. The previous version event is not sent
140 // for ping-only requests because they come before the client has
141 // rebooted.
142 string prev_version;
143 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
144 prev_version = "0.0.0.0";
145 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700146
147 app_body += StringPrintf(
148 " <event eventtype=\"%d\" eventresult=\"%d\" "
149 "previousversion=\"%s\"></event>\n",
150 OmahaEvent::kTypeUpdateComplete,
151 OmahaEvent::kResultSuccessReboot,
152 XmlEncode(prev_version).c_str());
153 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
154 << "Unable to reset the previous version.";
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 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700163 app_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 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700167
168 return app_body;
169}
170
171// Returns an XML that corresponds to the entire <app> node of the Omaha
172// request based on the given parameters.
173string GetAppXml(const OmahaEvent* event,
174 const OmahaRequestParams& params,
175 bool ping_only,
176 int ping_active_days,
177 int ping_roll_call_days,
178 SystemState* system_state) {
179 string app_body = GetAppBody(event, params, ping_only, ping_active_days,
180 ping_roll_call_days, system_state->prefs());
181 string app_versions;
182
183 // If we are upgrading to a more stable channel and we are allowed to do
184 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
185 // highest-versioned payload on the destination channel.
186 if (params.to_more_stable_channel() && params.is_powerwash_allowed()) {
187 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
188 << "on downgrading to the version in the more stable channel";
189 app_versions = "version=\"0.0.0.0\" from_version=\"" +
190 XmlEncode(params.app_version()) + "\" ";
191 } else {
192 app_versions = "version=\"" + XmlEncode(params.app_version()) + "\" ";
193 }
194
195 string app_channels = "track=\"" + XmlEncode(params.target_channel()) + "\" ";
196 if (params.current_channel() != params.target_channel())
197 app_channels +=
198 "from_track=\"" + XmlEncode(params.current_channel()) + "\" ";
199
200 string delta_okay_str = params.delta_okay() ? "true" : "false";
201
202 // Use the default app_id only if we're asking for an update on the
203 // canary-channel. Otherwise, use the board's app_id.
204 string request_app_id =
205 (params.target_channel() == "canary-channel" ?
206 params.app_id() : params.board_app_id());
207 string app_xml =
208 " <app appid=\"" + XmlEncode(request_app_id) + "\" " +
209 app_versions +
210 app_channels +
211 "lang=\"" + XmlEncode(params.app_lang()) + "\" " +
212 "board=\"" + XmlEncode(params.os_board()) + "\" " +
213 "hardware_class=\"" + XmlEncode(params.hwid()) + "\" " +
214 "delta_okay=\"" + delta_okay_str + "\" "
215 ">\n" +
216 app_body +
217 " </app>\n";
218
219 return app_xml;
220}
221
222// Returns an XML that corresponds to the entire <os> node of the Omaha
223// request based on the given parameters.
224string GetOsXml(const OmahaRequestParams& params) {
225 string os_xml =
226 " <os version=\"" + XmlEncode(params.os_version()) + "\" " +
227 "platform=\"" + XmlEncode(params.os_platform()) + "\" " +
228 "sp=\"" + XmlEncode(params.os_sp()) + "\">"
229 "</os>\n";
230 return os_xml;
231}
232
233// Returns an XML that corresponds to the entire Omaha request based on the
234// given parameters.
235string GetRequestXml(const OmahaEvent* event,
236 const OmahaRequestParams& params,
237 bool ping_only,
238 int ping_active_days,
239 int ping_roll_call_days,
240 SystemState* system_state) {
241 string os_xml = GetOsXml(params);
242 string app_xml = GetAppXml(event, params, ping_only, ping_active_days,
243 ping_roll_call_days, system_state);
244
245 string install_source = StringPrintf("installsource=\"%s\" ",
246 (params.interactive() ? "ondemandupdate" : "scheduler"));
247
248 string request_xml =
249 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700250 "<request protocol=\"3.0\" "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700251 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
252 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" " +
253 install_source +
254 "ismachine=\"1\">\n" +
255 os_xml +
256 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700257 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700258
259 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000260}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700261
rspangler@google.com49fdf182009-10-10 00:57:34 +0000262} // namespace {}
263
264// Encodes XML entities in a given string with libxml2. input must be
265// UTF-8 formatted. Output will be UTF-8 formatted.
266string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700267 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
268 // // cpu, considering creating one and caching it.
269 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
270 // xmlNewDoc(ConstXMLStr("1.0")));
271 // if (!xml_doc.get()) {
272 // LOG(ERROR) << "Unable to create xmlDoc";
273 // return "";
274 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000275 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
276 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
277 return string(reinterpret_cast<const char *>(str.get()));
278}
279
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800280OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700281 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700282 HttpFetcher* http_fetcher,
283 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800284 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700285 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700286 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700287 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700288 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700289 ping_roll_call_days_(0) {
290 params_ = system_state->request_params();
291}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000292
Darin Petkov6a5b3222010-07-13 14:55:28 -0700293OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000294
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700295// Calculates the value to use for the ping days parameter.
296int OmahaRequestAction::CalculatePingDays(const string& key) {
297 int days = kNeverPinged;
298 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800299 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700300 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
301 if (days < 0) {
302 // If |days| is negative, then the system clock must have jumped
303 // back in time since the ping was sent. Mark the value so that
304 // it doesn't get sent to the server but we still update the
305 // last ping daystart preference. This way the next ping time
306 // will be correct, hopefully.
307 days = kPingTimeJump;
308 LOG(WARNING) <<
309 "System clock jumped back in time. Resetting ping daystarts.";
310 }
311 }
312 return days;
313}
314
315void OmahaRequestAction::InitPingDays() {
316 // We send pings only along with update checks, not with events.
317 if (IsEvent()) {
318 return;
319 }
320 // TODO(petkov): Figure a way to distinguish active use pings
321 // vs. roll call pings. Currently, the two pings are identical. A
322 // fix needs to change this code as well as UpdateLastPingDays.
323 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
324 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
325}
326
Darin Petkov6a5b3222010-07-13 14:55:28 -0700327void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000328 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700329 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700330 if (ping_only_ &&
331 !ShouldPing(ping_active_days_) &&
332 !ShouldPing(ping_roll_call_days_)) {
333 processor_->ActionComplete(this, kActionCodeSuccess);
334 return;
335 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700336 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700337 *params_,
Thieu Le116fda32011-04-19 11:01:54 -0700338 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700339 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800340 ping_roll_call_days_,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700341 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700342
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800343 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
344 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700345 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700346 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700347 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000348}
349
Darin Petkov6a5b3222010-07-13 14:55:28 -0700350void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000351 http_fetcher_->TerminateTransfer();
352}
353
354// We just store the response in the buffer. Once we've received all bytes,
355// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700356void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
357 const char* bytes,
358 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000359 response_buffer_.reserve(response_buffer_.size() + length);
360 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
361}
362
363namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000364// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
365// on the returned object.
366// This code is roughly based on the libxml tutorial at:
367// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700368xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000369 xmlXPathObject* result = NULL;
370
371 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
372 xmlXPathNewContext(doc));
373 if (!context.get()) {
374 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
375 return NULL;
376 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000377
378 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000379 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700380 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000381 return NULL;
382 }
383 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700384 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000385 xmlXPathFreeObject(result);
386 return NULL;
387 }
388 return result;
389}
390
391// Returns the string value of a named attribute on a node, or empty string
392// if no such node exists. If the attribute exists and has a value of
393// empty string, there's no way to distinguish that from the attribute
394// not existing.
395string XmlGetProperty(xmlNode* node, const char* name) {
396 if (!xmlHasProp(node, ConstXMLStr(name)))
397 return "";
398 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
399 xmlGetProp(node, ConstXMLStr(name)));
400 string ret(reinterpret_cast<const char *>(str.get()));
401 return ret;
402}
403
404// Parses a 64 bit base-10 int from a string and returns it. Returns 0
405// on error. If the string contains "0", that's indistinguishable from
406// error.
407off_t ParseInt(const string& str) {
408 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700409 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000410 if (rc < 1) {
411 // failure
412 return 0;
413 }
414 return ret;
415}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700416
417// Update the last ping day preferences based on the server daystart
418// response. Returns true on success, false otherwise.
419bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700420 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700421
422 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700423 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700424 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
425 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
426 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
427 xmlNode* daystart_node = nodeset->nodeTab[0];
428 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
429 ConstXMLStr("elapsed_seconds")));
430
431 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700432 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
433 "elapsed_seconds"),
434 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700435 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
436
437 // Remember the local time that matches the server's last midnight
438 // time.
439 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
440 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
441 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
442 return true;
443}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000444} // namespace {}
445
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700446bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
447 OmahaResponse* output_object,
448 ScopedActionCompleter* completer) {
449 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
450
451 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
452 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
453 if (!xpath_nodeset.get()) {
454 completer->set_code(kActionCodeOmahaResponseInvalid);
455 return false;
456 }
457
458 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
459 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
460 CHECK_GE(nodeset->nodeNr, 1);
461 xmlNode* update_check_node = nodeset->nodeTab[0];
462
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800463 // chromium-os:37289: The PollInterval is not supported by Omaha server
464 // currently. But still keeping this existing code in case we ever decide to
465 // slow down the request rate from the server-side. Note that the
466 // PollInterval is not persisted, so it has to be sent by the server on every
467 // response to guarantee that the UpdateCheckScheduler uses this value
468 // (otherwise, if the device got rebooted after the last server-indicated
469 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
470 // value for the scattering logic is based on the assumption that we perform
471 // an update check every hour so that the max value of 8 will roughly be
472 // equivalent to one work day. If we decide to use PollInterval permanently,
473 // we should update the max_update_checks_allowed to take PollInterval into
474 // account. Note: The parsing for PollInterval happens even before parsing
475 // of the status because we may want to specify the PollInterval even when
476 // there's no update.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700477 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
478 &output_object->poll_interval);
479
480 if (!ParseStatus(update_check_node, output_object, completer))
481 return false;
482
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800483 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
484 // appends the package name to the URLs populated in this method.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700485 if (!ParseUrls(doc, output_object, completer))
486 return false;
487
488 if (!ParsePackage(doc, output_object, completer))
489 return false;
490
491 if (!ParseParams(doc, output_object, completer))
492 return false;
493
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800494 output_object->update_exists = true;
495 SetOutputObject(*output_object);
496 completer->set_code(kActionCodeSuccess);
497
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700498 return true;
499}
500
501bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
502 OmahaResponse* output_object,
503 ScopedActionCompleter* completer) {
504 // Get status.
505 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
506 LOG(ERROR) << "Omaha Response missing status";
507 completer->set_code(kActionCodeOmahaResponseInvalid);
508 return false;
509 }
510
511 const string status(XmlGetProperty(update_check_node, "status"));
512 if (status == "noupdate") {
513 LOG(INFO) << "No update.";
514 output_object->update_exists = false;
515 SetOutputObject(*output_object);
516 completer->set_code(kActionCodeSuccess);
517 return false;
518 }
519
520 if (status != "ok") {
521 LOG(ERROR) << "Unknown Omaha response status: " << status;
522 completer->set_code(kActionCodeOmahaResponseInvalid);
523 return false;
524 }
525
526 return true;
527}
528
529bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
530 OmahaResponse* output_object,
531 ScopedActionCompleter* completer) {
532 // Get the update URL.
533 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
534
535 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
536 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
537 if (!xpath_nodeset.get()) {
538 completer->set_code(kActionCodeOmahaResponseInvalid);
539 return false;
540 }
541
542 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
543 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
544 CHECK_GE(nodeset->nodeNr, 1);
545
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800546 LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)";
547 output_object->payload_urls.clear();
548 for (int i = 0; i < nodeset->nodeNr; i++) {
549 xmlNode* url_node = nodeset->nodeTab[i];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700550
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800551 const string codebase(XmlGetProperty(url_node, "codebase"));
552 if (codebase.empty()) {
553 LOG(ERROR) << "Omaha Response URL has empty codebase";
554 completer->set_code(kActionCodeOmahaResponseInvalid);
555 return false;
556 }
557 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700558 }
559
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700560 return true;
561}
562
563bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
564 OmahaResponse* output_object,
565 ScopedActionCompleter* completer) {
566 // Get the package node.
567 static const char* kPackageNodeXPath(
568 "/response/app/updatecheck/manifest/packages/package");
569
570 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
571 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
572 if (!xpath_nodeset.get()) {
573 completer->set_code(kActionCodeOmahaResponseInvalid);
574 return false;
575 }
576
577 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
578 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
579 CHECK_GE(nodeset->nodeNr, 1);
580
581 // We only care about the first package.
582 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
583 xmlNode* package_node = nodeset->nodeTab[0];
584
585 // Get package properties one by one.
586
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800587 // Parse the payload name to be appended to the base Url value.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700588 const string package_name(XmlGetProperty(package_node, "name"));
589 LOG(INFO) << "Omaha Response package name = " << package_name;
590 if (package_name.empty()) {
591 LOG(ERROR) << "Omaha Response has empty package name";
592 completer->set_code(kActionCodeOmahaResponseInvalid);
593 return false;
594 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800595
596 // Append the package name to each URL in our list so that we don't
597 // propagate the urlBase vs packageName distinctions beyond this point.
598 // From now on, we only need to use payload_urls.
599 for (size_t i = 0; i < output_object->payload_urls.size(); i++) {
600 output_object->payload_urls[i] += package_name;
601 LOG(INFO) << "Url" << i << ": " << output_object->payload_urls[i];
602 }
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700603
604 // Parse the payload size.
605 off_t size = ParseInt(XmlGetProperty(package_node, "size"));
606 if (size <= 0) {
607 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
608 completer->set_code(kActionCodeOmahaResponseInvalid);
609 return false;
610 }
611 output_object->size = size;
612
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800613 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700614
615 return true;
616}
617
618bool OmahaRequestAction::ParseParams(xmlDoc* doc,
619 OmahaResponse* output_object,
620 ScopedActionCompleter* completer) {
621 // Get the action node where parameters are present.
622 static const char* kActionNodeXPath(
623 "/response/app/updatecheck/manifest/actions/action");
624
625 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
626 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
627 if (!xpath_nodeset.get()) {
628 completer->set_code(kActionCodeOmahaResponseInvalid);
629 return false;
630 }
631
632 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
633 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
634
635 // We only care about the action that has event "postinall", because this is
636 // where Omaha puts all the generic name/value pairs in the rule.
637 LOG(INFO) << "Found " << nodeset->nodeNr
638 << " action(s). Processing the postinstall action.";
639
640 // pie_action_node holds the action node corresponding to the
641 // postinstall event action, if present.
642 xmlNode* pie_action_node = NULL;
643 for (int i = 0; i < nodeset->nodeNr; i++) {
644 xmlNode* action_node = nodeset->nodeTab[i];
645 if (XmlGetProperty(action_node, "event") == "postinstall") {
646 pie_action_node = action_node;
647 break;
648 }
649 }
650
651 if (!pie_action_node) {
652 LOG(ERROR) << "Omaha Response has no postinstall event action";
653 completer->set_code(kActionCodeOmahaResponseInvalid);
654 return false;
655 }
656
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800657 output_object->hash = XmlGetProperty(pie_action_node, kTagSha256);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700658 if (output_object->hash.empty()) {
659 LOG(ERROR) << "Omaha Response has empty sha256 value";
660 completer->set_code(kActionCodeOmahaResponseInvalid);
661 return false;
662 }
663
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800664 // Get the optional properties one by one.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700665 output_object->display_version =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800666 XmlGetProperty(pie_action_node, kTagDisplayVersion);
667 output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700668 output_object->metadata_size =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800669 ParseInt(XmlGetProperty(pie_action_node, kTagMetadataSize));
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700670 output_object->metadata_signature =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800671 XmlGetProperty(pie_action_node, kTagMetadataSignatureRsa);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700672 output_object->needs_admin =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800673 XmlGetProperty(pie_action_node, kTagNeedsAdmin) == "true";
674 output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true";
675 output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700676 output_object->max_days_to_scatter =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800677 ParseInt(XmlGetProperty(pie_action_node, kTagMaxDaysToScatter));
678
679 string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl);
Jay Srinivasan08262882012-12-28 19:29:43 -0800680 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800681 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700682
Jay Srinivasan08262882012-12-28 19:29:43 -0800683 output_object->is_delta_payload =
684 XmlGetProperty(pie_action_node, kTagIsDeltaPayload) == "true";
685
686 output_object->disable_payload_backoff =
687 XmlGetProperty(pie_action_node, kTagDisablePayloadBackoff) == "true";
688
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700689 return true;
690}
691
rspangler@google.com49fdf182009-10-10 00:57:34 +0000692// If the transfer was successful, this uses libxml2 to parse the response
693// and fill in the appropriate fields of the output object. Also, notifies
694// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700695void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
696 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000697 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800698 string current_response(response_buffer_.begin(), response_buffer_.end());
699 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700700
701 // Events are best effort transactions -- assume they always succeed.
702 if (IsEvent()) {
703 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800704 if (event_->result == OmahaEvent::kResultError && successful &&
705 utils::IsOfficialBuild()) {
706 LOG(INFO) << "Signalling Crash Reporter.";
707 utils::ScheduleCrashReporterUpload();
708 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700709 completer.set_code(kActionCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700710 return;
711 }
712
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700713 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700714 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700715 int code = GetHTTPResponseCode();
716 // Makes sure we send sane error values.
717 if (code < 0 || code >= 1000) {
718 code = 999;
719 }
720 completer.set_code(static_cast<ActionExitCode>(
721 kActionCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000722 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700723 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000724
725 // parse our response and fill the fields in the output object
726 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
727 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
728 if (!doc.get()) {
729 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700730 completer.set_code(response_buffer_.empty() ?
731 kActionCodeOmahaRequestEmptyResponseError :
732 kActionCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000733 return;
734 }
735
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700736 // If a ping was sent, update the last ping day preferences based on
737 // the server daystart response.
738 if (ShouldPing(ping_active_days_) ||
739 ShouldPing(ping_roll_call_days_) ||
740 ping_active_days_ == kPingTimeJump ||
741 ping_roll_call_days_ == kPingTimeJump) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800742 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700743 << "Failed to update the last ping day preferences!";
744 }
745
Thieu Le116fda32011-04-19 11:01:54 -0700746 if (!HasOutputPipe()) {
747 // Just set success to whether or not the http transfer succeeded,
748 // which must be true at this point in the code.
749 completer.set_code(kActionCodeSuccess);
750 return;
751 }
752
Darin Petkov6a5b3222010-07-13 14:55:28 -0700753 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700754 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000755 return;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000756
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700757 if (params_->update_disabled()) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700758 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700759 output_object.update_exists = false;
Jay Srinivasan0a708742012-03-20 11:26:12 -0700760 completer.set_code(kActionCodeOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700761 // Note: We could technically delete the UpdateFirstSeenAt state here.
762 // If we do, it'll mean a device has to restart the UpdateFirstSeenAt
763 // and thus help scattering take effect when the AU is turned on again.
764 // On the other hand, it also increases the chance of update starvation if
765 // an admin turns AU on/off more frequently. We choose to err on the side
766 // of preventing starvation at the cost of not applying scattering in
767 // those cases.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700768 return;
769 }
770
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700771 if (ShouldDeferDownload(&output_object)) {
772 output_object.update_exists = false;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700773 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
774 completer.set_code(kActionCodeOmahaUpdateDeferredPerPolicy);
775 return;
776 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800777
778 // Update the payload state with the current response. The payload state
779 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800780 // from what's stored already. We are updating the payload state as late
781 // as possible in this method so that if a new release gets pushed and then
782 // got pulled back due to some issues, we don't want to clear our internal
783 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800784 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800785 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800786
787 if (payload_state->ShouldBackoffDownload()) {
788 output_object.update_exists = false;
789 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
790 "attempts";
791 completer.set_code(kActionCodeOmahaUpdateDeferredForBackoff);
792 return;
793 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000794}
795
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700796bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700797 // We should defer the downloads only if we've first satisfied the
798 // wall-clock-based-waiting period and then the update-check-based waiting
799 // period, if required.
800
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700801 if (!params_->wall_clock_based_wait_enabled()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700802 // Wall-clock-based waiting period is not enabled, so no scattering needed.
803 return false;
804 }
805
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700806 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700807 case kWallClockWaitNotSatisfied:
808 // We haven't even satisfied the first condition, passing the
809 // wall-clock-based waiting period, so we should defer the downloads
810 // until that happens.
811 LOG(INFO) << "wall-clock-based-wait not satisfied.";
812 return true;
813
814 case kWallClockWaitDoneButUpdateCheckWaitRequired:
815 LOG(INFO) << "wall-clock-based-wait satisfied and "
816 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700817 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700818
819 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
820 // Wall-clock-based waiting period is satisfied, and it's determined
821 // that we do not need the update-check-based wait. so no need to
822 // defer downloads.
823 LOG(INFO) << "wall-clock-based-wait satisfied and "
824 << "update-check-based-wait is not required.";
825 return false;
826
827 default:
828 // Returning false for this default case so we err on the
829 // side of downloading updates than deferring in case of any bugs.
830 NOTREACHED();
831 return false;
832 }
833}
834
835OmahaRequestAction::WallClockWaitResult
836OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700837 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700838 Time update_first_seen_at;
839 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700840
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800841 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
842 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
843 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700844 // Note: This timestamp could be that of ANY update we saw in the past
845 // (not necessarily this particular update we're considering to apply)
846 // but never got to apply because of some reason (e.g. stop AU policy,
847 // updates being pulled out from Omaha, changes in target version prefix,
848 // new update being rolled out, etc.). But for the purposes of scattering
849 // it doesn't matter which update the timestamp corresponds to. i.e.
850 // the clock starts ticking the first time we see an update and we're
851 // ready to apply when the random wait period is satisfied relative to
852 // that first seen timestamp.
853 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
854 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
855 << utils::ToString(update_first_seen_at);
856 } else {
857 // This seems like an unexpected error where the persisted value exists
858 // but it's not readable for some reason. Just skip scattering in this
859 // case to be safe.
860 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
861 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
862 }
863 } else {
864 update_first_seen_at = Time::Now();
865 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800866 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
867 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700868 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
869 << utils::ToString(update_first_seen_at);
870 }
871 else {
872 // This seems like an unexpected error where the value cannot be
873 // persisted for some reason. Just skip scattering in this
874 // case to be safe.
875 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
876 << utils::ToString(update_first_seen_at)
877 << " cannot be persisted";
878 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
879 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700880 }
881
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700882 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700883 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700884 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700885
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700886 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700887 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700888 << ", Time Elapsed = "
889 << utils::FormatSecs(elapsed_time.InSeconds())
890 << ", MaxDaysToScatter = "
891 << max_scatter_period.InDays();
892
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700893 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700894 // The deadline is set for all rules which serve a delta update from a
895 // previous FSI, which means this update will be applied mostly in OOBE
896 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
897 // quickly.
898 LOG(INFO) << "Not scattering as deadline flag is set";
899 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
900 }
901
902 if (max_scatter_period.InDays() == 0) {
903 // This means the Omaha rule creator decides that this rule
904 // should not be scattered irrespective of the policy.
905 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
906 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
907 }
908
909 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700910 // This means we've waited more than the upperbound wait in the rule
911 // from the time we first saw a valid update available to us.
912 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700913 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
914 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
915 }
916
917 // This means we are required to participate in scattering.
918 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700919 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700920 if (remaining_wait_time.InSeconds() <= 0) {
921 // Yes, it's our turn now.
922 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
923
924 // But we can't download until the update-check-count-based wait is also
925 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700926 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700927 kWallClockWaitDoneButUpdateCheckWaitRequired :
928 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
929 }
930
931 // Not our turn yet, so we have to wait until our turn to
932 // help scatter the downloads across all clients of the enterprise.
933 LOG(INFO) << "Update deferred for another "
934 << utils::FormatSecs(remaining_wait_time.InSeconds())
935 << " per policy.";
936 return kWallClockWaitNotSatisfied;
937}
938
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700939bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700940 int64 update_check_count_value;
941
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800942 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
943 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
944 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700945 // We are unable to read the update check count from file for some reason.
946 // So let's proceed anyway so as to not stall the update.
947 LOG(ERROR) << "Unable to read update check count. "
948 << "Skipping update-check-count-based-wait.";
949 return true;
950 }
951 } else {
952 // This file does not exist. This means we haven't started our update
953 // check count down yet, so this is the right time to start the count down.
954 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700955 params_->min_update_checks_needed(),
956 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700957
958 LOG(INFO) << "Randomly picked update check count value = "
959 << update_check_count_value;
960
961 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800962 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
963 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700964 // We weren't able to write the update check count file for some reason.
965 // So let's proceed anyway so as to not stall the update.
966 LOG(ERROR) << "Unable to write update check count. "
967 << "Skipping update-check-count-based-wait.";
968 return true;
969 }
970 }
971
972 if (update_check_count_value == 0) {
973 LOG(INFO) << "Successfully passed the update-check-based-wait.";
974 return true;
975 }
976
977 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700978 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700979 // We err on the side of skipping scattering logic instead of stalling
980 // a machine from receiving any updates in case of any unexpected state.
981 LOG(ERROR) << "Invalid value for update check count detected. "
982 << "Skipping update-check-count-based-wait.";
983 return true;
984 }
985
986 // Legal value, we need to wait for more update checks to happen
987 // until this becomes 0.
988 LOG(INFO) << "Deferring Omaha updates for another "
989 << update_check_count_value
990 << " update checks per policy";
991 return false;
992}
993
994} // namespace chromeos_update_engine
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700995
996