blob: 043ec1df52fb81f1425ec438f7c61e41925c0027 [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"
Jay Srinivasand29695d2013-04-08 15:08:05 -070022#include "update_engine/constants.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070023#include "update_engine/omaha_request_params.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080024#include "update_engine/payload_state_interface.h"
Darin Petkov1cbd78f2010-07-29 12:38:34 -070025#include "update_engine/prefs_interface.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000026#include "update_engine/utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000027
Darin Petkov1cbd78f2010-07-29 12:38:34 -070028using base::Time;
29using base::TimeDelta;
rspangler@google.com49fdf182009-10-10 00:57:34 +000030using std::string;
31
32namespace chromeos_update_engine {
33
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080034// List of custom pair tags that we interpret in the Omaha Response:
35static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080036static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080037static const char* kTagDisplayVersion = "DisplayVersion";
Jay Srinivasand671e972013-01-11 17:17:19 -080038// Deprecated: "IsDelta"
39static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080040static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
41static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
42// Deprecated: "ManifestSignatureRsa"
43// Deprecated: "ManifestSize"
44static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
45static const char* kTagMetadataSize = "MetadataSize";
46static const char* kTagMoreInfo = "MoreInfo";
47static const char* kTagNeedsAdmin = "needsadmin";
48static const char* kTagPrompt = "Prompt";
49static const char* kTagSha256 = "sha256";
50
rspangler@google.com49fdf182009-10-10 00:57:34 +000051namespace {
52
53const string kGupdateVersion("ChromeOSUpdateEngine-0.1.0.0");
54
55// This is handy for passing strings into libxml2
56#define ConstXMLStr(x) (reinterpret_cast<const xmlChar*>(x))
57
58// These are for scoped_ptr_malloc, which is like scoped_ptr, but allows
59// a custom free() function to be specified.
60class ScopedPtrXmlDocFree {
61 public:
62 inline void operator()(void* x) const {
63 xmlFreeDoc(reinterpret_cast<xmlDoc*>(x));
64 }
65};
66class ScopedPtrXmlFree {
67 public:
68 inline void operator()(void* x) const {
69 xmlFree(x);
70 }
71};
72class ScopedPtrXmlXPathObjectFree {
73 public:
74 inline void operator()(void* x) const {
75 xmlXPathFreeObject(reinterpret_cast<xmlXPathObject*>(x));
76 }
77};
78class ScopedPtrXmlXPathContextFree {
79 public:
80 inline void operator()(void* x) const {
81 xmlXPathFreeContext(reinterpret_cast<xmlXPathContext*>(x));
82 }
83};
84
Darin Petkov1cbd78f2010-07-29 12:38:34 -070085// Returns true if |ping_days| has a value that needs to be sent,
86// false otherwise.
87bool ShouldPing(int ping_days) {
88 return ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged;
89}
90
91// Returns an XML ping element attribute assignment with attribute
92// |name| and value |ping_days| if |ping_days| has a value that needs
93// to be sent, or an empty string otherwise.
94string GetPingAttribute(const string& name, int ping_days) {
95 if (ShouldPing(ping_days)) {
96 return StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
97 }
98 return "";
99}
100
101// Returns an XML ping element if any of the elapsed days need to be
102// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700103string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700104 string ping_active = GetPingAttribute("a", ping_active_days);
105 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
106 if (!ping_active.empty() || !ping_roll_call.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700107 return StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700108 ping_active.c_str(),
109 ping_roll_call.c_str());
110 }
111 return "";
112}
113
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700114// Returns an XML that goes into the body of the <app> element of the Omaha
115// request based on the given parameters.
116string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700117 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700118 bool ping_only,
119 int ping_active_days,
120 int ping_roll_call_days,
121 PrefsInterface* prefs) {
122 string app_body;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700123 if (event == NULL) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700124 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700125 if (!ping_only) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700126 // not passing update_disabled to Omaha because we want to
127 // get the update and report with UpdateDeferred result so that
128 // borgmon charts show up updates that are deferred. This is also
129 // the expected behavior when we move to Omaha v3.0 protocol, so it'll
130 // be consistent.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700131 app_body += StringPrintf(
132 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700133 "></updatecheck>\n",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700134 XmlEncode(params->target_version_prefix()).c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700135
Darin Petkov265f2902011-05-09 15:17:40 -0700136 // If this is the first update check after a reboot following a previous
137 // update, generate an event containing the previous version number. If
138 // the previous version preference file doesn't exist the event is still
139 // generated with a previous version of 0.0.0.0 -- this is relevant for
140 // older clients or new installs. The previous version event is not sent
141 // for ping-only requests because they come before the client has
142 // rebooted.
143 string prev_version;
144 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
145 prev_version = "0.0.0.0";
146 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700147
148 app_body += StringPrintf(
149 " <event eventtype=\"%d\" eventresult=\"%d\" "
150 "previousversion=\"%s\"></event>\n",
151 OmahaEvent::kTypeUpdateComplete,
152 OmahaEvent::kResultSuccessReboot,
153 XmlEncode(prev_version).c_str());
154 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
155 << "Unable to reset the previous version.";
Darin Petkov95508da2011-01-05 12:42:29 -0800156 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700157 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800158 // The error code is an optional attribute so append it only if the result
159 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700160 string error_code;
161 if (event->result != OmahaEvent::kResultSuccess) {
Darin Petkov18c7bce2011-06-16 14:07:00 -0700162 error_code = StringPrintf(" errorcode=\"%d\"", event->error_code);
Darin Petkove17f86b2010-07-20 09:12:01 -0700163 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700164 app_body = StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700165 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700166 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700167 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700168
169 return app_body;
170}
171
172// Returns an XML that corresponds to the entire <app> node of the Omaha
173// request based on the given parameters.
174string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700175 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700176 bool ping_only,
177 int ping_active_days,
178 int ping_roll_call_days,
179 SystemState* system_state) {
180 string app_body = GetAppBody(event, params, ping_only, ping_active_days,
181 ping_roll_call_days, system_state->prefs());
182 string app_versions;
183
184 // If we are upgrading to a more stable channel and we are allowed to do
185 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
186 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700187 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700188 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
189 << "on downgrading to the version in the more stable channel";
190 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700191 XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700192 } else {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700193 app_versions = "version=\"" + XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700194 }
195
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700196 string download_channel = params->download_channel();
197 string app_channels = "track=\"" + XmlEncode(download_channel) + "\" ";
198 if (params->current_channel() != download_channel)
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700199 app_channels +=
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700200 "from_track=\"" + XmlEncode(params->current_channel()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700201
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700202 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700203
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700204 string app_xml =
Jay Srinivasandb0acdf2013-04-02 14:47:45 -0700205 " <app appid=\"" + XmlEncode(params->GetAppId()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700206 app_versions +
207 app_channels +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700208 "lang=\"" + XmlEncode(params->app_lang()) + "\" " +
209 "board=\"" + XmlEncode(params->os_board()) + "\" " +
210 "hardware_class=\"" + XmlEncode(params->hwid()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700211 "delta_okay=\"" + delta_okay_str + "\" "
212 ">\n" +
213 app_body +
214 " </app>\n";
215
216 return app_xml;
217}
218
219// Returns an XML that corresponds to the entire <os> node of the Omaha
220// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700221string GetOsXml(OmahaRequestParams* params) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700222 string os_xml =
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700223 " <os version=\"" + XmlEncode(params->os_version()) + "\" " +
224 "platform=\"" + XmlEncode(params->os_platform()) + "\" " +
225 "sp=\"" + XmlEncode(params->os_sp()) + "\">"
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700226 "</os>\n";
227 return os_xml;
228}
229
230// Returns an XML that corresponds to the entire Omaha request based on the
231// given parameters.
232string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700233 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700234 bool ping_only,
235 int ping_active_days,
236 int ping_roll_call_days,
237 SystemState* system_state) {
238 string os_xml = GetOsXml(params);
239 string app_xml = GetAppXml(event, params, ping_only, ping_active_days,
240 ping_roll_call_days, system_state);
241
242 string install_source = StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700243 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700244
245 string request_xml =
246 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700247 "<request protocol=\"3.0\" "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700248 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
249 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" " +
250 install_source +
251 "ismachine=\"1\">\n" +
252 os_xml +
253 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700254 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700255
256 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000257}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700258
rspangler@google.com49fdf182009-10-10 00:57:34 +0000259} // namespace {}
260
261// Encodes XML entities in a given string with libxml2. input must be
262// UTF-8 formatted. Output will be UTF-8 formatted.
263string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700264 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
265 // // cpu, considering creating one and caching it.
266 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
267 // xmlNewDoc(ConstXMLStr("1.0")));
268 // if (!xml_doc.get()) {
269 // LOG(ERROR) << "Unable to create xmlDoc";
270 // return "";
271 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000272 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
273 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
274 return string(reinterpret_cast<const char *>(str.get()));
275}
276
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800277OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700278 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700279 HttpFetcher* http_fetcher,
280 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800281 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700282 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700283 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700284 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700285 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700286 ping_roll_call_days_(0) {
287 params_ = system_state->request_params();
288}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000289
Darin Petkov6a5b3222010-07-13 14:55:28 -0700290OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000291
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700292// Calculates the value to use for the ping days parameter.
293int OmahaRequestAction::CalculatePingDays(const string& key) {
294 int days = kNeverPinged;
295 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800296 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700297 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
298 if (days < 0) {
299 // If |days| is negative, then the system clock must have jumped
300 // back in time since the ping was sent. Mark the value so that
301 // it doesn't get sent to the server but we still update the
302 // last ping daystart preference. This way the next ping time
303 // will be correct, hopefully.
304 days = kPingTimeJump;
305 LOG(WARNING) <<
306 "System clock jumped back in time. Resetting ping daystarts.";
307 }
308 }
309 return days;
310}
311
312void OmahaRequestAction::InitPingDays() {
313 // We send pings only along with update checks, not with events.
314 if (IsEvent()) {
315 return;
316 }
317 // TODO(petkov): Figure a way to distinguish active use pings
318 // vs. roll call pings. Currently, the two pings are identical. A
319 // fix needs to change this code as well as UpdateLastPingDays.
320 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
321 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
322}
323
Darin Petkov6a5b3222010-07-13 14:55:28 -0700324void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000325 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700326 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700327 if (ping_only_ &&
328 !ShouldPing(ping_active_days_) &&
329 !ShouldPing(ping_roll_call_days_)) {
330 processor_->ActionComplete(this, kActionCodeSuccess);
331 return;
332 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700333 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700334 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700335 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700336 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800337 ping_roll_call_days_,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700338 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700339
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800340 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
341 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700342 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700343 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700344 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000345}
346
Darin Petkov6a5b3222010-07-13 14:55:28 -0700347void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000348 http_fetcher_->TerminateTransfer();
349}
350
351// We just store the response in the buffer. Once we've received all bytes,
352// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700353void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
354 const char* bytes,
355 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000356 response_buffer_.reserve(response_buffer_.size() + length);
357 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
358}
359
360namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000361// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
362// on the returned object.
363// This code is roughly based on the libxml tutorial at:
364// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700365xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000366 xmlXPathObject* result = NULL;
367
368 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
369 xmlXPathNewContext(doc));
370 if (!context.get()) {
371 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
372 return NULL;
373 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000374
375 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000376 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700377 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000378 return NULL;
379 }
380 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700381 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000382 xmlXPathFreeObject(result);
383 return NULL;
384 }
385 return result;
386}
387
388// Returns the string value of a named attribute on a node, or empty string
389// if no such node exists. If the attribute exists and has a value of
390// empty string, there's no way to distinguish that from the attribute
391// not existing.
392string XmlGetProperty(xmlNode* node, const char* name) {
393 if (!xmlHasProp(node, ConstXMLStr(name)))
394 return "";
395 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
396 xmlGetProp(node, ConstXMLStr(name)));
397 string ret(reinterpret_cast<const char *>(str.get()));
398 return ret;
399}
400
401// Parses a 64 bit base-10 int from a string and returns it. Returns 0
402// on error. If the string contains "0", that's indistinguishable from
403// error.
404off_t ParseInt(const string& str) {
405 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700406 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000407 if (rc < 1) {
408 // failure
409 return 0;
410 }
411 return ret;
412}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700413
414// Update the last ping day preferences based on the server daystart
415// response. Returns true on success, false otherwise.
416bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700417 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700418
419 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700420 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700421 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
422 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
423 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
424 xmlNode* daystart_node = nodeset->nodeTab[0];
425 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
426 ConstXMLStr("elapsed_seconds")));
427
428 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700429 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
430 "elapsed_seconds"),
431 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700432 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
433
434 // Remember the local time that matches the server's last midnight
435 // time.
436 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
437 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
438 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
439 return true;
440}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000441} // namespace {}
442
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700443bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
444 OmahaResponse* output_object,
445 ScopedActionCompleter* completer) {
446 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
447
448 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
449 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
450 if (!xpath_nodeset.get()) {
451 completer->set_code(kActionCodeOmahaResponseInvalid);
452 return false;
453 }
454
455 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
456 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
457 CHECK_GE(nodeset->nodeNr, 1);
458 xmlNode* update_check_node = nodeset->nodeTab[0];
459
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800460 // chromium-os:37289: The PollInterval is not supported by Omaha server
461 // currently. But still keeping this existing code in case we ever decide to
462 // slow down the request rate from the server-side. Note that the
463 // PollInterval is not persisted, so it has to be sent by the server on every
464 // response to guarantee that the UpdateCheckScheduler uses this value
465 // (otherwise, if the device got rebooted after the last server-indicated
466 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
467 // value for the scattering logic is based on the assumption that we perform
468 // an update check every hour so that the max value of 8 will roughly be
469 // equivalent to one work day. If we decide to use PollInterval permanently,
470 // we should update the max_update_checks_allowed to take PollInterval into
471 // account. Note: The parsing for PollInterval happens even before parsing
472 // of the status because we may want to specify the PollInterval even when
473 // there's no update.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700474 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
475 &output_object->poll_interval);
476
477 if (!ParseStatus(update_check_node, output_object, completer))
478 return false;
479
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800480 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
481 // appends the package name to the URLs populated in this method.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700482 if (!ParseUrls(doc, output_object, completer))
483 return false;
484
485 if (!ParsePackage(doc, output_object, completer))
486 return false;
487
488 if (!ParseParams(doc, output_object, completer))
489 return false;
490
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800491 output_object->update_exists = true;
492 SetOutputObject(*output_object);
493 completer->set_code(kActionCodeSuccess);
494
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700495 return true;
496}
497
498bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
499 OmahaResponse* output_object,
500 ScopedActionCompleter* completer) {
501 // Get status.
502 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
503 LOG(ERROR) << "Omaha Response missing status";
504 completer->set_code(kActionCodeOmahaResponseInvalid);
505 return false;
506 }
507
508 const string status(XmlGetProperty(update_check_node, "status"));
509 if (status == "noupdate") {
510 LOG(INFO) << "No update.";
511 output_object->update_exists = false;
512 SetOutputObject(*output_object);
513 completer->set_code(kActionCodeSuccess);
514 return false;
515 }
516
517 if (status != "ok") {
518 LOG(ERROR) << "Unknown Omaha response status: " << status;
519 completer->set_code(kActionCodeOmahaResponseInvalid);
520 return false;
521 }
522
523 return true;
524}
525
526bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
527 OmahaResponse* output_object,
528 ScopedActionCompleter* completer) {
529 // Get the update URL.
530 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
531
532 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
533 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
534 if (!xpath_nodeset.get()) {
535 completer->set_code(kActionCodeOmahaResponseInvalid);
536 return false;
537 }
538
539 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
540 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
541 CHECK_GE(nodeset->nodeNr, 1);
542
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800543 LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)";
544 output_object->payload_urls.clear();
545 for (int i = 0; i < nodeset->nodeNr; i++) {
546 xmlNode* url_node = nodeset->nodeTab[i];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700547
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800548 const string codebase(XmlGetProperty(url_node, "codebase"));
549 if (codebase.empty()) {
550 LOG(ERROR) << "Omaha Response URL has empty codebase";
551 completer->set_code(kActionCodeOmahaResponseInvalid);
552 return false;
553 }
554 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700555 }
556
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700557 return true;
558}
559
560bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
561 OmahaResponse* output_object,
562 ScopedActionCompleter* completer) {
563 // Get the package node.
564 static const char* kPackageNodeXPath(
565 "/response/app/updatecheck/manifest/packages/package");
566
567 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
568 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
569 if (!xpath_nodeset.get()) {
570 completer->set_code(kActionCodeOmahaResponseInvalid);
571 return false;
572 }
573
574 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
575 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
576 CHECK_GE(nodeset->nodeNr, 1);
577
578 // We only care about the first package.
579 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
580 xmlNode* package_node = nodeset->nodeTab[0];
581
582 // Get package properties one by one.
583
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800584 // Parse the payload name to be appended to the base Url value.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700585 const string package_name(XmlGetProperty(package_node, "name"));
586 LOG(INFO) << "Omaha Response package name = " << package_name;
587 if (package_name.empty()) {
588 LOG(ERROR) << "Omaha Response has empty package name";
589 completer->set_code(kActionCodeOmahaResponseInvalid);
590 return false;
591 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800592
593 // Append the package name to each URL in our list so that we don't
594 // propagate the urlBase vs packageName distinctions beyond this point.
595 // From now on, we only need to use payload_urls.
596 for (size_t i = 0; i < output_object->payload_urls.size(); i++) {
597 output_object->payload_urls[i] += package_name;
598 LOG(INFO) << "Url" << i << ": " << output_object->payload_urls[i];
599 }
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700600
601 // Parse the payload size.
602 off_t size = ParseInt(XmlGetProperty(package_node, "size"));
603 if (size <= 0) {
604 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
605 completer->set_code(kActionCodeOmahaResponseInvalid);
606 return false;
607 }
608 output_object->size = size;
609
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800610 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700611
612 return true;
613}
614
615bool OmahaRequestAction::ParseParams(xmlDoc* doc,
616 OmahaResponse* output_object,
617 ScopedActionCompleter* completer) {
618 // Get the action node where parameters are present.
619 static const char* kActionNodeXPath(
620 "/response/app/updatecheck/manifest/actions/action");
621
622 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
623 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
624 if (!xpath_nodeset.get()) {
625 completer->set_code(kActionCodeOmahaResponseInvalid);
626 return false;
627 }
628
629 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
630 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
631
632 // We only care about the action that has event "postinall", because this is
633 // where Omaha puts all the generic name/value pairs in the rule.
634 LOG(INFO) << "Found " << nodeset->nodeNr
635 << " action(s). Processing the postinstall action.";
636
637 // pie_action_node holds the action node corresponding to the
638 // postinstall event action, if present.
639 xmlNode* pie_action_node = NULL;
640 for (int i = 0; i < nodeset->nodeNr; i++) {
641 xmlNode* action_node = nodeset->nodeTab[i];
642 if (XmlGetProperty(action_node, "event") == "postinstall") {
643 pie_action_node = action_node;
644 break;
645 }
646 }
647
648 if (!pie_action_node) {
649 LOG(ERROR) << "Omaha Response has no postinstall event action";
650 completer->set_code(kActionCodeOmahaResponseInvalid);
651 return false;
652 }
653
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800654 output_object->hash = XmlGetProperty(pie_action_node, kTagSha256);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700655 if (output_object->hash.empty()) {
656 LOG(ERROR) << "Omaha Response has empty sha256 value";
657 completer->set_code(kActionCodeOmahaResponseInvalid);
658 return false;
659 }
660
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800661 // Get the optional properties one by one.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700662 output_object->display_version =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800663 XmlGetProperty(pie_action_node, kTagDisplayVersion);
664 output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700665 output_object->metadata_size =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800666 ParseInt(XmlGetProperty(pie_action_node, kTagMetadataSize));
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700667 output_object->metadata_signature =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800668 XmlGetProperty(pie_action_node, kTagMetadataSignatureRsa);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700669 output_object->needs_admin =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800670 XmlGetProperty(pie_action_node, kTagNeedsAdmin) == "true";
671 output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true";
672 output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700673 output_object->max_days_to_scatter =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800674 ParseInt(XmlGetProperty(pie_action_node, kTagMaxDaysToScatter));
675
676 string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl);
Jay Srinivasan08262882012-12-28 19:29:43 -0800677 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800678 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700679
Jay Srinivasan08262882012-12-28 19:29:43 -0800680 output_object->is_delta_payload =
681 XmlGetProperty(pie_action_node, kTagIsDeltaPayload) == "true";
682
683 output_object->disable_payload_backoff =
684 XmlGetProperty(pie_action_node, kTagDisablePayloadBackoff) == "true";
685
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700686 return true;
687}
688
rspangler@google.com49fdf182009-10-10 00:57:34 +0000689// If the transfer was successful, this uses libxml2 to parse the response
690// and fill in the appropriate fields of the output object. Also, notifies
691// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700692void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
693 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000694 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800695 string current_response(response_buffer_.begin(), response_buffer_.end());
696 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700697
698 // Events are best effort transactions -- assume they always succeed.
699 if (IsEvent()) {
700 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800701 if (event_->result == OmahaEvent::kResultError && successful &&
702 utils::IsOfficialBuild()) {
703 LOG(INFO) << "Signalling Crash Reporter.";
704 utils::ScheduleCrashReporterUpload();
705 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700706 completer.set_code(kActionCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700707 return;
708 }
709
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700710 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700711 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700712 int code = GetHTTPResponseCode();
713 // Makes sure we send sane error values.
714 if (code < 0 || code >= 1000) {
715 code = 999;
716 }
717 completer.set_code(static_cast<ActionExitCode>(
718 kActionCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000719 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700720 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000721
722 // parse our response and fill the fields in the output object
723 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
724 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
725 if (!doc.get()) {
726 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700727 completer.set_code(response_buffer_.empty() ?
728 kActionCodeOmahaRequestEmptyResponseError :
729 kActionCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000730 return;
731 }
732
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700733 // If a ping was sent, update the last ping day preferences based on
734 // the server daystart response.
735 if (ShouldPing(ping_active_days_) ||
736 ShouldPing(ping_roll_call_days_) ||
737 ping_active_days_ == kPingTimeJump ||
738 ping_roll_call_days_ == kPingTimeJump) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800739 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700740 << "Failed to update the last ping day preferences!";
741 }
742
Thieu Le116fda32011-04-19 11:01:54 -0700743 if (!HasOutputPipe()) {
744 // Just set success to whether or not the http transfer succeeded,
745 // which must be true at this point in the code.
746 completer.set_code(kActionCodeSuccess);
747 return;
748 }
749
Darin Petkov6a5b3222010-07-13 14:55:28 -0700750 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700751 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000752 return;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000753
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700754 if (params_->update_disabled()) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700755 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700756 output_object.update_exists = false;
Jay Srinivasan0a708742012-03-20 11:26:12 -0700757 completer.set_code(kActionCodeOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700758 // Note: We could technically delete the UpdateFirstSeenAt state here.
759 // If we do, it'll mean a device has to restart the UpdateFirstSeenAt
760 // and thus help scattering take effect when the AU is turned on again.
761 // On the other hand, it also increases the chance of update starvation if
762 // an admin turns AU on/off more frequently. We choose to err on the side
763 // of preventing starvation at the cost of not applying scattering in
764 // those cases.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700765 return;
766 }
767
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700768 if (ShouldDeferDownload(&output_object)) {
769 output_object.update_exists = false;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700770 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
771 completer.set_code(kActionCodeOmahaUpdateDeferredPerPolicy);
772 return;
773 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800774
775 // Update the payload state with the current response. The payload state
776 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800777 // from what's stored already. We are updating the payload state as late
778 // as possible in this method so that if a new release gets pushed and then
779 // got pulled back due to some issues, we don't want to clear our internal
780 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800781 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800782 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800783
784 if (payload_state->ShouldBackoffDownload()) {
785 output_object.update_exists = false;
786 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
787 "attempts";
788 completer.set_code(kActionCodeOmahaUpdateDeferredForBackoff);
789 return;
790 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000791}
792
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700793bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700794 // We should defer the downloads only if we've first satisfied the
795 // wall-clock-based-waiting period and then the update-check-based waiting
796 // period, if required.
797
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700798 if (!params_->wall_clock_based_wait_enabled()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700799 // Wall-clock-based waiting period is not enabled, so no scattering needed.
800 return false;
801 }
802
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700803 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700804 case kWallClockWaitNotSatisfied:
805 // We haven't even satisfied the first condition, passing the
806 // wall-clock-based waiting period, so we should defer the downloads
807 // until that happens.
808 LOG(INFO) << "wall-clock-based-wait not satisfied.";
809 return true;
810
811 case kWallClockWaitDoneButUpdateCheckWaitRequired:
812 LOG(INFO) << "wall-clock-based-wait satisfied and "
813 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700814 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700815
816 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
817 // Wall-clock-based waiting period is satisfied, and it's determined
818 // that we do not need the update-check-based wait. so no need to
819 // defer downloads.
820 LOG(INFO) << "wall-clock-based-wait satisfied and "
821 << "update-check-based-wait is not required.";
822 return false;
823
824 default:
825 // Returning false for this default case so we err on the
826 // side of downloading updates than deferring in case of any bugs.
827 NOTREACHED();
828 return false;
829 }
830}
831
832OmahaRequestAction::WallClockWaitResult
833OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700834 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700835 Time update_first_seen_at;
836 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700837
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800838 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
839 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
840 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700841 // Note: This timestamp could be that of ANY update we saw in the past
842 // (not necessarily this particular update we're considering to apply)
843 // but never got to apply because of some reason (e.g. stop AU policy,
844 // updates being pulled out from Omaha, changes in target version prefix,
845 // new update being rolled out, etc.). But for the purposes of scattering
846 // it doesn't matter which update the timestamp corresponds to. i.e.
847 // the clock starts ticking the first time we see an update and we're
848 // ready to apply when the random wait period is satisfied relative to
849 // that first seen timestamp.
850 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
851 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
852 << utils::ToString(update_first_seen_at);
853 } else {
854 // This seems like an unexpected error where the persisted value exists
855 // but it's not readable for some reason. Just skip scattering in this
856 // case to be safe.
857 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
858 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
859 }
860 } else {
861 update_first_seen_at = Time::Now();
862 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800863 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
864 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700865 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
866 << utils::ToString(update_first_seen_at);
867 }
868 else {
869 // This seems like an unexpected error where the value cannot be
870 // persisted for some reason. Just skip scattering in this
871 // case to be safe.
872 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
873 << utils::ToString(update_first_seen_at)
874 << " cannot be persisted";
875 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
876 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700877 }
878
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700879 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700880 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700881 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700882
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700883 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700884 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700885 << ", Time Elapsed = "
886 << utils::FormatSecs(elapsed_time.InSeconds())
887 << ", MaxDaysToScatter = "
888 << max_scatter_period.InDays();
889
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700890 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700891 // The deadline is set for all rules which serve a delta update from a
892 // previous FSI, which means this update will be applied mostly in OOBE
893 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
894 // quickly.
895 LOG(INFO) << "Not scattering as deadline flag is set";
896 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
897 }
898
899 if (max_scatter_period.InDays() == 0) {
900 // This means the Omaha rule creator decides that this rule
901 // should not be scattered irrespective of the policy.
902 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
903 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
904 }
905
906 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700907 // This means we've waited more than the upperbound wait in the rule
908 // from the time we first saw a valid update available to us.
909 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700910 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
911 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
912 }
913
914 // This means we are required to participate in scattering.
915 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700916 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700917 if (remaining_wait_time.InSeconds() <= 0) {
918 // Yes, it's our turn now.
919 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
920
921 // But we can't download until the update-check-count-based wait is also
922 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700923 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700924 kWallClockWaitDoneButUpdateCheckWaitRequired :
925 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
926 }
927
928 // Not our turn yet, so we have to wait until our turn to
929 // help scatter the downloads across all clients of the enterprise.
930 LOG(INFO) << "Update deferred for another "
931 << utils::FormatSecs(remaining_wait_time.InSeconds())
932 << " per policy.";
933 return kWallClockWaitNotSatisfied;
934}
935
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700936bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700937 int64 update_check_count_value;
938
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800939 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
940 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
941 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700942 // We are unable to read the update check count from file for some reason.
943 // So let's proceed anyway so as to not stall the update.
944 LOG(ERROR) << "Unable to read update check count. "
945 << "Skipping update-check-count-based-wait.";
946 return true;
947 }
948 } else {
949 // This file does not exist. This means we haven't started our update
950 // check count down yet, so this is the right time to start the count down.
951 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700952 params_->min_update_checks_needed(),
953 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700954
955 LOG(INFO) << "Randomly picked update check count value = "
956 << update_check_count_value;
957
958 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800959 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
960 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700961 // We weren't able to write the update check count file for some reason.
962 // So let's proceed anyway so as to not stall the update.
963 LOG(ERROR) << "Unable to write update check count. "
964 << "Skipping update-check-count-based-wait.";
965 return true;
966 }
967 }
968
969 if (update_check_count_value == 0) {
970 LOG(INFO) << "Successfully passed the update-check-based-wait.";
971 return true;
972 }
973
974 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700975 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700976 // We err on the side of skipping scattering logic instead of stalling
977 // a machine from receiving any updates in case of any unexpected state.
978 LOG(ERROR) << "Invalid value for update check count detected. "
979 << "Skipping update-check-count-based-wait.";
980 return true;
981 }
982
983 // Legal value, we need to wait for more update checks to happen
984 // until this becomes 0.
985 LOG(INFO) << "Deferring Omaha updates for another "
986 << update_check_count_value
987 << " update checks per policy";
988 return false;
989}
990
991} // namespace chromeos_update_engine
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700992
993