blob: 6391208ad9dce0e8547ae9d186bc4711c8b4a9fc [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,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700116 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700117 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 Srinivasan1c0fe792013-03-28 16:45:25 -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,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700174 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700175 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.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700186 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700187 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=\"" +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700190 XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700191 } else {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700192 app_versions = "version=\"" + XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700193 }
194
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700195 string download_channel = params->download_channel();
196 string app_channels = "track=\"" + XmlEncode(download_channel) + "\" ";
197 if (params->current_channel() != download_channel)
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700198 app_channels +=
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700199 "from_track=\"" + XmlEncode(params->current_channel()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700200
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700201 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700202
203 // Use the default app_id only if we're asking for an update on the
204 // canary-channel. Otherwise, use the board's app_id.
205 string request_app_id =
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700206 (download_channel == "canary-channel" ?
207 params->app_id() : params->board_app_id());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700208 string app_xml =
209 " <app appid=\"" + XmlEncode(request_app_id) + "\" " +
210 app_versions +
211 app_channels +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700212 "lang=\"" + XmlEncode(params->app_lang()) + "\" " +
213 "board=\"" + XmlEncode(params->os_board()) + "\" " +
214 "hardware_class=\"" + XmlEncode(params->hwid()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700215 "delta_okay=\"" + delta_okay_str + "\" "
216 ">\n" +
217 app_body +
218 " </app>\n";
219
220 return app_xml;
221}
222
223// Returns an XML that corresponds to the entire <os> node of the Omaha
224// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700225string GetOsXml(OmahaRequestParams* params) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700226 string os_xml =
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700227 " <os version=\"" + XmlEncode(params->os_version()) + "\" " +
228 "platform=\"" + XmlEncode(params->os_platform()) + "\" " +
229 "sp=\"" + XmlEncode(params->os_sp()) + "\">"
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700230 "</os>\n";
231 return os_xml;
232}
233
234// Returns an XML that corresponds to the entire Omaha request based on the
235// given parameters.
236string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700237 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700238 bool ping_only,
239 int ping_active_days,
240 int ping_roll_call_days,
241 SystemState* system_state) {
242 string os_xml = GetOsXml(params);
243 string app_xml = GetAppXml(event, params, ping_only, ping_active_days,
244 ping_roll_call_days, system_state);
245
246 string install_source = StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700247 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700248
249 string request_xml =
250 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700251 "<request protocol=\"3.0\" "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700252 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
253 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" " +
254 install_source +
255 "ismachine=\"1\">\n" +
256 os_xml +
257 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700258 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700259
260 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000261}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700262
rspangler@google.com49fdf182009-10-10 00:57:34 +0000263} // namespace {}
264
265// Encodes XML entities in a given string with libxml2. input must be
266// UTF-8 formatted. Output will be UTF-8 formatted.
267string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700268 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
269 // // cpu, considering creating one and caching it.
270 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
271 // xmlNewDoc(ConstXMLStr("1.0")));
272 // if (!xml_doc.get()) {
273 // LOG(ERROR) << "Unable to create xmlDoc";
274 // return "";
275 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000276 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
277 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
278 return string(reinterpret_cast<const char *>(str.get()));
279}
280
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800281OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700282 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700283 HttpFetcher* http_fetcher,
284 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800285 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700286 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700287 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700288 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700289 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700290 ping_roll_call_days_(0) {
291 params_ = system_state->request_params();
292}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000293
Darin Petkov6a5b3222010-07-13 14:55:28 -0700294OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000295
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700296// Calculates the value to use for the ping days parameter.
297int OmahaRequestAction::CalculatePingDays(const string& key) {
298 int days = kNeverPinged;
299 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800300 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700301 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
302 if (days < 0) {
303 // If |days| is negative, then the system clock must have jumped
304 // back in time since the ping was sent. Mark the value so that
305 // it doesn't get sent to the server but we still update the
306 // last ping daystart preference. This way the next ping time
307 // will be correct, hopefully.
308 days = kPingTimeJump;
309 LOG(WARNING) <<
310 "System clock jumped back in time. Resetting ping daystarts.";
311 }
312 }
313 return days;
314}
315
316void OmahaRequestAction::InitPingDays() {
317 // We send pings only along with update checks, not with events.
318 if (IsEvent()) {
319 return;
320 }
321 // TODO(petkov): Figure a way to distinguish active use pings
322 // vs. roll call pings. Currently, the two pings are identical. A
323 // fix needs to change this code as well as UpdateLastPingDays.
324 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
325 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
326}
327
Darin Petkov6a5b3222010-07-13 14:55:28 -0700328void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000329 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700330 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700331 if (ping_only_ &&
332 !ShouldPing(ping_active_days_) &&
333 !ShouldPing(ping_roll_call_days_)) {
334 processor_->ActionComplete(this, kActionCodeSuccess);
335 return;
336 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700337 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700338 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700339 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700340 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800341 ping_roll_call_days_,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700342 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700343
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800344 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
345 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700346 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700347 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700348 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000349}
350
Darin Petkov6a5b3222010-07-13 14:55:28 -0700351void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000352 http_fetcher_->TerminateTransfer();
353}
354
355// We just store the response in the buffer. Once we've received all bytes,
356// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700357void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
358 const char* bytes,
359 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000360 response_buffer_.reserve(response_buffer_.size() + length);
361 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
362}
363
364namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000365// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
366// on the returned object.
367// This code is roughly based on the libxml tutorial at:
368// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700369xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000370 xmlXPathObject* result = NULL;
371
372 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
373 xmlXPathNewContext(doc));
374 if (!context.get()) {
375 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
376 return NULL;
377 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000378
379 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000380 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700381 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000382 return NULL;
383 }
384 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700385 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000386 xmlXPathFreeObject(result);
387 return NULL;
388 }
389 return result;
390}
391
392// Returns the string value of a named attribute on a node, or empty string
393// if no such node exists. If the attribute exists and has a value of
394// empty string, there's no way to distinguish that from the attribute
395// not existing.
396string XmlGetProperty(xmlNode* node, const char* name) {
397 if (!xmlHasProp(node, ConstXMLStr(name)))
398 return "";
399 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
400 xmlGetProp(node, ConstXMLStr(name)));
401 string ret(reinterpret_cast<const char *>(str.get()));
402 return ret;
403}
404
405// Parses a 64 bit base-10 int from a string and returns it. Returns 0
406// on error. If the string contains "0", that's indistinguishable from
407// error.
408off_t ParseInt(const string& str) {
409 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700410 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000411 if (rc < 1) {
412 // failure
413 return 0;
414 }
415 return ret;
416}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700417
418// Update the last ping day preferences based on the server daystart
419// response. Returns true on success, false otherwise.
420bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700421 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700422
423 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700424 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700425 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
426 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
427 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
428 xmlNode* daystart_node = nodeset->nodeTab[0];
429 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
430 ConstXMLStr("elapsed_seconds")));
431
432 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700433 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
434 "elapsed_seconds"),
435 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700436 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
437
438 // Remember the local time that matches the server's last midnight
439 // time.
440 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
441 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
442 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
443 return true;
444}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000445} // namespace {}
446
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700447bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
448 OmahaResponse* output_object,
449 ScopedActionCompleter* completer) {
450 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
451
452 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
453 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
454 if (!xpath_nodeset.get()) {
455 completer->set_code(kActionCodeOmahaResponseInvalid);
456 return false;
457 }
458
459 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
460 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
461 CHECK_GE(nodeset->nodeNr, 1);
462 xmlNode* update_check_node = nodeset->nodeTab[0];
463
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800464 // chromium-os:37289: The PollInterval is not supported by Omaha server
465 // currently. But still keeping this existing code in case we ever decide to
466 // slow down the request rate from the server-side. Note that the
467 // PollInterval is not persisted, so it has to be sent by the server on every
468 // response to guarantee that the UpdateCheckScheduler uses this value
469 // (otherwise, if the device got rebooted after the last server-indicated
470 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
471 // value for the scattering logic is based on the assumption that we perform
472 // an update check every hour so that the max value of 8 will roughly be
473 // equivalent to one work day. If we decide to use PollInterval permanently,
474 // we should update the max_update_checks_allowed to take PollInterval into
475 // account. Note: The parsing for PollInterval happens even before parsing
476 // of the status because we may want to specify the PollInterval even when
477 // there's no update.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700478 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
479 &output_object->poll_interval);
480
481 if (!ParseStatus(update_check_node, output_object, completer))
482 return false;
483
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800484 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
485 // appends the package name to the URLs populated in this method.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700486 if (!ParseUrls(doc, output_object, completer))
487 return false;
488
489 if (!ParsePackage(doc, output_object, completer))
490 return false;
491
492 if (!ParseParams(doc, output_object, completer))
493 return false;
494
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800495 output_object->update_exists = true;
496 SetOutputObject(*output_object);
497 completer->set_code(kActionCodeSuccess);
498
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700499 return true;
500}
501
502bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
503 OmahaResponse* output_object,
504 ScopedActionCompleter* completer) {
505 // Get status.
506 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
507 LOG(ERROR) << "Omaha Response missing status";
508 completer->set_code(kActionCodeOmahaResponseInvalid);
509 return false;
510 }
511
512 const string status(XmlGetProperty(update_check_node, "status"));
513 if (status == "noupdate") {
514 LOG(INFO) << "No update.";
515 output_object->update_exists = false;
516 SetOutputObject(*output_object);
517 completer->set_code(kActionCodeSuccess);
518 return false;
519 }
520
521 if (status != "ok") {
522 LOG(ERROR) << "Unknown Omaha response status: " << status;
523 completer->set_code(kActionCodeOmahaResponseInvalid);
524 return false;
525 }
526
527 return true;
528}
529
530bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
531 OmahaResponse* output_object,
532 ScopedActionCompleter* completer) {
533 // Get the update URL.
534 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
535
536 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
537 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
538 if (!xpath_nodeset.get()) {
539 completer->set_code(kActionCodeOmahaResponseInvalid);
540 return false;
541 }
542
543 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
544 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
545 CHECK_GE(nodeset->nodeNr, 1);
546
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800547 LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)";
548 output_object->payload_urls.clear();
549 for (int i = 0; i < nodeset->nodeNr; i++) {
550 xmlNode* url_node = nodeset->nodeTab[i];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700551
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800552 const string codebase(XmlGetProperty(url_node, "codebase"));
553 if (codebase.empty()) {
554 LOG(ERROR) << "Omaha Response URL has empty codebase";
555 completer->set_code(kActionCodeOmahaResponseInvalid);
556 return false;
557 }
558 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700559 }
560
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700561 return true;
562}
563
564bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
565 OmahaResponse* output_object,
566 ScopedActionCompleter* completer) {
567 // Get the package node.
568 static const char* kPackageNodeXPath(
569 "/response/app/updatecheck/manifest/packages/package");
570
571 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
572 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
573 if (!xpath_nodeset.get()) {
574 completer->set_code(kActionCodeOmahaResponseInvalid);
575 return false;
576 }
577
578 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
579 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
580 CHECK_GE(nodeset->nodeNr, 1);
581
582 // We only care about the first package.
583 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
584 xmlNode* package_node = nodeset->nodeTab[0];
585
586 // Get package properties one by one.
587
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800588 // Parse the payload name to be appended to the base Url value.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700589 const string package_name(XmlGetProperty(package_node, "name"));
590 LOG(INFO) << "Omaha Response package name = " << package_name;
591 if (package_name.empty()) {
592 LOG(ERROR) << "Omaha Response has empty package name";
593 completer->set_code(kActionCodeOmahaResponseInvalid);
594 return false;
595 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800596
597 // Append the package name to each URL in our list so that we don't
598 // propagate the urlBase vs packageName distinctions beyond this point.
599 // From now on, we only need to use payload_urls.
600 for (size_t i = 0; i < output_object->payload_urls.size(); i++) {
601 output_object->payload_urls[i] += package_name;
602 LOG(INFO) << "Url" << i << ": " << output_object->payload_urls[i];
603 }
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700604
605 // Parse the payload size.
606 off_t size = ParseInt(XmlGetProperty(package_node, "size"));
607 if (size <= 0) {
608 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
609 completer->set_code(kActionCodeOmahaResponseInvalid);
610 return false;
611 }
612 output_object->size = size;
613
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800614 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700615
616 return true;
617}
618
619bool OmahaRequestAction::ParseParams(xmlDoc* doc,
620 OmahaResponse* output_object,
621 ScopedActionCompleter* completer) {
622 // Get the action node where parameters are present.
623 static const char* kActionNodeXPath(
624 "/response/app/updatecheck/manifest/actions/action");
625
626 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
627 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
628 if (!xpath_nodeset.get()) {
629 completer->set_code(kActionCodeOmahaResponseInvalid);
630 return false;
631 }
632
633 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
634 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
635
636 // We only care about the action that has event "postinall", because this is
637 // where Omaha puts all the generic name/value pairs in the rule.
638 LOG(INFO) << "Found " << nodeset->nodeNr
639 << " action(s). Processing the postinstall action.";
640
641 // pie_action_node holds the action node corresponding to the
642 // postinstall event action, if present.
643 xmlNode* pie_action_node = NULL;
644 for (int i = 0; i < nodeset->nodeNr; i++) {
645 xmlNode* action_node = nodeset->nodeTab[i];
646 if (XmlGetProperty(action_node, "event") == "postinstall") {
647 pie_action_node = action_node;
648 break;
649 }
650 }
651
652 if (!pie_action_node) {
653 LOG(ERROR) << "Omaha Response has no postinstall event action";
654 completer->set_code(kActionCodeOmahaResponseInvalid);
655 return false;
656 }
657
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800658 output_object->hash = XmlGetProperty(pie_action_node, kTagSha256);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700659 if (output_object->hash.empty()) {
660 LOG(ERROR) << "Omaha Response has empty sha256 value";
661 completer->set_code(kActionCodeOmahaResponseInvalid);
662 return false;
663 }
664
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800665 // Get the optional properties one by one.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700666 output_object->display_version =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800667 XmlGetProperty(pie_action_node, kTagDisplayVersion);
668 output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700669 output_object->metadata_size =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800670 ParseInt(XmlGetProperty(pie_action_node, kTagMetadataSize));
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700671 output_object->metadata_signature =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800672 XmlGetProperty(pie_action_node, kTagMetadataSignatureRsa);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700673 output_object->needs_admin =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800674 XmlGetProperty(pie_action_node, kTagNeedsAdmin) == "true";
675 output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true";
676 output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700677 output_object->max_days_to_scatter =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800678 ParseInt(XmlGetProperty(pie_action_node, kTagMaxDaysToScatter));
679
680 string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl);
Jay Srinivasan08262882012-12-28 19:29:43 -0800681 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800682 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700683
Jay Srinivasan08262882012-12-28 19:29:43 -0800684 output_object->is_delta_payload =
685 XmlGetProperty(pie_action_node, kTagIsDeltaPayload) == "true";
686
687 output_object->disable_payload_backoff =
688 XmlGetProperty(pie_action_node, kTagDisablePayloadBackoff) == "true";
689
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700690 return true;
691}
692
rspangler@google.com49fdf182009-10-10 00:57:34 +0000693// If the transfer was successful, this uses libxml2 to parse the response
694// and fill in the appropriate fields of the output object. Also, notifies
695// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700696void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
697 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000698 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800699 string current_response(response_buffer_.begin(), response_buffer_.end());
700 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700701
702 // Events are best effort transactions -- assume they always succeed.
703 if (IsEvent()) {
704 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800705 if (event_->result == OmahaEvent::kResultError && successful &&
706 utils::IsOfficialBuild()) {
707 LOG(INFO) << "Signalling Crash Reporter.";
708 utils::ScheduleCrashReporterUpload();
709 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700710 completer.set_code(kActionCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700711 return;
712 }
713
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700714 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700715 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700716 int code = GetHTTPResponseCode();
717 // Makes sure we send sane error values.
718 if (code < 0 || code >= 1000) {
719 code = 999;
720 }
721 completer.set_code(static_cast<ActionExitCode>(
722 kActionCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000723 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700724 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000725
726 // parse our response and fill the fields in the output object
727 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
728 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
729 if (!doc.get()) {
730 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700731 completer.set_code(response_buffer_.empty() ?
732 kActionCodeOmahaRequestEmptyResponseError :
733 kActionCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000734 return;
735 }
736
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700737 // If a ping was sent, update the last ping day preferences based on
738 // the server daystart response.
739 if (ShouldPing(ping_active_days_) ||
740 ShouldPing(ping_roll_call_days_) ||
741 ping_active_days_ == kPingTimeJump ||
742 ping_roll_call_days_ == kPingTimeJump) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800743 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700744 << "Failed to update the last ping day preferences!";
745 }
746
Thieu Le116fda32011-04-19 11:01:54 -0700747 if (!HasOutputPipe()) {
748 // Just set success to whether or not the http transfer succeeded,
749 // which must be true at this point in the code.
750 completer.set_code(kActionCodeSuccess);
751 return;
752 }
753
Darin Petkov6a5b3222010-07-13 14:55:28 -0700754 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700755 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000756 return;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000757
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700758 if (params_->update_disabled()) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700759 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700760 output_object.update_exists = false;
Jay Srinivasan0a708742012-03-20 11:26:12 -0700761 completer.set_code(kActionCodeOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700762 // Note: We could technically delete the UpdateFirstSeenAt state here.
763 // If we do, it'll mean a device has to restart the UpdateFirstSeenAt
764 // and thus help scattering take effect when the AU is turned on again.
765 // On the other hand, it also increases the chance of update starvation if
766 // an admin turns AU on/off more frequently. We choose to err on the side
767 // of preventing starvation at the cost of not applying scattering in
768 // those cases.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700769 return;
770 }
771
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700772 if (ShouldDeferDownload(&output_object)) {
773 output_object.update_exists = false;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700774 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
775 completer.set_code(kActionCodeOmahaUpdateDeferredPerPolicy);
776 return;
777 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800778
779 // Update the payload state with the current response. The payload state
780 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800781 // from what's stored already. We are updating the payload state as late
782 // as possible in this method so that if a new release gets pushed and then
783 // got pulled back due to some issues, we don't want to clear our internal
784 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800785 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800786 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800787
788 if (payload_state->ShouldBackoffDownload()) {
789 output_object.update_exists = false;
790 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
791 "attempts";
792 completer.set_code(kActionCodeOmahaUpdateDeferredForBackoff);
793 return;
794 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000795}
796
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700797bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700798 // We should defer the downloads only if we've first satisfied the
799 // wall-clock-based-waiting period and then the update-check-based waiting
800 // period, if required.
801
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700802 if (!params_->wall_clock_based_wait_enabled()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700803 // Wall-clock-based waiting period is not enabled, so no scattering needed.
804 return false;
805 }
806
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700807 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700808 case kWallClockWaitNotSatisfied:
809 // We haven't even satisfied the first condition, passing the
810 // wall-clock-based waiting period, so we should defer the downloads
811 // until that happens.
812 LOG(INFO) << "wall-clock-based-wait not satisfied.";
813 return true;
814
815 case kWallClockWaitDoneButUpdateCheckWaitRequired:
816 LOG(INFO) << "wall-clock-based-wait satisfied and "
817 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700818 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700819
820 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
821 // Wall-clock-based waiting period is satisfied, and it's determined
822 // that we do not need the update-check-based wait. so no need to
823 // defer downloads.
824 LOG(INFO) << "wall-clock-based-wait satisfied and "
825 << "update-check-based-wait is not required.";
826 return false;
827
828 default:
829 // Returning false for this default case so we err on the
830 // side of downloading updates than deferring in case of any bugs.
831 NOTREACHED();
832 return false;
833 }
834}
835
836OmahaRequestAction::WallClockWaitResult
837OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700838 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700839 Time update_first_seen_at;
840 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700841
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800842 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
843 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
844 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700845 // Note: This timestamp could be that of ANY update we saw in the past
846 // (not necessarily this particular update we're considering to apply)
847 // but never got to apply because of some reason (e.g. stop AU policy,
848 // updates being pulled out from Omaha, changes in target version prefix,
849 // new update being rolled out, etc.). But for the purposes of scattering
850 // it doesn't matter which update the timestamp corresponds to. i.e.
851 // the clock starts ticking the first time we see an update and we're
852 // ready to apply when the random wait period is satisfied relative to
853 // that first seen timestamp.
854 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
855 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
856 << utils::ToString(update_first_seen_at);
857 } else {
858 // This seems like an unexpected error where the persisted value exists
859 // but it's not readable for some reason. Just skip scattering in this
860 // case to be safe.
861 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
862 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
863 }
864 } else {
865 update_first_seen_at = Time::Now();
866 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800867 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
868 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700869 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
870 << utils::ToString(update_first_seen_at);
871 }
872 else {
873 // This seems like an unexpected error where the value cannot be
874 // persisted for some reason. Just skip scattering in this
875 // case to be safe.
876 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
877 << utils::ToString(update_first_seen_at)
878 << " cannot be persisted";
879 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
880 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700881 }
882
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700883 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700884 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700885 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700886
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700887 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700888 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700889 << ", Time Elapsed = "
890 << utils::FormatSecs(elapsed_time.InSeconds())
891 << ", MaxDaysToScatter = "
892 << max_scatter_period.InDays();
893
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700894 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700895 // The deadline is set for all rules which serve a delta update from a
896 // previous FSI, which means this update will be applied mostly in OOBE
897 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
898 // quickly.
899 LOG(INFO) << "Not scattering as deadline flag is set";
900 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
901 }
902
903 if (max_scatter_period.InDays() == 0) {
904 // This means the Omaha rule creator decides that this rule
905 // should not be scattered irrespective of the policy.
906 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
907 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
908 }
909
910 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700911 // This means we've waited more than the upperbound wait in the rule
912 // from the time we first saw a valid update available to us.
913 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700914 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
915 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
916 }
917
918 // This means we are required to participate in scattering.
919 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700920 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700921 if (remaining_wait_time.InSeconds() <= 0) {
922 // Yes, it's our turn now.
923 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
924
925 // But we can't download until the update-check-count-based wait is also
926 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700927 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700928 kWallClockWaitDoneButUpdateCheckWaitRequired :
929 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
930 }
931
932 // Not our turn yet, so we have to wait until our turn to
933 // help scatter the downloads across all clients of the enterprise.
934 LOG(INFO) << "Update deferred for another "
935 << utils::FormatSecs(remaining_wait_time.InSeconds())
936 << " per policy.";
937 return kWallClockWaitNotSatisfied;
938}
939
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700940bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700941 int64 update_check_count_value;
942
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800943 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
944 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
945 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700946 // We are unable to read the update check count from file for some reason.
947 // So let's proceed anyway so as to not stall the update.
948 LOG(ERROR) << "Unable to read update check count. "
949 << "Skipping update-check-count-based-wait.";
950 return true;
951 }
952 } else {
953 // This file does not exist. This means we haven't started our update
954 // check count down yet, so this is the right time to start the count down.
955 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700956 params_->min_update_checks_needed(),
957 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700958
959 LOG(INFO) << "Randomly picked update check count value = "
960 << update_check_count_value;
961
962 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800963 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
964 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700965 // We weren't able to write the update check count file for some reason.
966 // So let's proceed anyway so as to not stall the update.
967 LOG(ERROR) << "Unable to write update check count. "
968 << "Skipping update-check-count-based-wait.";
969 return true;
970 }
971 }
972
973 if (update_check_count_value == 0) {
974 LOG(INFO) << "Successfully passed the update-check-based-wait.";
975 return true;
976 }
977
978 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700979 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700980 // We err on the side of skipping scattering logic instead of stalling
981 // a machine from receiving any updates in case of any unexpected state.
982 LOG(ERROR) << "Invalid value for update check count detected. "
983 << "Skipping update-check-count-based-wait.";
984 return true;
985 }
986
987 // Legal value, we need to wait for more update checks to happen
988 // until this becomes 0.
989 LOG(INFO) << "Deferring Omaha updates for another "
990 << update_check_count_value
991 << " update checks per policy";
992 return false;
993}
994
995} // namespace chromeos_update_engine
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700996
997