blob: c931065713bc13906506f9340c91b918bf384191 [file] [log] [blame]
Darin Petkova4a8a8c2010-07-15 22:21:12 -07001// Copyright (c) 2010 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>
10
Darin Petkov85ced132010-09-01 10:20:56 -070011#include <base/string_number_conversions.h>
12#include <base/string_util.h>
13#include <base/time.h>
14#include <base/logging.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000015#include <libxml/parser.h>
16#include <libxml/xpath.h>
17#include <libxml/xpathInternals.h>
18
19#include "update_engine/action_pipe.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070020#include "update_engine/omaha_request_params.h"
Darin Petkov1cbd78f2010-07-29 12:38:34 -070021#include "update_engine/prefs_interface.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000022#include "update_engine/utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000023
Darin Petkov1cbd78f2010-07-29 12:38:34 -070024using base::Time;
25using base::TimeDelta;
rspangler@google.com49fdf182009-10-10 00:57:34 +000026using std::string;
27
28namespace chromeos_update_engine {
29
rspangler@google.com49fdf182009-10-10 00:57:34 +000030namespace {
31
32const string kGupdateVersion("ChromeOSUpdateEngine-0.1.0.0");
33
34// This is handy for passing strings into libxml2
35#define ConstXMLStr(x) (reinterpret_cast<const xmlChar*>(x))
36
37// These are for scoped_ptr_malloc, which is like scoped_ptr, but allows
38// a custom free() function to be specified.
39class ScopedPtrXmlDocFree {
40 public:
41 inline void operator()(void* x) const {
42 xmlFreeDoc(reinterpret_cast<xmlDoc*>(x));
43 }
44};
45class ScopedPtrXmlFree {
46 public:
47 inline void operator()(void* x) const {
48 xmlFree(x);
49 }
50};
51class ScopedPtrXmlXPathObjectFree {
52 public:
53 inline void operator()(void* x) const {
54 xmlXPathFreeObject(reinterpret_cast<xmlXPathObject*>(x));
55 }
56};
57class ScopedPtrXmlXPathContextFree {
58 public:
59 inline void operator()(void* x) const {
60 xmlXPathFreeContext(reinterpret_cast<xmlXPathContext*>(x));
61 }
62};
63
Darin Petkov1cbd78f2010-07-29 12:38:34 -070064// Returns true if |ping_days| has a value that needs to be sent,
65// false otherwise.
66bool ShouldPing(int ping_days) {
67 return ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged;
68}
69
70// Returns an XML ping element attribute assignment with attribute
71// |name| and value |ping_days| if |ping_days| has a value that needs
72// to be sent, or an empty string otherwise.
73string GetPingAttribute(const string& name, int ping_days) {
74 if (ShouldPing(ping_days)) {
75 return StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
76 }
77 return "";
78}
79
80// Returns an XML ping element if any of the elapsed days need to be
81// sent, or an empty string otherwise.
82string GetPingBody(int ping_active_days, int ping_roll_call_days) {
83 string ping_active = GetPingAttribute("a", ping_active_days);
84 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
85 if (!ping_active.empty() || !ping_roll_call.empty()) {
86 return StringPrintf(" <o:ping%s%s></o:ping>\n",
87 ping_active.c_str(),
88 ping_roll_call.c_str());
89 }
90 return "";
91}
92
Darin Petkov0dc8e9a2010-07-14 14:51:57 -070093string FormatRequest(const OmahaEvent* event,
Darin Petkov1cbd78f2010-07-29 12:38:34 -070094 const OmahaRequestParams& params,
95 int ping_active_days,
96 int ping_roll_call_days) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -070097 string body;
98 if (event == NULL) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -070099 body = GetPingBody(ping_active_days, ping_roll_call_days) +
100 " <o:updatecheck></o:updatecheck>\n";
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700101 } else {
Darin Petkove17f86b2010-07-20 09:12:01 -0700102 // The error code is an optional attribute so append it only if
103 // the result is not success.
104 string error_code;
105 if (event->result != OmahaEvent::kResultSuccess) {
106 error_code = StringPrintf(" errorcode=\"%d\"", event->error_code);
107 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700108 body = StringPrintf(
Darin Petkove17f86b2010-07-20 09:12:01 -0700109 " <o:event eventtype=\"%d\" eventresult=\"%d\"%s></o:event>\n",
110 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700111 }
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700112 return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
113 "<o:gupdate xmlns:o=\"http://www.google.com/update2/request\" "
114 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
115 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" "
116 "protocol=\"2.0\" ismachine=\"1\">\n"
rspangler@google.com49fdf182009-10-10 00:57:34 +0000117 " <o:os version=\"" + XmlEncode(params.os_version) + "\" platform=\"" +
118 XmlEncode(params.os_platform) + "\" sp=\"" +
119 XmlEncode(params.os_sp) + "\"></o:os>\n"
120 " <o:app appid=\"" + XmlEncode(params.app_id) + "\" version=\"" +
121 XmlEncode(params.app_version) + "\" "
122 "lang=\"" + XmlEncode(params.app_lang) + "\" track=\"" +
Andrew de los Reyes37c20322010-06-30 13:27:19 -0700123 XmlEncode(params.app_track) + "\" board=\"" +
Darin Petkovfbb40092010-07-29 17:05:50 -0700124 XmlEncode(params.os_board) + "\" hardware_class=\"" +
125 XmlEncode(params.hardware_class) + "\" delta_okay=\"" +
Andrew de los Reyes3f0303a2010-07-15 22:35:35 -0700126 (params.delta_okay ? "true" : "false") + "\">\n" + body +
rspangler@google.com49fdf182009-10-10 00:57:34 +0000127 " </o:app>\n"
128 "</o:gupdate>\n";
129}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700130
rspangler@google.com49fdf182009-10-10 00:57:34 +0000131} // namespace {}
132
133// Encodes XML entities in a given string with libxml2. input must be
134// UTF-8 formatted. Output will be UTF-8 formatted.
135string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700136 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
137 // // cpu, considering creating one and caching it.
138 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
139 // xmlNewDoc(ConstXMLStr("1.0")));
140 // if (!xml_doc.get()) {
141 // LOG(ERROR) << "Unable to create xmlDoc";
142 // return "";
143 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000144 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
145 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
146 return string(reinterpret_cast<const char *>(str.get()));
147}
148
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700149OmahaRequestAction::OmahaRequestAction(PrefsInterface* prefs,
150 const OmahaRequestParams& params,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700151 OmahaEvent* event,
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700152 HttpFetcher* http_fetcher)
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700153 : prefs_(prefs),
154 params_(params),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700155 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700156 http_fetcher_(http_fetcher),
157 ping_active_days_(0),
158 ping_roll_call_days_(0) {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000159
Darin Petkov6a5b3222010-07-13 14:55:28 -0700160OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000161
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700162// Calculates the value to use for the ping days parameter.
163int OmahaRequestAction::CalculatePingDays(const string& key) {
164 int days = kNeverPinged;
165 int64_t last_ping = 0;
166 if (prefs_->GetInt64(key, &last_ping) && last_ping >= 0) {
167 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
168 if (days < 0) {
169 // If |days| is negative, then the system clock must have jumped
170 // back in time since the ping was sent. Mark the value so that
171 // it doesn't get sent to the server but we still update the
172 // last ping daystart preference. This way the next ping time
173 // will be correct, hopefully.
174 days = kPingTimeJump;
175 LOG(WARNING) <<
176 "System clock jumped back in time. Resetting ping daystarts.";
177 }
178 }
179 return days;
180}
181
182void OmahaRequestAction::InitPingDays() {
183 // We send pings only along with update checks, not with events.
184 if (IsEvent()) {
185 return;
186 }
187 // TODO(petkov): Figure a way to distinguish active use pings
188 // vs. roll call pings. Currently, the two pings are identical. A
189 // fix needs to change this code as well as UpdateLastPingDays.
190 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
191 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
192}
193
Darin Petkov6a5b3222010-07-13 14:55:28 -0700194void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000195 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700196 InitPingDays();
197 string request_post(FormatRequest(event_.get(),
198 params_,
199 ping_active_days_,
200 ping_roll_call_days_));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000201 http_fetcher_->SetPostData(request_post.data(), request_post.size());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700202 LOG(INFO) << "Posting an Omaha request to " << params_.update_url;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700203 LOG(INFO) << "Request: " << request_post;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700204 http_fetcher_->BeginTransfer(params_.update_url);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000205}
206
Darin Petkov6a5b3222010-07-13 14:55:28 -0700207void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000208 http_fetcher_->TerminateTransfer();
209}
210
211// We just store the response in the buffer. Once we've received all bytes,
212// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700213void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
214 const char* bytes,
215 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000216 response_buffer_.reserve(response_buffer_.size() + length);
217 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
218}
219
220namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000221// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
222// on the returned object.
223// This code is roughly based on the libxml tutorial at:
224// http://xmlsoft.org/tutorial/apd.html
225xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath,
226 const xmlChar* ns, const xmlChar* ns_url) {
227 xmlXPathObject* result = NULL;
228
229 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
230 xmlXPathNewContext(doc));
231 if (!context.get()) {
232 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
233 return NULL;
234 }
235 if (xmlXPathRegisterNs(context.get(), ns, ns_url) < 0) {
236 LOG(ERROR) << "xmlXPathRegisterNs() returned error";
237 return NULL;
238 }
239
240 result = xmlXPathEvalExpression(xpath, context.get());
241
242 if (result == NULL) {
243 LOG(ERROR) << "xmlXPathEvalExpression returned error";
244 return NULL;
245 }
246 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
247 LOG(INFO) << "xpath not found in doc";
248 xmlXPathFreeObject(result);
249 return NULL;
250 }
251 return result;
252}
253
254// Returns the string value of a named attribute on a node, or empty string
255// if no such node exists. If the attribute exists and has a value of
256// empty string, there's no way to distinguish that from the attribute
257// not existing.
258string XmlGetProperty(xmlNode* node, const char* name) {
259 if (!xmlHasProp(node, ConstXMLStr(name)))
260 return "";
261 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
262 xmlGetProp(node, ConstXMLStr(name)));
263 string ret(reinterpret_cast<const char *>(str.get()));
264 return ret;
265}
266
267// Parses a 64 bit base-10 int from a string and returns it. Returns 0
268// on error. If the string contains "0", that's indistinguishable from
269// error.
270off_t ParseInt(const string& str) {
271 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700272 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000273 if (rc < 1) {
274 // failure
275 return 0;
276 }
277 return ret;
278}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700279
280// Update the last ping day preferences based on the server daystart
281// response. Returns true on success, false otherwise.
282bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
283 static const char kNamespace[] = "x";
284 static const char kDaystartNodeXpath[] = "/x:gupdate/x:daystart";
285 static const char kNsUrl[] = "http://www.google.com/update2/response";
286
287 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
288 xpath_nodeset(GetNodeSet(doc,
289 ConstXMLStr(kDaystartNodeXpath),
290 ConstXMLStr(kNamespace),
291 ConstXMLStr(kNsUrl)));
292 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
293 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
294 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
295 xmlNode* daystart_node = nodeset->nodeTab[0];
296 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
297 ConstXMLStr("elapsed_seconds")));
298
299 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700300 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
301 "elapsed_seconds"),
302 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700303 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
304
305 // Remember the local time that matches the server's last midnight
306 // time.
307 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
308 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
309 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
310 return true;
311}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000312} // namespace {}
313
314// If the transfer was successful, this uses libxml2 to parse the response
315// and fill in the appropriate fields of the output object. Also, notifies
316// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700317void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
318 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000319 ScopedActionCompleter completer(processor_, this);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700320 LOG(INFO) << "Omaha request response: " << string(response_buffer_.begin(),
321 response_buffer_.end());
322
323 // Events are best effort transactions -- assume they always succeed.
324 if (IsEvent()) {
325 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Darin Petkovc1a8b422010-07-19 11:34:49 -0700326 completer.set_code(kActionCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700327 return;
328 }
329
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700330 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700331 LOG(ERROR) << "Omaha request network transfer failed.";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000332 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700333 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000334 if (!HasOutputPipe()) {
335 // Just set success to whether or not the http transfer succeeded,
336 // which must be true at this point in the code.
Darin Petkovc1a8b422010-07-19 11:34:49 -0700337 completer.set_code(kActionCodeSuccess);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000338 return;
339 }
340
341 // parse our response and fill the fields in the output object
342 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
343 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
344 if (!doc.get()) {
345 LOG(ERROR) << "Omaha response not valid XML";
346 return;
347 }
348
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700349 // If a ping was sent, update the last ping day preferences based on
350 // the server daystart response.
351 if (ShouldPing(ping_active_days_) ||
352 ShouldPing(ping_roll_call_days_) ||
353 ping_active_days_ == kPingTimeJump ||
354 ping_roll_call_days_ == kPingTimeJump) {
355 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), prefs_))
356 << "Failed to update the last ping day preferences!";
357 }
358
rspangler@google.com49fdf182009-10-10 00:57:34 +0000359 static const char* kNamespace("x");
360 static const char* kUpdatecheckNodeXpath("/x:gupdate/x:app/x:updatecheck");
361 static const char* kNsUrl("http://www.google.com/update2/response");
362
363 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
364 xpath_nodeset(GetNodeSet(doc.get(),
365 ConstXMLStr(kUpdatecheckNodeXpath),
366 ConstXMLStr(kNamespace),
367 ConstXMLStr(kNsUrl)));
368 if (!xpath_nodeset.get()) {
369 return;
370 }
371 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
372 CHECK(nodeset) << "XPath missing NodeSet";
373 CHECK_GE(nodeset->nodeNr, 1);
374
375 xmlNode* updatecheck_node = nodeset->nodeTab[0];
376 // get status
377 if (!xmlHasProp(updatecheck_node, ConstXMLStr("status"))) {
378 LOG(ERROR) << "Response missing status";
379 return;
380 }
381
Darin Petkov6a5b3222010-07-13 14:55:28 -0700382 OmahaResponse output_object;
Darin Petkov85ced132010-09-01 10:20:56 -0700383 base::StringToInt(XmlGetProperty(updatecheck_node, "PollInterval"),
384 &output_object.poll_interval);
385 const string status(XmlGetProperty(updatecheck_node, "status"));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000386 if (status == "noupdate") {
387 LOG(INFO) << "No update.";
388 output_object.update_exists = false;
389 SetOutputObject(output_object);
Darin Petkovc1a8b422010-07-19 11:34:49 -0700390 completer.set_code(kActionCodeSuccess);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000391 return;
392 }
393
394 if (status != "ok") {
395 LOG(ERROR) << "Unknown status: " << status;
396 return;
397 }
398
399 // In best-effort fashion, fetch the rest of the expected attributes
400 // from the updatecheck node, then return the object
401 output_object.update_exists = true;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700402 completer.set_code(kActionCodeSuccess);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000403
404 output_object.display_version =
405 XmlGetProperty(updatecheck_node, "DisplayVersion");
406 output_object.codebase = XmlGetProperty(updatecheck_node, "codebase");
407 output_object.more_info_url = XmlGetProperty(updatecheck_node, "MoreInfo");
408 output_object.hash = XmlGetProperty(updatecheck_node, "hash");
409 output_object.size = ParseInt(XmlGetProperty(updatecheck_node, "size"));
410 output_object.needs_admin =
411 XmlGetProperty(updatecheck_node, "needsadmin") == "true";
412 output_object.prompt = XmlGetProperty(updatecheck_node, "Prompt") == "true";
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700413 output_object.is_delta =
414 XmlGetProperty(updatecheck_node, "IsDelta") == "true";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000415 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000416}
417
418}; // namespace chromeos_update_engine