blob: ae8e5e7bf096863707073398dfcd355bf1649809 [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()) {
Thieu Le116fda32011-04-19 11:01:54 -070088 return StringPrintf(" <o:ping active=\"1\"%s%s></o: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(
111 " <o:updatecheck"
Jay Srinivasan0a708742012-03-20 11:26:12 -0700112 " targetversionprefix=\"%s\""
113 "></o: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(
129 " <o:event eventtype=\"%d\" eventresult=\"%d\" "
130 "previousversion=\"%s\"></o:event>\n",
131 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(
Darin Petkove17f86b2010-07-20 09:12:01 -0700146 " <o:event eventtype=\"%d\" eventresult=\"%d\"%s></o:event>\n",
147 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"
150 "<o:gupdate xmlns:o=\"http://www.google.com/update2/request\" "
151 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
152 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" "
153 "protocol=\"2.0\" ismachine=\"1\">\n"
rspangler@google.com49fdf182009-10-10 00:57:34 +0000154 " <o:os version=\"" + XmlEncode(params.os_version) + "\" platform=\"" +
155 XmlEncode(params.os_platform) + "\" sp=\"" +
156 XmlEncode(params.os_sp) + "\"></o:os>\n"
157 " <o:app appid=\"" + XmlEncode(params.app_id) + "\" version=\"" +
158 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 +
rspangler@google.com49fdf182009-10-10 00:57:34 +0000164 " </o:app>\n"
165 "</o:gupdate>\n";
166}
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
274xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath,
275 const xmlChar* ns, const xmlChar* ns_url) {
276 xmlXPathObject* result = NULL;
277
278 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
279 xmlXPathNewContext(doc));
280 if (!context.get()) {
281 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
282 return NULL;
283 }
284 if (xmlXPathRegisterNs(context.get(), ns, ns_url) < 0) {
285 LOG(ERROR) << "xmlXPathRegisterNs() returned error";
286 return NULL;
287 }
288
289 result = xmlXPathEvalExpression(xpath, context.get());
290
291 if (result == NULL) {
292 LOG(ERROR) << "xmlXPathEvalExpression returned error";
293 return NULL;
294 }
295 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
296 LOG(INFO) << "xpath not found in doc";
297 xmlXPathFreeObject(result);
298 return NULL;
299 }
300 return result;
301}
302
303// Returns the string value of a named attribute on a node, or empty string
304// if no such node exists. If the attribute exists and has a value of
305// empty string, there's no way to distinguish that from the attribute
306// not existing.
307string XmlGetProperty(xmlNode* node, const char* name) {
308 if (!xmlHasProp(node, ConstXMLStr(name)))
309 return "";
310 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
311 xmlGetProp(node, ConstXMLStr(name)));
312 string ret(reinterpret_cast<const char *>(str.get()));
313 return ret;
314}
315
316// Parses a 64 bit base-10 int from a string and returns it. Returns 0
317// on error. If the string contains "0", that's indistinguishable from
318// error.
319off_t ParseInt(const string& str) {
320 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700321 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000322 if (rc < 1) {
323 // failure
324 return 0;
325 }
326 return ret;
327}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700328
329// Update the last ping day preferences based on the server daystart
330// response. Returns true on success, false otherwise.
331bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
332 static const char kNamespace[] = "x";
333 static const char kDaystartNodeXpath[] = "/x:gupdate/x:daystart";
334 static const char kNsUrl[] = "http://www.google.com/update2/response";
335
336 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
337 xpath_nodeset(GetNodeSet(doc,
338 ConstXMLStr(kDaystartNodeXpath),
339 ConstXMLStr(kNamespace),
340 ConstXMLStr(kNsUrl)));
341 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
342 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
343 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
344 xmlNode* daystart_node = nodeset->nodeTab[0];
345 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
346 ConstXMLStr("elapsed_seconds")));
347
348 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700349 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
350 "elapsed_seconds"),
351 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700352 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
353
354 // Remember the local time that matches the server's last midnight
355 // time.
356 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
357 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
358 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
359 return true;
360}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000361} // namespace {}
362
363// If the transfer was successful, this uses libxml2 to parse the response
364// and fill in the appropriate fields of the output object. Also, notifies
365// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700366void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
367 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000368 ScopedActionCompleter completer(processor_, this);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700369 LOG(INFO) << "Omaha request response: " << string(response_buffer_.begin(),
370 response_buffer_.end());
371
372 // Events are best effort transactions -- assume they always succeed.
373 if (IsEvent()) {
374 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800375 if (event_->result == OmahaEvent::kResultError && successful &&
376 utils::IsOfficialBuild()) {
377 LOG(INFO) << "Signalling Crash Reporter.";
378 utils::ScheduleCrashReporterUpload();
379 }
Darin Petkovc1a8b422010-07-19 11:34:49 -0700380 completer.set_code(kActionCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700381 return;
382 }
383
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700384 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700385 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700386 int code = GetHTTPResponseCode();
387 // Makes sure we send sane error values.
388 if (code < 0 || code >= 1000) {
389 code = 999;
390 }
391 completer.set_code(static_cast<ActionExitCode>(
392 kActionCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000393 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700394 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000395
396 // parse our response and fill the fields in the output object
397 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
398 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
399 if (!doc.get()) {
400 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700401 completer.set_code(response_buffer_.empty() ?
402 kActionCodeOmahaRequestEmptyResponseError :
403 kActionCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000404 return;
405 }
406
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700407 // If a ping was sent, update the last ping day preferences based on
408 // the server daystart response.
409 if (ShouldPing(ping_active_days_) ||
410 ShouldPing(ping_roll_call_days_) ||
411 ping_active_days_ == kPingTimeJump ||
412 ping_roll_call_days_ == kPingTimeJump) {
413 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), prefs_))
414 << "Failed to update the last ping day preferences!";
415 }
416
Thieu Le116fda32011-04-19 11:01:54 -0700417 if (!HasOutputPipe()) {
418 // Just set success to whether or not the http transfer succeeded,
419 // which must be true at this point in the code.
420 completer.set_code(kActionCodeSuccess);
421 return;
422 }
423
rspangler@google.com49fdf182009-10-10 00:57:34 +0000424 static const char* kNamespace("x");
425 static const char* kUpdatecheckNodeXpath("/x:gupdate/x:app/x:updatecheck");
426 static const char* kNsUrl("http://www.google.com/update2/response");
427
428 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
429 xpath_nodeset(GetNodeSet(doc.get(),
430 ConstXMLStr(kUpdatecheckNodeXpath),
431 ConstXMLStr(kNamespace),
432 ConstXMLStr(kNsUrl)));
433 if (!xpath_nodeset.get()) {
Darin Petkovedc522e2010-11-05 09:35:17 -0700434 completer.set_code(kActionCodeOmahaRequestNoUpdateCheckNode);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000435 return;
436 }
437 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
438 CHECK(nodeset) << "XPath missing NodeSet";
439 CHECK_GE(nodeset->nodeNr, 1);
440
441 xmlNode* updatecheck_node = nodeset->nodeTab[0];
442 // get status
443 if (!xmlHasProp(updatecheck_node, ConstXMLStr("status"))) {
444 LOG(ERROR) << "Response missing status";
Darin Petkovedc522e2010-11-05 09:35:17 -0700445 completer.set_code(kActionCodeOmahaRequestNoUpdateCheckStatus);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000446 return;
447 }
448
Darin Petkov6a5b3222010-07-13 14:55:28 -0700449 OmahaResponse output_object;
Darin Petkov85ced132010-09-01 10:20:56 -0700450 base::StringToInt(XmlGetProperty(updatecheck_node, "PollInterval"),
451 &output_object.poll_interval);
452 const string status(XmlGetProperty(updatecheck_node, "status"));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000453 if (status == "noupdate") {
454 LOG(INFO) << "No update.";
455 output_object.update_exists = false;
456 SetOutputObject(output_object);
Darin Petkovc1a8b422010-07-19 11:34:49 -0700457 completer.set_code(kActionCodeSuccess);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000458 return;
459 }
460
461 if (status != "ok") {
462 LOG(ERROR) << "Unknown status: " << status;
Darin Petkovedc522e2010-11-05 09:35:17 -0700463 completer.set_code(kActionCodeOmahaRequestBadUpdateCheckStatus);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000464 return;
465 }
466
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700467 if (params_->update_disabled) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700468 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
Jay Srinivasan0a708742012-03-20 11:26:12 -0700469 completer.set_code(kActionCodeOmahaUpdateIgnoredPerPolicy);
470 return;
471 }
472
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700473 if (ShouldDeferDownload(updatecheck_node)) {
474 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
475 completer.set_code(kActionCodeOmahaUpdateDeferredPerPolicy);
476 return;
477 }
478
rspangler@google.com49fdf182009-10-10 00:57:34 +0000479 // In best-effort fashion, fetch the rest of the expected attributes
480 // from the updatecheck node, then return the object
481 output_object.update_exists = true;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700482 completer.set_code(kActionCodeSuccess);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000483
484 output_object.display_version =
485 XmlGetProperty(updatecheck_node, "DisplayVersion");
486 output_object.codebase = XmlGetProperty(updatecheck_node, "codebase");
487 output_object.more_info_url = XmlGetProperty(updatecheck_node, "MoreInfo");
Darin Petkovd22cb292010-09-29 10:02:29 -0700488 output_object.hash = XmlGetProperty(updatecheck_node, "sha256");
rspangler@google.com49fdf182009-10-10 00:57:34 +0000489 output_object.size = ParseInt(XmlGetProperty(updatecheck_node, "size"));
490 output_object.needs_admin =
491 XmlGetProperty(updatecheck_node, "needsadmin") == "true";
492 output_object.prompt = XmlGetProperty(updatecheck_node, "Prompt") == "true";
Darin Petkov6c118642010-10-21 12:06:30 -0700493 output_object.deadline = XmlGetProperty(updatecheck_node, "deadline");
rspangler@google.com49fdf182009-10-10 00:57:34 +0000494 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000495}
496
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700497bool OmahaRequestAction::ShouldDeferDownload(xmlNode* updatecheck_node) {
498 // We should defer the downloads only if we've first satisfied the
499 // wall-clock-based-waiting period and then the update-check-based waiting
500 // period, if required.
501
502 if (!params_->wall_clock_based_wait_enabled) {
503 // Wall-clock-based waiting period is not enabled, so no scattering needed.
504 return false;
505 }
506
507 switch (IsWallClockBasedWaitingSatisfied(updatecheck_node)) {
508 case kWallClockWaitNotSatisfied:
509 // We haven't even satisfied the first condition, passing the
510 // wall-clock-based waiting period, so we should defer the downloads
511 // until that happens.
512 LOG(INFO) << "wall-clock-based-wait not satisfied.";
513 return true;
514
515 case kWallClockWaitDoneButUpdateCheckWaitRequired:
516 LOG(INFO) << "wall-clock-based-wait satisfied and "
517 << "update-check-based-wait required.";
518 return !IsUpdateCheckCountBasedWaitingSatisfied(updatecheck_node);
519
520 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
521 // Wall-clock-based waiting period is satisfied, and it's determined
522 // that we do not need the update-check-based wait. so no need to
523 // defer downloads.
524 LOG(INFO) << "wall-clock-based-wait satisfied and "
525 << "update-check-based-wait is not required.";
526 return false;
527
528 default:
529 // Returning false for this default case so we err on the
530 // side of downloading updates than deferring in case of any bugs.
531 NOTREACHED();
532 return false;
533 }
534}
535
536OmahaRequestAction::WallClockWaitResult
537OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
538 xmlNode* updatecheck_node) {
539 Time update_published_time;
540
541 // UpdatePublishedOn must be in GMT.
542 if (!Time::FromString(
543 XmlGetProperty(updatecheck_node, "UpdatePublishedOn").c_str(),
544 &update_published_time)) {
545 LOG(INFO) << "UpdatePublishedOn not present in rule. Treating as 0.";
546 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
547 }
548
549 TimeDelta elapsed_time = Time::Now() - update_published_time;
550 TimeDelta max_scatter_period = TimeDelta::FromDays(
551 ParseInt(XmlGetProperty(updatecheck_node, "MaxDaysToScatter")));
552
553 LOG(INFO) << "Update Published On = "
554 << utils::ToString(update_published_time)
555 << ", Waiting Period = "
556 << utils::FormatSecs(params_->waiting_period.InSeconds())
557 << ", Time Elapsed = "
558 << utils::FormatSecs(elapsed_time.InSeconds())
559 << ", MaxDaysToScatter = "
560 << max_scatter_period.InDays();
561
562 if (!XmlGetProperty(updatecheck_node, "deadline").empty()) {
563 // The deadline is set for all rules which serve a delta update from a
564 // previous FSI, which means this update will be applied mostly in OOBE
565 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
566 // quickly.
567 LOG(INFO) << "Not scattering as deadline flag is set";
568 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
569 }
570
571 if (max_scatter_period.InDays() == 0) {
572 // This means the Omaha rule creator decides that this rule
573 // should not be scattered irrespective of the policy.
574 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
575 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
576 }
577
578 if (elapsed_time > max_scatter_period) {
579 // This means it's been a while since the update was published and
580 // we are less likely to cause bandwidth spikes by downloading now.
581 // This also establishes an upperbound wait in terms of wall-clock time
582 // so as to prevent machines from not getting updated for too long.
583 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
584 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
585 }
586
587 // This means we are required to participate in scattering.
588 // See if our turn has arrived now.
589 TimeDelta remaining_wait_time = params_->waiting_period - elapsed_time;
590 if (remaining_wait_time.InSeconds() <= 0) {
591 // Yes, it's our turn now.
592 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
593
594 // But we can't download until the update-check-count-based wait is also
595 // satisfied, so mark it as required now if update checks are enabled.
596 return params_->update_check_count_wait_enabled ?
597 kWallClockWaitDoneButUpdateCheckWaitRequired :
598 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
599 }
600
601 // Not our turn yet, so we have to wait until our turn to
602 // help scatter the downloads across all clients of the enterprise.
603 LOG(INFO) << "Update deferred for another "
604 << utils::FormatSecs(remaining_wait_time.InSeconds())
605 << " per policy.";
606 return kWallClockWaitNotSatisfied;
607}
608
609bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied(
610 xmlNode* updatecheck_node) {
611 int64 update_check_count_value;
612
613 if (prefs_->Exists(kPrefsUpdateCheckCount)) {
614 if (!prefs_->GetInt64(kPrefsUpdateCheckCount, &update_check_count_value)) {
615 // We are unable to read the update check count from file for some reason.
616 // So let's proceed anyway so as to not stall the update.
617 LOG(ERROR) << "Unable to read update check count. "
618 << "Skipping update-check-count-based-wait.";
619 return true;
620 }
621 } else {
622 // This file does not exist. This means we haven't started our update
623 // check count down yet, so this is the right time to start the count down.
624 update_check_count_value = base::RandInt(
625 params_->min_update_checks_needed,
626 params_->max_update_checks_allowed);
627
628 LOG(INFO) << "Randomly picked update check count value = "
629 << update_check_count_value;
630
631 // Write out the initial value of update_check_count_value.
632 if (!prefs_->SetInt64(kPrefsUpdateCheckCount, update_check_count_value)) {
633 // We weren't able to write the update check count file for some reason.
634 // So let's proceed anyway so as to not stall the update.
635 LOG(ERROR) << "Unable to write update check count. "
636 << "Skipping update-check-count-based-wait.";
637 return true;
638 }
639 }
640
641 if (update_check_count_value == 0) {
642 LOG(INFO) << "Successfully passed the update-check-based-wait.";
643 return true;
644 }
645
646 if (update_check_count_value < 0 ||
647 update_check_count_value > params_->max_update_checks_allowed) {
648 // We err on the side of skipping scattering logic instead of stalling
649 // a machine from receiving any updates in case of any unexpected state.
650 LOG(ERROR) << "Invalid value for update check count detected. "
651 << "Skipping update-check-count-based-wait.";
652 return true;
653 }
654
655 // Legal value, we need to wait for more update checks to happen
656 // until this becomes 0.
657 LOG(INFO) << "Deferring Omaha updates for another "
658 << update_check_count_value
659 << " update checks per policy";
660 return false;
661}
662
663} // namespace chromeos_update_engine