blob: d2399c1c191ca53ff6d80b29b401a1992609f92a [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"
Darin Petkov1cbd78f2010-07-29 12:38:34 -070023#include "update_engine/prefs_interface.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000024#include "update_engine/utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000025
Darin Petkov1cbd78f2010-07-29 12:38:34 -070026using base::Time;
27using base::TimeDelta;
rspangler@google.com49fdf182009-10-10 00:57:34 +000028using std::string;
29
30namespace chromeos_update_engine {
31
rspangler@google.com49fdf182009-10-10 00:57:34 +000032namespace {
33
34const string kGupdateVersion("ChromeOSUpdateEngine-0.1.0.0");
35
36// This is handy for passing strings into libxml2
37#define ConstXMLStr(x) (reinterpret_cast<const xmlChar*>(x))
38
39// These are for scoped_ptr_malloc, which is like scoped_ptr, but allows
40// a custom free() function to be specified.
41class ScopedPtrXmlDocFree {
42 public:
43 inline void operator()(void* x) const {
44 xmlFreeDoc(reinterpret_cast<xmlDoc*>(x));
45 }
46};
47class ScopedPtrXmlFree {
48 public:
49 inline void operator()(void* x) const {
50 xmlFree(x);
51 }
52};
53class ScopedPtrXmlXPathObjectFree {
54 public:
55 inline void operator()(void* x) const {
56 xmlXPathFreeObject(reinterpret_cast<xmlXPathObject*>(x));
57 }
58};
59class ScopedPtrXmlXPathContextFree {
60 public:
61 inline void operator()(void* x) const {
62 xmlXPathFreeContext(reinterpret_cast<xmlXPathContext*>(x));
63 }
64};
65
Darin Petkov1cbd78f2010-07-29 12:38:34 -070066// Returns true if |ping_days| has a value that needs to be sent,
67// false otherwise.
68bool ShouldPing(int ping_days) {
69 return ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged;
70}
71
72// Returns an XML ping element attribute assignment with attribute
73// |name| and value |ping_days| if |ping_days| has a value that needs
74// to be sent, or an empty string otherwise.
75string GetPingAttribute(const string& name, int ping_days) {
76 if (ShouldPing(ping_days)) {
77 return StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
78 }
79 return "";
80}
81
82// Returns an XML ping element if any of the elapsed days need to be
83// sent, or an empty string otherwise.
84string GetPingBody(int ping_active_days, int ping_roll_call_days) {
85 string ping_active = GetPingAttribute("a", ping_active_days);
86 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
87 if (!ping_active.empty() || !ping_roll_call.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -070088 return StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Darin Petkov1cbd78f2010-07-29 12:38:34 -070089 ping_active.c_str(),
90 ping_roll_call.c_str());
91 }
92 return "";
93}
94
Darin Petkov0dc8e9a2010-07-14 14:51:57 -070095string FormatRequest(const OmahaEvent* event,
Darin Petkov1cbd78f2010-07-29 12:38:34 -070096 const OmahaRequestParams& params,
Thieu Le116fda32011-04-19 11:01:54 -070097 bool ping_only,
Darin Petkov1cbd78f2010-07-29 12:38:34 -070098 int ping_active_days,
Darin Petkov95508da2011-01-05 12:42:29 -080099 int ping_roll_call_days,
100 PrefsInterface* prefs) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700101 string body;
102 if (event == NULL) {
Thieu Le116fda32011-04-19 11:01:54 -0700103 body = GetPingBody(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700104 if (!ping_only) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700105 // not passing update_disabled to Omaha because we want to
106 // get the update and report with UpdateDeferred result so that
107 // borgmon charts show up updates that are deferred. This is also
108 // the expected behavior when we move to Omaha v3.0 protocol, so it'll
109 // be consistent.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700110 body += StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700111 " <updatecheck"
Jay Srinivasan0a708742012-03-20 11:26:12 -0700112 " targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700113 "></updatecheck>\n",
Jay Srinivasan0a708742012-03-20 11:26:12 -0700114 XmlEncode(params.target_version_prefix).c_str());
115
Darin Petkov265f2902011-05-09 15:17:40 -0700116 // If this is the first update check after a reboot following a previous
117 // update, generate an event containing the previous version number. If
118 // the previous version preference file doesn't exist the event is still
119 // generated with a previous version of 0.0.0.0 -- this is relevant for
120 // older clients or new installs. The previous version event is not sent
121 // for ping-only requests because they come before the client has
122 // rebooted.
123 string prev_version;
124 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
125 prev_version = "0.0.0.0";
126 }
127 if (!prev_version.empty()) {
128 body += StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700129 " <event eventtype=\"%d\" eventresult=\"%d\" "
130 "previousversion=\"%s\"></event>\n",
Darin Petkov265f2902011-05-09 15:17:40 -0700131 OmahaEvent::kTypeUpdateComplete,
132 OmahaEvent::kResultSuccessReboot,
133 XmlEncode(prev_version).c_str());
134 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
135 << "Unable to reset the previous version.";
136 }
Darin Petkov95508da2011-01-05 12:42:29 -0800137 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700138 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800139 // The error code is an optional attribute so append it only if the result
140 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700141 string error_code;
142 if (event->result != OmahaEvent::kResultSuccess) {
Darin Petkov18c7bce2011-06-16 14:07:00 -0700143 error_code = StringPrintf(" errorcode=\"%d\"", event->error_code);
Darin Petkove17f86b2010-07-20 09:12:01 -0700144 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700145 body = StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700146 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700147 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700148 }
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700149 return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700150 "<request protocol=\"3.0\" "
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700151 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
152 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" "
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700153 "ismachine=\"1\">\n"
154 " <os version=\"" + XmlEncode(params.os_version) + "\" platform=\"" +
rspangler@google.com49fdf182009-10-10 00:57:34 +0000155 XmlEncode(params.os_platform) + "\" sp=\"" +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700156 XmlEncode(params.os_sp) + "\"></os>\n"
157 " <app appid=\"" + XmlEncode(params.app_id) + "\" version=\"" +
rspangler@google.com49fdf182009-10-10 00:57:34 +0000158 XmlEncode(params.app_version) + "\" "
159 "lang=\"" + XmlEncode(params.app_lang) + "\" track=\"" +
Andrew de los Reyes37c20322010-06-30 13:27:19 -0700160 XmlEncode(params.app_track) + "\" board=\"" +
Darin Petkovfbb40092010-07-29 17:05:50 -0700161 XmlEncode(params.os_board) + "\" hardware_class=\"" +
162 XmlEncode(params.hardware_class) + "\" delta_okay=\"" +
Andrew de los Reyes3f0303a2010-07-15 22:35:35 -0700163 (params.delta_okay ? "true" : "false") + "\">\n" + body +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700164 " </app>\n"
165 "</request>\n";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000166}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700167
rspangler@google.com49fdf182009-10-10 00:57:34 +0000168} // namespace {}
169
170// Encodes XML entities in a given string with libxml2. input must be
171// UTF-8 formatted. Output will be UTF-8 formatted.
172string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700173 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
174 // // cpu, considering creating one and caching it.
175 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
176 // xmlNewDoc(ConstXMLStr("1.0")));
177 // if (!xml_doc.get()) {
178 // LOG(ERROR) << "Unable to create xmlDoc";
179 // return "";
180 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000181 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
182 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
183 return string(reinterpret_cast<const char *>(str.get()));
184}
185
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700186OmahaRequestAction::OmahaRequestAction(PrefsInterface* prefs,
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700187 OmahaRequestParams* params,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700188 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700189 HttpFetcher* http_fetcher,
190 bool ping_only)
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700191 : prefs_(prefs),
192 params_(params),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700193 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700194 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700195 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700196 ping_active_days_(0),
Andrew de los Reyes771e1bd2011-08-30 14:47:23 -0700197 ping_roll_call_days_(0) {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000198
Darin Petkov6a5b3222010-07-13 14:55:28 -0700199OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000200
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700201// Calculates the value to use for the ping days parameter.
202int OmahaRequestAction::CalculatePingDays(const string& key) {
203 int days = kNeverPinged;
204 int64_t last_ping = 0;
205 if (prefs_->GetInt64(key, &last_ping) && last_ping >= 0) {
206 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
207 if (days < 0) {
208 // If |days| is negative, then the system clock must have jumped
209 // back in time since the ping was sent. Mark the value so that
210 // it doesn't get sent to the server but we still update the
211 // last ping daystart preference. This way the next ping time
212 // will be correct, hopefully.
213 days = kPingTimeJump;
214 LOG(WARNING) <<
215 "System clock jumped back in time. Resetting ping daystarts.";
216 }
217 }
218 return days;
219}
220
221void OmahaRequestAction::InitPingDays() {
222 // We send pings only along with update checks, not with events.
223 if (IsEvent()) {
224 return;
225 }
226 // TODO(petkov): Figure a way to distinguish active use pings
227 // vs. roll call pings. Currently, the two pings are identical. A
228 // fix needs to change this code as well as UpdateLastPingDays.
229 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
230 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
231}
232
Darin Petkov6a5b3222010-07-13 14:55:28 -0700233void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000234 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700235 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700236 if (ping_only_ &&
237 !ShouldPing(ping_active_days_) &&
238 !ShouldPing(ping_roll_call_days_)) {
239 processor_->ActionComplete(this, kActionCodeSuccess);
240 return;
241 }
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700242 string request_post(FormatRequest(event_.get(),
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700243 *params_,
Thieu Le116fda32011-04-19 11:01:54 -0700244 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700245 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800246 ping_roll_call_days_,
247 prefs_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700248
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800249 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
250 kHttpContentTypeTextXml);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700251 LOG(INFO) << "Posting an Omaha request to " << params_->update_url;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700252 LOG(INFO) << "Request: " << request_post;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700253 http_fetcher_->BeginTransfer(params_->update_url);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000254}
255
Darin Petkov6a5b3222010-07-13 14:55:28 -0700256void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000257 http_fetcher_->TerminateTransfer();
258}
259
260// We just store the response in the buffer. Once we've received all bytes,
261// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700262void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
263 const char* bytes,
264 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000265 response_buffer_.reserve(response_buffer_.size() + length);
266 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
267}
268
269namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000270// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
271// on the returned object.
272// This code is roughly based on the libxml tutorial at:
273// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700274xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000275 xmlXPathObject* result = NULL;
276
277 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
278 xmlXPathNewContext(doc));
279 if (!context.get()) {
280 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
281 return NULL;
282 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000283
284 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000285 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700286 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000287 return NULL;
288 }
289 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700290 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000291 xmlXPathFreeObject(result);
292 return NULL;
293 }
294 return result;
295}
296
297// Returns the string value of a named attribute on a node, or empty string
298// if no such node exists. If the attribute exists and has a value of
299// empty string, there's no way to distinguish that from the attribute
300// not existing.
301string XmlGetProperty(xmlNode* node, const char* name) {
302 if (!xmlHasProp(node, ConstXMLStr(name)))
303 return "";
304 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
305 xmlGetProp(node, ConstXMLStr(name)));
306 string ret(reinterpret_cast<const char *>(str.get()));
307 return ret;
308}
309
310// Parses a 64 bit base-10 int from a string and returns it. Returns 0
311// on error. If the string contains "0", that's indistinguishable from
312// error.
313off_t ParseInt(const string& str) {
314 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700315 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000316 if (rc < 1) {
317 // failure
318 return 0;
319 }
320 return ret;
321}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700322
323// Update the last ping day preferences based on the server daystart
324// response. Returns true on success, false otherwise.
325bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700326 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700327
328 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700329 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700330 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
331 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
332 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
333 xmlNode* daystart_node = nodeset->nodeTab[0];
334 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
335 ConstXMLStr("elapsed_seconds")));
336
337 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700338 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
339 "elapsed_seconds"),
340 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700341 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
342
343 // Remember the local time that matches the server's last midnight
344 // time.
345 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
346 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
347 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
348 return true;
349}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000350} // namespace {}
351
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700352bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
353 OmahaResponse* output_object,
354 ScopedActionCompleter* completer) {
355 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
356
357 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
358 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
359 if (!xpath_nodeset.get()) {
360 completer->set_code(kActionCodeOmahaResponseInvalid);
361 return false;
362 }
363
364 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
365 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
366 CHECK_GE(nodeset->nodeNr, 1);
367 xmlNode* update_check_node = nodeset->nodeTab[0];
368
369 // TODO(jaysri): The PollInterval is not supported by Omaha server currently.
370 // But still keeping this existing code in case we ever decide to slow down
371 // the request rate from the server-side. Note that the PollInterval is not
372 // persisted, so it has to be sent by the server on every response to
373 // guarantee that the UpdateCheckScheduler uses this value (otherwise, if the
374 // device got rebooted after the last server-indicated value, it'll revert to
375 // the default value). Also kDefaultMaxUpdateChecks value for the scattering
376 // logic is based on the assumption that we perform an update check every
377 // hour so that the max value of 8 will roughly be equivalent to one work
378 // day. If we decide to use PollInterval permanently, we should update
379 // the max_update_checks_allowed to take PollInterval into account. Note:
380 // The parsing for PollInterval happens even before parsing of the status
381 // because we may want to specify the PollInterval even when there's no
382 // update.
383 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
384 &output_object->poll_interval);
385
386 if (!ParseStatus(update_check_node, output_object, completer))
387 return false;
388
389 if (!ParseUrls(doc, output_object, completer))
390 return false;
391
392 if (!ParsePackage(doc, output_object, completer))
393 return false;
394
395 if (!ParseParams(doc, output_object, completer))
396 return false;
397
398 return true;
399}
400
401bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
402 OmahaResponse* output_object,
403 ScopedActionCompleter* completer) {
404 // Get status.
405 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
406 LOG(ERROR) << "Omaha Response missing status";
407 completer->set_code(kActionCodeOmahaResponseInvalid);
408 return false;
409 }
410
411 const string status(XmlGetProperty(update_check_node, "status"));
412 if (status == "noupdate") {
413 LOG(INFO) << "No update.";
414 output_object->update_exists = false;
415 SetOutputObject(*output_object);
416 completer->set_code(kActionCodeSuccess);
417 return false;
418 }
419
420 if (status != "ok") {
421 LOG(ERROR) << "Unknown Omaha response status: " << status;
422 completer->set_code(kActionCodeOmahaResponseInvalid);
423 return false;
424 }
425
426 return true;
427}
428
429bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
430 OmahaResponse* output_object,
431 ScopedActionCompleter* completer) {
432 // Get the update URL.
433 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
434
435 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
436 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
437 if (!xpath_nodeset.get()) {
438 completer->set_code(kActionCodeOmahaResponseInvalid);
439 return false;
440 }
441
442 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
443 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
444 CHECK_GE(nodeset->nodeNr, 1);
445
446 // TODO(jaysri): For now, just process only the first URL. In subsequent
447 // check-ins, we'll add the support to honor multiples URLs.
448 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " url(s)";
449 xmlNode* url_node = nodeset->nodeTab[0];
450
451 const string codebase(XmlGetProperty(url_node, "codebase"));
452 if (codebase.empty()) {
453 LOG(ERROR) << "Omaha Response URL has empty codebase";
454 completer->set_code(kActionCodeOmahaResponseInvalid);
455 return false;
456 }
457
458 output_object->codebase = codebase;
459 return true;
460}
461
462bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
463 OmahaResponse* output_object,
464 ScopedActionCompleter* completer) {
465 // Get the package node.
466 static const char* kPackageNodeXPath(
467 "/response/app/updatecheck/manifest/packages/package");
468
469 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
470 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
471 if (!xpath_nodeset.get()) {
472 completer->set_code(kActionCodeOmahaResponseInvalid);
473 return false;
474 }
475
476 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
477 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
478 CHECK_GE(nodeset->nodeNr, 1);
479
480 // We only care about the first package.
481 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
482 xmlNode* package_node = nodeset->nodeTab[0];
483
484 // Get package properties one by one.
485
486 // Parse the payload name to be appended to the Url codebase.
487 const string package_name(XmlGetProperty(package_node, "name"));
488 LOG(INFO) << "Omaha Response package name = " << package_name;
489 if (package_name.empty()) {
490 LOG(ERROR) << "Omaha Response has empty package name";
491 completer->set_code(kActionCodeOmahaResponseInvalid);
492 return false;
493 }
494 output_object->codebase += package_name;
495
496 // Parse the payload size.
497 off_t size = ParseInt(XmlGetProperty(package_node, "size"));
498 if (size <= 0) {
499 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
500 completer->set_code(kActionCodeOmahaResponseInvalid);
501 return false;
502 }
503 output_object->size = size;
504
505 LOG(INFO) << "Download URL = " << output_object->codebase
506 << ", Paylod size = " << output_object->size;
507
508 return true;
509}
510
511bool OmahaRequestAction::ParseParams(xmlDoc* doc,
512 OmahaResponse* output_object,
513 ScopedActionCompleter* completer) {
514 // Get the action node where parameters are present.
515 static const char* kActionNodeXPath(
516 "/response/app/updatecheck/manifest/actions/action");
517
518 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
519 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
520 if (!xpath_nodeset.get()) {
521 completer->set_code(kActionCodeOmahaResponseInvalid);
522 return false;
523 }
524
525 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
526 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
527
528 // We only care about the action that has event "postinall", because this is
529 // where Omaha puts all the generic name/value pairs in the rule.
530 LOG(INFO) << "Found " << nodeset->nodeNr
531 << " action(s). Processing the postinstall action.";
532
533 // pie_action_node holds the action node corresponding to the
534 // postinstall event action, if present.
535 xmlNode* pie_action_node = NULL;
536 for (int i = 0; i < nodeset->nodeNr; i++) {
537 xmlNode* action_node = nodeset->nodeTab[i];
538 if (XmlGetProperty(action_node, "event") == "postinstall") {
539 pie_action_node = action_node;
540 break;
541 }
542 }
543
544 if (!pie_action_node) {
545 LOG(ERROR) << "Omaha Response has no postinstall event action";
546 completer->set_code(kActionCodeOmahaResponseInvalid);
547 return false;
548 }
549
550 output_object->hash = XmlGetProperty(pie_action_node, "sha256");
551 if (output_object->hash.empty()) {
552 LOG(ERROR) << "Omaha Response has empty sha256 value";
553 completer->set_code(kActionCodeOmahaResponseInvalid);
554 return false;
555 }
556
557 // Get the optional properties one by one.
558 output_object->display_version =
559 XmlGetProperty(pie_action_node, "DisplayVersion");
560 output_object->more_info_url = XmlGetProperty(pie_action_node, "MoreInfo");
561 output_object->metadata_size =
562 ParseInt(XmlGetProperty(pie_action_node, "MetadataSize"));
563 output_object->metadata_signature =
564 XmlGetProperty(pie_action_node, "MetadataSignatureRsa");
565 output_object->needs_admin =
566 XmlGetProperty(pie_action_node, "needsadmin") == "true";
567 output_object->prompt = XmlGetProperty(pie_action_node, "Prompt") == "true";
568 output_object->deadline = XmlGetProperty(pie_action_node, "deadline");
569 output_object->max_days_to_scatter =
570 ParseInt(XmlGetProperty(pie_action_node, "MaxDaysToScatter"));
571
572 output_object->update_exists = true;
573 SetOutputObject(*output_object);
574 completer->set_code(kActionCodeSuccess);
575
576 return true;
577}
578
rspangler@google.com49fdf182009-10-10 00:57:34 +0000579// If the transfer was successful, this uses libxml2 to parse the response
580// and fill in the appropriate fields of the output object. Also, notifies
581// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700582void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
583 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000584 ScopedActionCompleter completer(processor_, this);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700585 LOG(INFO) << "Omaha request response: " << string(response_buffer_.begin(),
586 response_buffer_.end());
587
588 // Events are best effort transactions -- assume they always succeed.
589 if (IsEvent()) {
590 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800591 if (event_->result == OmahaEvent::kResultError && successful &&
592 utils::IsOfficialBuild()) {
593 LOG(INFO) << "Signalling Crash Reporter.";
594 utils::ScheduleCrashReporterUpload();
595 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700596 completer.set_code(kActionCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700597 return;
598 }
599
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700600 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700601 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700602 int code = GetHTTPResponseCode();
603 // Makes sure we send sane error values.
604 if (code < 0 || code >= 1000) {
605 code = 999;
606 }
607 completer.set_code(static_cast<ActionExitCode>(
608 kActionCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000609 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700610 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000611
612 // parse our response and fill the fields in the output object
613 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
614 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
615 if (!doc.get()) {
616 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700617 completer.set_code(response_buffer_.empty() ?
618 kActionCodeOmahaRequestEmptyResponseError :
619 kActionCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000620 return;
621 }
622
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700623 // If a ping was sent, update the last ping day preferences based on
624 // the server daystart response.
625 if (ShouldPing(ping_active_days_) ||
626 ShouldPing(ping_roll_call_days_) ||
627 ping_active_days_ == kPingTimeJump ||
628 ping_roll_call_days_ == kPingTimeJump) {
629 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), prefs_))
630 << "Failed to update the last ping day preferences!";
631 }
632
Thieu Le116fda32011-04-19 11:01:54 -0700633 if (!HasOutputPipe()) {
634 // Just set success to whether or not the http transfer succeeded,
635 // which must be true at this point in the code.
636 completer.set_code(kActionCodeSuccess);
637 return;
638 }
639
Darin Petkov6a5b3222010-07-13 14:55:28 -0700640 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700641 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000642 return;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000643
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700644 if (params_->update_disabled) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700645 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700646 output_object.update_exists = false;
Jay Srinivasan0a708742012-03-20 11:26:12 -0700647 completer.set_code(kActionCodeOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700648 // Note: We could technically delete the UpdateFirstSeenAt state here.
649 // If we do, it'll mean a device has to restart the UpdateFirstSeenAt
650 // and thus help scattering take effect when the AU is turned on again.
651 // On the other hand, it also increases the chance of update starvation if
652 // an admin turns AU on/off more frequently. We choose to err on the side
653 // of preventing starvation at the cost of not applying scattering in
654 // those cases.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700655 return;
656 }
657
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700658 if (ShouldDeferDownload(&output_object)) {
659 output_object.update_exists = false;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700660 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
661 completer.set_code(kActionCodeOmahaUpdateDeferredPerPolicy);
662 return;
663 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000664}
665
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700666bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700667 // We should defer the downloads only if we've first satisfied the
668 // wall-clock-based-waiting period and then the update-check-based waiting
669 // period, if required.
670
671 if (!params_->wall_clock_based_wait_enabled) {
672 // Wall-clock-based waiting period is not enabled, so no scattering needed.
673 return false;
674 }
675
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700676 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700677 case kWallClockWaitNotSatisfied:
678 // We haven't even satisfied the first condition, passing the
679 // wall-clock-based waiting period, so we should defer the downloads
680 // until that happens.
681 LOG(INFO) << "wall-clock-based-wait not satisfied.";
682 return true;
683
684 case kWallClockWaitDoneButUpdateCheckWaitRequired:
685 LOG(INFO) << "wall-clock-based-wait satisfied and "
686 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700687 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700688
689 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
690 // Wall-clock-based waiting period is satisfied, and it's determined
691 // that we do not need the update-check-based wait. so no need to
692 // defer downloads.
693 LOG(INFO) << "wall-clock-based-wait satisfied and "
694 << "update-check-based-wait is not required.";
695 return false;
696
697 default:
698 // Returning false for this default case so we err on the
699 // side of downloading updates than deferring in case of any bugs.
700 NOTREACHED();
701 return false;
702 }
703}
704
705OmahaRequestAction::WallClockWaitResult
706OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700707 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700708 Time update_first_seen_at;
709 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700710
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700711 if (prefs_->Exists(kPrefsUpdateFirstSeenAt)) {
712 if (prefs_->GetInt64(kPrefsUpdateFirstSeenAt, &update_first_seen_at_int)) {
713 // Note: This timestamp could be that of ANY update we saw in the past
714 // (not necessarily this particular update we're considering to apply)
715 // but never got to apply because of some reason (e.g. stop AU policy,
716 // updates being pulled out from Omaha, changes in target version prefix,
717 // new update being rolled out, etc.). But for the purposes of scattering
718 // it doesn't matter which update the timestamp corresponds to. i.e.
719 // the clock starts ticking the first time we see an update and we're
720 // ready to apply when the random wait period is satisfied relative to
721 // that first seen timestamp.
722 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
723 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
724 << utils::ToString(update_first_seen_at);
725 } else {
726 // This seems like an unexpected error where the persisted value exists
727 // but it's not readable for some reason. Just skip scattering in this
728 // case to be safe.
729 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
730 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
731 }
732 } else {
733 update_first_seen_at = Time::Now();
734 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
735 if (prefs_->SetInt64(kPrefsUpdateFirstSeenAt, update_first_seen_at_int)) {
736 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
737 << utils::ToString(update_first_seen_at);
738 }
739 else {
740 // This seems like an unexpected error where the value cannot be
741 // persisted for some reason. Just skip scattering in this
742 // case to be safe.
743 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
744 << utils::ToString(update_first_seen_at)
745 << " cannot be persisted";
746 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
747 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700748 }
749
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700750 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700751 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700752 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700753
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700754 LOG(INFO) << "Waiting Period = "
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700755 << utils::FormatSecs(params_->waiting_period.InSeconds())
756 << ", Time Elapsed = "
757 << utils::FormatSecs(elapsed_time.InSeconds())
758 << ", MaxDaysToScatter = "
759 << max_scatter_period.InDays();
760
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700761 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700762 // The deadline is set for all rules which serve a delta update from a
763 // previous FSI, which means this update will be applied mostly in OOBE
764 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
765 // quickly.
766 LOG(INFO) << "Not scattering as deadline flag is set";
767 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
768 }
769
770 if (max_scatter_period.InDays() == 0) {
771 // This means the Omaha rule creator decides that this rule
772 // should not be scattered irrespective of the policy.
773 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
774 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
775 }
776
777 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700778 // This means we've waited more than the upperbound wait in the rule
779 // from the time we first saw a valid update available to us.
780 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700781 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
782 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
783 }
784
785 // This means we are required to participate in scattering.
786 // See if our turn has arrived now.
787 TimeDelta remaining_wait_time = params_->waiting_period - elapsed_time;
788 if (remaining_wait_time.InSeconds() <= 0) {
789 // Yes, it's our turn now.
790 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
791
792 // But we can't download until the update-check-count-based wait is also
793 // satisfied, so mark it as required now if update checks are enabled.
794 return params_->update_check_count_wait_enabled ?
795 kWallClockWaitDoneButUpdateCheckWaitRequired :
796 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
797 }
798
799 // Not our turn yet, so we have to wait until our turn to
800 // help scatter the downloads across all clients of the enterprise.
801 LOG(INFO) << "Update deferred for another "
802 << utils::FormatSecs(remaining_wait_time.InSeconds())
803 << " per policy.";
804 return kWallClockWaitNotSatisfied;
805}
806
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700807bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700808 int64 update_check_count_value;
809
810 if (prefs_->Exists(kPrefsUpdateCheckCount)) {
811 if (!prefs_->GetInt64(kPrefsUpdateCheckCount, &update_check_count_value)) {
812 // We are unable to read the update check count from file for some reason.
813 // So let's proceed anyway so as to not stall the update.
814 LOG(ERROR) << "Unable to read update check count. "
815 << "Skipping update-check-count-based-wait.";
816 return true;
817 }
818 } else {
819 // This file does not exist. This means we haven't started our update
820 // check count down yet, so this is the right time to start the count down.
821 update_check_count_value = base::RandInt(
822 params_->min_update_checks_needed,
823 params_->max_update_checks_allowed);
824
825 LOG(INFO) << "Randomly picked update check count value = "
826 << update_check_count_value;
827
828 // Write out the initial value of update_check_count_value.
829 if (!prefs_->SetInt64(kPrefsUpdateCheckCount, update_check_count_value)) {
830 // We weren't able to write the update check count file for some reason.
831 // So let's proceed anyway so as to not stall the update.
832 LOG(ERROR) << "Unable to write update check count. "
833 << "Skipping update-check-count-based-wait.";
834 return true;
835 }
836 }
837
838 if (update_check_count_value == 0) {
839 LOG(INFO) << "Successfully passed the update-check-based-wait.";
840 return true;
841 }
842
843 if (update_check_count_value < 0 ||
844 update_check_count_value > params_->max_update_checks_allowed) {
845 // We err on the side of skipping scattering logic instead of stalling
846 // a machine from receiving any updates in case of any unexpected state.
847 LOG(ERROR) << "Invalid value for update check count detected. "
848 << "Skipping update-check-count-based-wait.";
849 return true;
850 }
851
852 // Legal value, we need to wait for more update checks to happen
853 // until this becomes 0.
854 LOG(INFO) << "Deferring Omaha updates for another "
855 << update_check_count_value
856 << " update checks per policy";
857 return false;
858}
859
860} // namespace chromeos_update_engine
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700861
862