blob: 1c79fb06949e1ab7c623aaae5ea6d4f2fc119de2 [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"
Andrew de los Reyes08c4e272010-04-15 14:02:17 -07006#include <inttypes.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +00007#include <sstream>
8
9#include <libxml/parser.h>
10#include <libxml/xpath.h>
11#include <libxml/xpathInternals.h>
12
Chris Masone790e62e2010-08-12 10:41:18 -070013#include "base/string_number_conversions.h"
Darin Petkov0dc8e9a2010-07-14 14:51:57 -070014#include "base/string_util.h"
Darin Petkov1cbd78f2010-07-29 12:38:34 -070015#include "base/time.h"
Chris Masone790e62e2010-08-12 10:41:18 -070016#include "base/logging.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000017#include "update_engine/action_pipe.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070018#include "update_engine/omaha_request_params.h"
Darin Petkov1cbd78f2010-07-29 12:38:34 -070019#include "update_engine/prefs_interface.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000020#include "update_engine/utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000021
Darin Petkov1cbd78f2010-07-29 12:38:34 -070022using base::Time;
23using base::TimeDelta;
rspangler@google.com49fdf182009-10-10 00:57:34 +000024using std::string;
25
26namespace chromeos_update_engine {
27
rspangler@google.com49fdf182009-10-10 00:57:34 +000028namespace {
29
30const string kGupdateVersion("ChromeOSUpdateEngine-0.1.0.0");
31
32// This is handy for passing strings into libxml2
33#define ConstXMLStr(x) (reinterpret_cast<const xmlChar*>(x))
34
35// These are for scoped_ptr_malloc, which is like scoped_ptr, but allows
36// a custom free() function to be specified.
37class ScopedPtrXmlDocFree {
38 public:
39 inline void operator()(void* x) const {
40 xmlFreeDoc(reinterpret_cast<xmlDoc*>(x));
41 }
42};
43class ScopedPtrXmlFree {
44 public:
45 inline void operator()(void* x) const {
46 xmlFree(x);
47 }
48};
49class ScopedPtrXmlXPathObjectFree {
50 public:
51 inline void operator()(void* x) const {
52 xmlXPathFreeObject(reinterpret_cast<xmlXPathObject*>(x));
53 }
54};
55class ScopedPtrXmlXPathContextFree {
56 public:
57 inline void operator()(void* x) const {
58 xmlXPathFreeContext(reinterpret_cast<xmlXPathContext*>(x));
59 }
60};
61
Darin Petkov1cbd78f2010-07-29 12:38:34 -070062// Returns true if |ping_days| has a value that needs to be sent,
63// false otherwise.
64bool ShouldPing(int ping_days) {
65 return ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged;
66}
67
68// Returns an XML ping element attribute assignment with attribute
69// |name| and value |ping_days| if |ping_days| has a value that needs
70// to be sent, or an empty string otherwise.
71string GetPingAttribute(const string& name, int ping_days) {
72 if (ShouldPing(ping_days)) {
73 return StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
74 }
75 return "";
76}
77
78// Returns an XML ping element if any of the elapsed days need to be
79// sent, or an empty string otherwise.
80string GetPingBody(int ping_active_days, int ping_roll_call_days) {
81 string ping_active = GetPingAttribute("a", ping_active_days);
82 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
83 if (!ping_active.empty() || !ping_roll_call.empty()) {
84 return StringPrintf(" <o:ping%s%s></o:ping>\n",
85 ping_active.c_str(),
86 ping_roll_call.c_str());
87 }
88 return "";
89}
90
Darin Petkov0dc8e9a2010-07-14 14:51:57 -070091string FormatRequest(const OmahaEvent* event,
Darin Petkov1cbd78f2010-07-29 12:38:34 -070092 const OmahaRequestParams& params,
93 int ping_active_days,
94 int ping_roll_call_days) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -070095 string body;
96 if (event == NULL) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -070097 body = GetPingBody(ping_active_days, ping_roll_call_days) +
98 " <o:updatecheck></o:updatecheck>\n";
Darin Petkov0dc8e9a2010-07-14 14:51:57 -070099 } else {
Darin Petkove17f86b2010-07-20 09:12:01 -0700100 // The error code is an optional attribute so append it only if
101 // the result is not success.
102 string error_code;
103 if (event->result != OmahaEvent::kResultSuccess) {
104 error_code = StringPrintf(" errorcode=\"%d\"", event->error_code);
105 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700106 body = StringPrintf(
Darin Petkove17f86b2010-07-20 09:12:01 -0700107 " <o:event eventtype=\"%d\" eventresult=\"%d\"%s></o:event>\n",
108 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700109 }
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700110 return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
111 "<o:gupdate xmlns:o=\"http://www.google.com/update2/request\" "
112 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
113 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" "
114 "protocol=\"2.0\" ismachine=\"1\">\n"
rspangler@google.com49fdf182009-10-10 00:57:34 +0000115 " <o:os version=\"" + XmlEncode(params.os_version) + "\" platform=\"" +
116 XmlEncode(params.os_platform) + "\" sp=\"" +
117 XmlEncode(params.os_sp) + "\"></o:os>\n"
118 " <o:app appid=\"" + XmlEncode(params.app_id) + "\" version=\"" +
119 XmlEncode(params.app_version) + "\" "
120 "lang=\"" + XmlEncode(params.app_lang) + "\" track=\"" +
Andrew de los Reyes37c20322010-06-30 13:27:19 -0700121 XmlEncode(params.app_track) + "\" board=\"" +
Darin Petkovfbb40092010-07-29 17:05:50 -0700122 XmlEncode(params.os_board) + "\" hardware_class=\"" +
123 XmlEncode(params.hardware_class) + "\" delta_okay=\"" +
Andrew de los Reyes3f0303a2010-07-15 22:35:35 -0700124 (params.delta_okay ? "true" : "false") + "\">\n" + body +
rspangler@google.com49fdf182009-10-10 00:57:34 +0000125 " </o:app>\n"
126 "</o:gupdate>\n";
127}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700128
rspangler@google.com49fdf182009-10-10 00:57:34 +0000129} // namespace {}
130
131// Encodes XML entities in a given string with libxml2. input must be
132// UTF-8 formatted. Output will be UTF-8 formatted.
133string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700134 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
135 // // cpu, considering creating one and caching it.
136 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
137 // xmlNewDoc(ConstXMLStr("1.0")));
138 // if (!xml_doc.get()) {
139 // LOG(ERROR) << "Unable to create xmlDoc";
140 // return "";
141 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000142 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
143 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
144 return string(reinterpret_cast<const char *>(str.get()));
145}
146
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700147OmahaRequestAction::OmahaRequestAction(PrefsInterface* prefs,
148 const OmahaRequestParams& params,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700149 OmahaEvent* event,
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700150 HttpFetcher* http_fetcher)
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700151 : prefs_(prefs),
152 params_(params),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700153 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700154 http_fetcher_(http_fetcher),
155 ping_active_days_(0),
156 ping_roll_call_days_(0) {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000157
Darin Petkov6a5b3222010-07-13 14:55:28 -0700158OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000159
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700160// Calculates the value to use for the ping days parameter.
161int OmahaRequestAction::CalculatePingDays(const string& key) {
162 int days = kNeverPinged;
163 int64_t last_ping = 0;
164 if (prefs_->GetInt64(key, &last_ping) && last_ping >= 0) {
165 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
166 if (days < 0) {
167 // If |days| is negative, then the system clock must have jumped
168 // back in time since the ping was sent. Mark the value so that
169 // it doesn't get sent to the server but we still update the
170 // last ping daystart preference. This way the next ping time
171 // will be correct, hopefully.
172 days = kPingTimeJump;
173 LOG(WARNING) <<
174 "System clock jumped back in time. Resetting ping daystarts.";
175 }
176 }
177 return days;
178}
179
180void OmahaRequestAction::InitPingDays() {
181 // We send pings only along with update checks, not with events.
182 if (IsEvent()) {
183 return;
184 }
185 // TODO(petkov): Figure a way to distinguish active use pings
186 // vs. roll call pings. Currently, the two pings are identical. A
187 // fix needs to change this code as well as UpdateLastPingDays.
188 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
189 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
190}
191
Darin Petkov6a5b3222010-07-13 14:55:28 -0700192void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000193 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700194 InitPingDays();
195 string request_post(FormatRequest(event_.get(),
196 params_,
197 ping_active_days_,
198 ping_roll_call_days_));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000199 http_fetcher_->SetPostData(request_post.data(), request_post.size());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700200 LOG(INFO) << "Posting an Omaha request to " << params_.update_url;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700201 LOG(INFO) << "Request: " << request_post;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700202 http_fetcher_->BeginTransfer(params_.update_url);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000203}
204
Darin Petkov6a5b3222010-07-13 14:55:28 -0700205void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000206 http_fetcher_->TerminateTransfer();
207}
208
209// We just store the response in the buffer. Once we've received all bytes,
210// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700211void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
212 const char* bytes,
213 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000214 response_buffer_.reserve(response_buffer_.size() + length);
215 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
216}
217
218namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000219// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
220// on the returned object.
221// This code is roughly based on the libxml tutorial at:
222// http://xmlsoft.org/tutorial/apd.html
223xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath,
224 const xmlChar* ns, const xmlChar* ns_url) {
225 xmlXPathObject* result = NULL;
226
227 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
228 xmlXPathNewContext(doc));
229 if (!context.get()) {
230 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
231 return NULL;
232 }
233 if (xmlXPathRegisterNs(context.get(), ns, ns_url) < 0) {
234 LOG(ERROR) << "xmlXPathRegisterNs() returned error";
235 return NULL;
236 }
237
238 result = xmlXPathEvalExpression(xpath, context.get());
239
240 if (result == NULL) {
241 LOG(ERROR) << "xmlXPathEvalExpression returned error";
242 return NULL;
243 }
244 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
245 LOG(INFO) << "xpath not found in doc";
246 xmlXPathFreeObject(result);
247 return NULL;
248 }
249 return result;
250}
251
252// Returns the string value of a named attribute on a node, or empty string
253// if no such node exists. If the attribute exists and has a value of
254// empty string, there's no way to distinguish that from the attribute
255// not existing.
256string XmlGetProperty(xmlNode* node, const char* name) {
257 if (!xmlHasProp(node, ConstXMLStr(name)))
258 return "";
259 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
260 xmlGetProp(node, ConstXMLStr(name)));
261 string ret(reinterpret_cast<const char *>(str.get()));
262 return ret;
263}
264
265// Parses a 64 bit base-10 int from a string and returns it. Returns 0
266// on error. If the string contains "0", that's indistinguishable from
267// error.
268off_t ParseInt(const string& str) {
269 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700270 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000271 if (rc < 1) {
272 // failure
273 return 0;
274 }
275 return ret;
276}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700277
278// Update the last ping day preferences based on the server daystart
279// response. Returns true on success, false otherwise.
280bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
281 static const char kNamespace[] = "x";
282 static const char kDaystartNodeXpath[] = "/x:gupdate/x:daystart";
283 static const char kNsUrl[] = "http://www.google.com/update2/response";
284
285 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
286 xpath_nodeset(GetNodeSet(doc,
287 ConstXMLStr(kDaystartNodeXpath),
288 ConstXMLStr(kNamespace),
289 ConstXMLStr(kNsUrl)));
290 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
291 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
292 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
293 xmlNode* daystart_node = nodeset->nodeTab[0];
294 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
295 ConstXMLStr("elapsed_seconds")));
296
297 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700298 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
299 "elapsed_seconds"),
300 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700301 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
302
303 // Remember the local time that matches the server's last midnight
304 // time.
305 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
306 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
307 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
308 return true;
309}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000310} // namespace {}
311
312// If the transfer was successful, this uses libxml2 to parse the response
313// and fill in the appropriate fields of the output object. Also, notifies
314// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700315void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
316 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000317 ScopedActionCompleter completer(processor_, this);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700318 LOG(INFO) << "Omaha request response: " << string(response_buffer_.begin(),
319 response_buffer_.end());
320
321 // Events are best effort transactions -- assume they always succeed.
322 if (IsEvent()) {
323 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Darin Petkovc1a8b422010-07-19 11:34:49 -0700324 completer.set_code(kActionCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700325 return;
326 }
327
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700328 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700329 LOG(ERROR) << "Omaha request network transfer failed.";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000330 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700331 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000332 if (!HasOutputPipe()) {
333 // Just set success to whether or not the http transfer succeeded,
334 // which must be true at this point in the code.
Darin Petkovc1a8b422010-07-19 11:34:49 -0700335 completer.set_code(kActionCodeSuccess);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000336 return;
337 }
338
339 // parse our response and fill the fields in the output object
340 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
341 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
342 if (!doc.get()) {
343 LOG(ERROR) << "Omaha response not valid XML";
344 return;
345 }
346
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700347 // If a ping was sent, update the last ping day preferences based on
348 // the server daystart response.
349 if (ShouldPing(ping_active_days_) ||
350 ShouldPing(ping_roll_call_days_) ||
351 ping_active_days_ == kPingTimeJump ||
352 ping_roll_call_days_ == kPingTimeJump) {
353 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), prefs_))
354 << "Failed to update the last ping day preferences!";
355 }
356
rspangler@google.com49fdf182009-10-10 00:57:34 +0000357 static const char* kNamespace("x");
358 static const char* kUpdatecheckNodeXpath("/x:gupdate/x:app/x:updatecheck");
359 static const char* kNsUrl("http://www.google.com/update2/response");
360
361 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
362 xpath_nodeset(GetNodeSet(doc.get(),
363 ConstXMLStr(kUpdatecheckNodeXpath),
364 ConstXMLStr(kNamespace),
365 ConstXMLStr(kNsUrl)));
366 if (!xpath_nodeset.get()) {
367 return;
368 }
369 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
370 CHECK(nodeset) << "XPath missing NodeSet";
371 CHECK_GE(nodeset->nodeNr, 1);
372
373 xmlNode* updatecheck_node = nodeset->nodeTab[0];
374 // get status
375 if (!xmlHasProp(updatecheck_node, ConstXMLStr("status"))) {
376 LOG(ERROR) << "Response missing status";
377 return;
378 }
379
380 const string status(XmlGetProperty(updatecheck_node, "status"));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700381 OmahaResponse output_object;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000382 if (status == "noupdate") {
383 LOG(INFO) << "No update.";
384 output_object.update_exists = false;
385 SetOutputObject(output_object);
Darin Petkovc1a8b422010-07-19 11:34:49 -0700386 completer.set_code(kActionCodeSuccess);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000387 return;
388 }
389
390 if (status != "ok") {
391 LOG(ERROR) << "Unknown status: " << status;
392 return;
393 }
394
395 // In best-effort fashion, fetch the rest of the expected attributes
396 // from the updatecheck node, then return the object
397 output_object.update_exists = true;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700398 completer.set_code(kActionCodeSuccess);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000399
400 output_object.display_version =
401 XmlGetProperty(updatecheck_node, "DisplayVersion");
402 output_object.codebase = XmlGetProperty(updatecheck_node, "codebase");
403 output_object.more_info_url = XmlGetProperty(updatecheck_node, "MoreInfo");
404 output_object.hash = XmlGetProperty(updatecheck_node, "hash");
405 output_object.size = ParseInt(XmlGetProperty(updatecheck_node, "size"));
406 output_object.needs_admin =
407 XmlGetProperty(updatecheck_node, "needsadmin") == "true";
408 output_object.prompt = XmlGetProperty(updatecheck_node, "Prompt") == "true";
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700409 output_object.is_delta =
410 XmlGetProperty(updatecheck_node, "IsDelta") == "true";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000411 SetOutputObject(output_object);
412 return;
413}
414
415}; // namespace chromeos_update_engine