blob: cd318051b2cb1a11d87831d20dbd5570ae0b18e0 [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
Darin Petkov0dc8e9a2010-07-14 14:51:57 -070013#include "base/string_util.h"
Darin Petkov1cbd78f2010-07-29 12:38:34 -070014#include "base/time.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000015#include "chromeos/obsolete_logging.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000016#include "update_engine/action_pipe.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070017#include "update_engine/omaha_request_params.h"
Darin Petkov1cbd78f2010-07-29 12:38:34 -070018#include "update_engine/prefs_interface.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000019#include "update_engine/utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000020
Darin Petkov1cbd78f2010-07-29 12:38:34 -070021using base::Time;
22using base::TimeDelta;
rspangler@google.com49fdf182009-10-10 00:57:34 +000023using std::string;
24
25namespace chromeos_update_engine {
26
rspangler@google.com49fdf182009-10-10 00:57:34 +000027namespace {
28
29const string kGupdateVersion("ChromeOSUpdateEngine-0.1.0.0");
30
31// This is handy for passing strings into libxml2
32#define ConstXMLStr(x) (reinterpret_cast<const xmlChar*>(x))
33
34// These are for scoped_ptr_malloc, which is like scoped_ptr, but allows
35// a custom free() function to be specified.
36class ScopedPtrXmlDocFree {
37 public:
38 inline void operator()(void* x) const {
39 xmlFreeDoc(reinterpret_cast<xmlDoc*>(x));
40 }
41};
42class ScopedPtrXmlFree {
43 public:
44 inline void operator()(void* x) const {
45 xmlFree(x);
46 }
47};
48class ScopedPtrXmlXPathObjectFree {
49 public:
50 inline void operator()(void* x) const {
51 xmlXPathFreeObject(reinterpret_cast<xmlXPathObject*>(x));
52 }
53};
54class ScopedPtrXmlXPathContextFree {
55 public:
56 inline void operator()(void* x) const {
57 xmlXPathFreeContext(reinterpret_cast<xmlXPathContext*>(x));
58 }
59};
60
Darin Petkov1cbd78f2010-07-29 12:38:34 -070061// Returns true if |ping_days| has a value that needs to be sent,
62// false otherwise.
63bool ShouldPing(int ping_days) {
64 return ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged;
65}
66
67// Returns an XML ping element attribute assignment with attribute
68// |name| and value |ping_days| if |ping_days| has a value that needs
69// to be sent, or an empty string otherwise.
70string GetPingAttribute(const string& name, int ping_days) {
71 if (ShouldPing(ping_days)) {
72 return StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
73 }
74 return "";
75}
76
77// Returns an XML ping element if any of the elapsed days need to be
78// sent, or an empty string otherwise.
79string GetPingBody(int ping_active_days, int ping_roll_call_days) {
80 string ping_active = GetPingAttribute("a", ping_active_days);
81 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
82 if (!ping_active.empty() || !ping_roll_call.empty()) {
83 return StringPrintf(" <o:ping%s%s></o:ping>\n",
84 ping_active.c_str(),
85 ping_roll_call.c_str());
86 }
87 return "";
88}
89
Darin Petkov0dc8e9a2010-07-14 14:51:57 -070090string FormatRequest(const OmahaEvent* event,
Darin Petkov1cbd78f2010-07-29 12:38:34 -070091 const OmahaRequestParams& params,
92 int ping_active_days,
93 int ping_roll_call_days) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -070094 string body;
95 if (event == NULL) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -070096 body = GetPingBody(ping_active_days, ping_roll_call_days) +
97 " <o:updatecheck></o:updatecheck>\n";
Darin Petkov0dc8e9a2010-07-14 14:51:57 -070098 } else {
Darin Petkove17f86b2010-07-20 09:12:01 -070099 // The error code is an optional attribute so append it only if
100 // the result is not success.
101 string error_code;
102 if (event->result != OmahaEvent::kResultSuccess) {
103 error_code = StringPrintf(" errorcode=\"%d\"", event->error_code);
104 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700105 body = StringPrintf(
Darin Petkove17f86b2010-07-20 09:12:01 -0700106 " <o:event eventtype=\"%d\" eventresult=\"%d\"%s></o:event>\n",
107 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700108 }
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700109 return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
110 "<o:gupdate xmlns:o=\"http://www.google.com/update2/request\" "
111 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
112 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" "
113 "protocol=\"2.0\" ismachine=\"1\">\n"
rspangler@google.com49fdf182009-10-10 00:57:34 +0000114 " <o:os version=\"" + XmlEncode(params.os_version) + "\" platform=\"" +
115 XmlEncode(params.os_platform) + "\" sp=\"" +
116 XmlEncode(params.os_sp) + "\"></o:os>\n"
117 " <o:app appid=\"" + XmlEncode(params.app_id) + "\" version=\"" +
118 XmlEncode(params.app_version) + "\" "
119 "lang=\"" + XmlEncode(params.app_lang) + "\" track=\"" +
Andrew de los Reyes37c20322010-06-30 13:27:19 -0700120 XmlEncode(params.app_track) + "\" board=\"" +
Darin Petkovfbb40092010-07-29 17:05:50 -0700121 XmlEncode(params.os_board) + "\" hardware_class=\"" +
122 XmlEncode(params.hardware_class) + "\" delta_okay=\"" +
Andrew de los Reyes3f0303a2010-07-15 22:35:35 -0700123 (params.delta_okay ? "true" : "false") + "\">\n" + body +
rspangler@google.com49fdf182009-10-10 00:57:34 +0000124 " </o:app>\n"
125 "</o:gupdate>\n";
126}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700127
rspangler@google.com49fdf182009-10-10 00:57:34 +0000128} // namespace {}
129
130// Encodes XML entities in a given string with libxml2. input must be
131// UTF-8 formatted. Output will be UTF-8 formatted.
132string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700133 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
134 // // cpu, considering creating one and caching it.
135 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
136 // xmlNewDoc(ConstXMLStr("1.0")));
137 // if (!xml_doc.get()) {
138 // LOG(ERROR) << "Unable to create xmlDoc";
139 // return "";
140 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000141 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
142 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
143 return string(reinterpret_cast<const char *>(str.get()));
144}
145
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700146OmahaRequestAction::OmahaRequestAction(PrefsInterface* prefs,
147 const OmahaRequestParams& params,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700148 OmahaEvent* event,
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700149 HttpFetcher* http_fetcher)
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700150 : prefs_(prefs),
151 params_(params),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700152 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700153 http_fetcher_(http_fetcher),
154 ping_active_days_(0),
155 ping_roll_call_days_(0) {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000156
Darin Petkov6a5b3222010-07-13 14:55:28 -0700157OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000158
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700159// Calculates the value to use for the ping days parameter.
160int OmahaRequestAction::CalculatePingDays(const string& key) {
161 int days = kNeverPinged;
162 int64_t last_ping = 0;
163 if (prefs_->GetInt64(key, &last_ping) && last_ping >= 0) {
164 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
165 if (days < 0) {
166 // If |days| is negative, then the system clock must have jumped
167 // back in time since the ping was sent. Mark the value so that
168 // it doesn't get sent to the server but we still update the
169 // last ping daystart preference. This way the next ping time
170 // will be correct, hopefully.
171 days = kPingTimeJump;
172 LOG(WARNING) <<
173 "System clock jumped back in time. Resetting ping daystarts.";
174 }
175 }
176 return days;
177}
178
179void OmahaRequestAction::InitPingDays() {
180 // We send pings only along with update checks, not with events.
181 if (IsEvent()) {
182 return;
183 }
184 // TODO(petkov): Figure a way to distinguish active use pings
185 // vs. roll call pings. Currently, the two pings are identical. A
186 // fix needs to change this code as well as UpdateLastPingDays.
187 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
188 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
189}
190
Darin Petkov6a5b3222010-07-13 14:55:28 -0700191void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000192 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700193 InitPingDays();
194 string request_post(FormatRequest(event_.get(),
195 params_,
196 ping_active_days_,
197 ping_roll_call_days_));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000198 http_fetcher_->SetPostData(request_post.data(), request_post.size());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700199 LOG(INFO) << "Posting an Omaha request to " << params_.update_url;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700200 LOG(INFO) << "Request: " << request_post;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700201 http_fetcher_->BeginTransfer(params_.update_url);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000202}
203
Darin Petkov6a5b3222010-07-13 14:55:28 -0700204void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000205 http_fetcher_->TerminateTransfer();
206}
207
208// We just store the response in the buffer. Once we've received all bytes,
209// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700210void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
211 const char* bytes,
212 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000213 response_buffer_.reserve(response_buffer_.size() + length);
214 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
215}
216
217namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000218// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
219// on the returned object.
220// This code is roughly based on the libxml tutorial at:
221// http://xmlsoft.org/tutorial/apd.html
222xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath,
223 const xmlChar* ns, const xmlChar* ns_url) {
224 xmlXPathObject* result = NULL;
225
226 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
227 xmlXPathNewContext(doc));
228 if (!context.get()) {
229 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
230 return NULL;
231 }
232 if (xmlXPathRegisterNs(context.get(), ns, ns_url) < 0) {
233 LOG(ERROR) << "xmlXPathRegisterNs() returned error";
234 return NULL;
235 }
236
237 result = xmlXPathEvalExpression(xpath, context.get());
238
239 if (result == NULL) {
240 LOG(ERROR) << "xmlXPathEvalExpression returned error";
241 return NULL;
242 }
243 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
244 LOG(INFO) << "xpath not found in doc";
245 xmlXPathFreeObject(result);
246 return NULL;
247 }
248 return result;
249}
250
251// Returns the string value of a named attribute on a node, or empty string
252// if no such node exists. If the attribute exists and has a value of
253// empty string, there's no way to distinguish that from the attribute
254// not existing.
255string XmlGetProperty(xmlNode* node, const char* name) {
256 if (!xmlHasProp(node, ConstXMLStr(name)))
257 return "";
258 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
259 xmlGetProp(node, ConstXMLStr(name)));
260 string ret(reinterpret_cast<const char *>(str.get()));
261 return ret;
262}
263
264// Parses a 64 bit base-10 int from a string and returns it. Returns 0
265// on error. If the string contains "0", that's indistinguishable from
266// error.
267off_t ParseInt(const string& str) {
268 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700269 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000270 if (rc < 1) {
271 // failure
272 return 0;
273 }
274 return ret;
275}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700276
277// Update the last ping day preferences based on the server daystart
278// response. Returns true on success, false otherwise.
279bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
280 static const char kNamespace[] = "x";
281 static const char kDaystartNodeXpath[] = "/x:gupdate/x:daystart";
282 static const char kNsUrl[] = "http://www.google.com/update2/response";
283
284 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
285 xpath_nodeset(GetNodeSet(doc,
286 ConstXMLStr(kDaystartNodeXpath),
287 ConstXMLStr(kNamespace),
288 ConstXMLStr(kNsUrl)));
289 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
290 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
291 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
292 xmlNode* daystart_node = nodeset->nodeTab[0];
293 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
294 ConstXMLStr("elapsed_seconds")));
295
296 int64_t elapsed_seconds = 0;
297 TEST_AND_RETURN_FALSE(StringToInt64(XmlGetProperty(daystart_node,
298 "elapsed_seconds"),
299 &elapsed_seconds));
300 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
301
302 // Remember the local time that matches the server's last midnight
303 // time.
304 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
305 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
306 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
307 return true;
308}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000309} // namespace {}
310
311// If the transfer was successful, this uses libxml2 to parse the response
312// and fill in the appropriate fields of the output object. Also, notifies
313// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700314void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
315 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000316 ScopedActionCompleter completer(processor_, this);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700317 LOG(INFO) << "Omaha request response: " << string(response_buffer_.begin(),
318 response_buffer_.end());
319
320 // Events are best effort transactions -- assume they always succeed.
321 if (IsEvent()) {
322 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Darin Petkovc1a8b422010-07-19 11:34:49 -0700323 completer.set_code(kActionCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700324 return;
325 }
326
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700327 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700328 LOG(ERROR) << "Omaha request network transfer failed.";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000329 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700330 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000331 if (!HasOutputPipe()) {
332 // Just set success to whether or not the http transfer succeeded,
333 // which must be true at this point in the code.
Darin Petkovc1a8b422010-07-19 11:34:49 -0700334 completer.set_code(kActionCodeSuccess);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000335 return;
336 }
337
338 // parse our response and fill the fields in the output object
339 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
340 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
341 if (!doc.get()) {
342 LOG(ERROR) << "Omaha response not valid XML";
343 return;
344 }
345
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700346 // If a ping was sent, update the last ping day preferences based on
347 // the server daystart response.
348 if (ShouldPing(ping_active_days_) ||
349 ShouldPing(ping_roll_call_days_) ||
350 ping_active_days_ == kPingTimeJump ||
351 ping_roll_call_days_ == kPingTimeJump) {
352 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), prefs_))
353 << "Failed to update the last ping day preferences!";
354 }
355
rspangler@google.com49fdf182009-10-10 00:57:34 +0000356 static const char* kNamespace("x");
357 static const char* kUpdatecheckNodeXpath("/x:gupdate/x:app/x:updatecheck");
358 static const char* kNsUrl("http://www.google.com/update2/response");
359
360 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
361 xpath_nodeset(GetNodeSet(doc.get(),
362 ConstXMLStr(kUpdatecheckNodeXpath),
363 ConstXMLStr(kNamespace),
364 ConstXMLStr(kNsUrl)));
365 if (!xpath_nodeset.get()) {
366 return;
367 }
368 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
369 CHECK(nodeset) << "XPath missing NodeSet";
370 CHECK_GE(nodeset->nodeNr, 1);
371
372 xmlNode* updatecheck_node = nodeset->nodeTab[0];
373 // get status
374 if (!xmlHasProp(updatecheck_node, ConstXMLStr("status"))) {
375 LOG(ERROR) << "Response missing status";
376 return;
377 }
378
379 const string status(XmlGetProperty(updatecheck_node, "status"));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700380 OmahaResponse output_object;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000381 if (status == "noupdate") {
382 LOG(INFO) << "No update.";
383 output_object.update_exists = false;
384 SetOutputObject(output_object);
Darin Petkovc1a8b422010-07-19 11:34:49 -0700385 completer.set_code(kActionCodeSuccess);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000386 return;
387 }
388
389 if (status != "ok") {
390 LOG(ERROR) << "Unknown status: " << status;
391 return;
392 }
393
394 // In best-effort fashion, fetch the rest of the expected attributes
395 // from the updatecheck node, then return the object
396 output_object.update_exists = true;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700397 completer.set_code(kActionCodeSuccess);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000398
399 output_object.display_version =
400 XmlGetProperty(updatecheck_node, "DisplayVersion");
401 output_object.codebase = XmlGetProperty(updatecheck_node, "codebase");
402 output_object.more_info_url = XmlGetProperty(updatecheck_node, "MoreInfo");
403 output_object.hash = XmlGetProperty(updatecheck_node, "hash");
404 output_object.size = ParseInt(XmlGetProperty(updatecheck_node, "size"));
405 output_object.needs_admin =
406 XmlGetProperty(updatecheck_node, "needsadmin") == "true";
407 output_object.prompt = XmlGetProperty(updatecheck_node, "Prompt") == "true";
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700408 output_object.is_delta =
409 XmlGetProperty(updatecheck_node, "IsDelta") == "true";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000410 SetOutputObject(output_object);
411 return;
412}
413
414}; // namespace chromeos_update_engine