blob: 7eca9e07e434ce0d837958abc6d9812a2e5600b1 [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=\"" +
Andrew de los Reyes3f0303a2010-07-15 22:35:35 -0700121 XmlEncode(params.os_board) + "\" delta_okay=\"" +
122 (params.delta_okay ? "true" : "false") + "\">\n" + body +
rspangler@google.com49fdf182009-10-10 00:57:34 +0000123 " </o:app>\n"
124 "</o:gupdate>\n";
125}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700126
rspangler@google.com49fdf182009-10-10 00:57:34 +0000127} // namespace {}
128
129// Encodes XML entities in a given string with libxml2. input must be
130// UTF-8 formatted. Output will be UTF-8 formatted.
131string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700132 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
133 // // cpu, considering creating one and caching it.
134 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
135 // xmlNewDoc(ConstXMLStr("1.0")));
136 // if (!xml_doc.get()) {
137 // LOG(ERROR) << "Unable to create xmlDoc";
138 // return "";
139 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000140 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
141 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
142 return string(reinterpret_cast<const char *>(str.get()));
143}
144
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700145OmahaRequestAction::OmahaRequestAction(PrefsInterface* prefs,
146 const OmahaRequestParams& params,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700147 OmahaEvent* event,
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700148 HttpFetcher* http_fetcher)
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700149 : prefs_(prefs),
150 params_(params),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700151 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700152 http_fetcher_(http_fetcher),
153 ping_active_days_(0),
154 ping_roll_call_days_(0) {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000155
Darin Petkov6a5b3222010-07-13 14:55:28 -0700156OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000157
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700158// Calculates the value to use for the ping days parameter.
159int OmahaRequestAction::CalculatePingDays(const string& key) {
160 int days = kNeverPinged;
161 int64_t last_ping = 0;
162 if (prefs_->GetInt64(key, &last_ping) && last_ping >= 0) {
163 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
164 if (days < 0) {
165 // If |days| is negative, then the system clock must have jumped
166 // back in time since the ping was sent. Mark the value so that
167 // it doesn't get sent to the server but we still update the
168 // last ping daystart preference. This way the next ping time
169 // will be correct, hopefully.
170 days = kPingTimeJump;
171 LOG(WARNING) <<
172 "System clock jumped back in time. Resetting ping daystarts.";
173 }
174 }
175 return days;
176}
177
178void OmahaRequestAction::InitPingDays() {
179 // We send pings only along with update checks, not with events.
180 if (IsEvent()) {
181 return;
182 }
183 // TODO(petkov): Figure a way to distinguish active use pings
184 // vs. roll call pings. Currently, the two pings are identical. A
185 // fix needs to change this code as well as UpdateLastPingDays.
186 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
187 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
188}
189
Darin Petkov6a5b3222010-07-13 14:55:28 -0700190void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000191 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700192 InitPingDays();
193 string request_post(FormatRequest(event_.get(),
194 params_,
195 ping_active_days_,
196 ping_roll_call_days_));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000197 http_fetcher_->SetPostData(request_post.data(), request_post.size());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700198 LOG(INFO) << "Posting an Omaha request to " << params_.update_url;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700199 LOG(INFO) << "Request: " << request_post;
Andrew de los Reyesf9714432010-05-04 10:21:23 -0700200 http_fetcher_->BeginTransfer(params_.update_url);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000201}
202
Darin Petkov6a5b3222010-07-13 14:55:28 -0700203void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000204 http_fetcher_->TerminateTransfer();
205}
206
207// We just store the response in the buffer. Once we've received all bytes,
208// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700209void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
210 const char* bytes,
211 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000212 response_buffer_.reserve(response_buffer_.size() + length);
213 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
214}
215
216namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000217// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
218// on the returned object.
219// This code is roughly based on the libxml tutorial at:
220// http://xmlsoft.org/tutorial/apd.html
221xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath,
222 const xmlChar* ns, const xmlChar* ns_url) {
223 xmlXPathObject* result = NULL;
224
225 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
226 xmlXPathNewContext(doc));
227 if (!context.get()) {
228 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
229 return NULL;
230 }
231 if (xmlXPathRegisterNs(context.get(), ns, ns_url) < 0) {
232 LOG(ERROR) << "xmlXPathRegisterNs() returned error";
233 return NULL;
234 }
235
236 result = xmlXPathEvalExpression(xpath, context.get());
237
238 if (result == NULL) {
239 LOG(ERROR) << "xmlXPathEvalExpression returned error";
240 return NULL;
241 }
242 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
243 LOG(INFO) << "xpath not found in doc";
244 xmlXPathFreeObject(result);
245 return NULL;
246 }
247 return result;
248}
249
250// Returns the string value of a named attribute on a node, or empty string
251// if no such node exists. If the attribute exists and has a value of
252// empty string, there's no way to distinguish that from the attribute
253// not existing.
254string XmlGetProperty(xmlNode* node, const char* name) {
255 if (!xmlHasProp(node, ConstXMLStr(name)))
256 return "";
257 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
258 xmlGetProp(node, ConstXMLStr(name)));
259 string ret(reinterpret_cast<const char *>(str.get()));
260 return ret;
261}
262
263// Parses a 64 bit base-10 int from a string and returns it. Returns 0
264// on error. If the string contains "0", that's indistinguishable from
265// error.
266off_t ParseInt(const string& str) {
267 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700268 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000269 if (rc < 1) {
270 // failure
271 return 0;
272 }
273 return ret;
274}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700275
276// Update the last ping day preferences based on the server daystart
277// response. Returns true on success, false otherwise.
278bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
279 static const char kNamespace[] = "x";
280 static const char kDaystartNodeXpath[] = "/x:gupdate/x:daystart";
281 static const char kNsUrl[] = "http://www.google.com/update2/response";
282
283 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
284 xpath_nodeset(GetNodeSet(doc,
285 ConstXMLStr(kDaystartNodeXpath),
286 ConstXMLStr(kNamespace),
287 ConstXMLStr(kNsUrl)));
288 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
289 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
290 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
291 xmlNode* daystart_node = nodeset->nodeTab[0];
292 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
293 ConstXMLStr("elapsed_seconds")));
294
295 int64_t elapsed_seconds = 0;
296 TEST_AND_RETURN_FALSE(StringToInt64(XmlGetProperty(daystart_node,
297 "elapsed_seconds"),
298 &elapsed_seconds));
299 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
300
301 // Remember the local time that matches the server's last midnight
302 // time.
303 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
304 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
305 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
306 return true;
307}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000308} // namespace {}
309
310// If the transfer was successful, this uses libxml2 to parse the response
311// and fill in the appropriate fields of the output object. Also, notifies
312// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700313void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
314 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000315 ScopedActionCompleter completer(processor_, this);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700316 LOG(INFO) << "Omaha request response: " << string(response_buffer_.begin(),
317 response_buffer_.end());
318
319 // Events are best effort transactions -- assume they always succeed.
320 if (IsEvent()) {
321 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Darin Petkovc1a8b422010-07-19 11:34:49 -0700322 completer.set_code(kActionCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700323 return;
324 }
325
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700326 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700327 LOG(ERROR) << "Omaha request network transfer failed.";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000328 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700329 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000330 if (!HasOutputPipe()) {
331 // Just set success to whether or not the http transfer succeeded,
332 // which must be true at this point in the code.
Darin Petkovc1a8b422010-07-19 11:34:49 -0700333 completer.set_code(kActionCodeSuccess);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000334 return;
335 }
336
337 // parse our response and fill the fields in the output object
338 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
339 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
340 if (!doc.get()) {
341 LOG(ERROR) << "Omaha response not valid XML";
342 return;
343 }
344
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700345 // If a ping was sent, update the last ping day preferences based on
346 // the server daystart response.
347 if (ShouldPing(ping_active_days_) ||
348 ShouldPing(ping_roll_call_days_) ||
349 ping_active_days_ == kPingTimeJump ||
350 ping_roll_call_days_ == kPingTimeJump) {
351 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), prefs_))
352 << "Failed to update the last ping day preferences!";
353 }
354
rspangler@google.com49fdf182009-10-10 00:57:34 +0000355 static const char* kNamespace("x");
356 static const char* kUpdatecheckNodeXpath("/x:gupdate/x:app/x:updatecheck");
357 static const char* kNsUrl("http://www.google.com/update2/response");
358
359 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
360 xpath_nodeset(GetNodeSet(doc.get(),
361 ConstXMLStr(kUpdatecheckNodeXpath),
362 ConstXMLStr(kNamespace),
363 ConstXMLStr(kNsUrl)));
364 if (!xpath_nodeset.get()) {
365 return;
366 }
367 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
368 CHECK(nodeset) << "XPath missing NodeSet";
369 CHECK_GE(nodeset->nodeNr, 1);
370
371 xmlNode* updatecheck_node = nodeset->nodeTab[0];
372 // get status
373 if (!xmlHasProp(updatecheck_node, ConstXMLStr("status"))) {
374 LOG(ERROR) << "Response missing status";
375 return;
376 }
377
378 const string status(XmlGetProperty(updatecheck_node, "status"));
Darin Petkov6a5b3222010-07-13 14:55:28 -0700379 OmahaResponse output_object;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000380 if (status == "noupdate") {
381 LOG(INFO) << "No update.";
382 output_object.update_exists = false;
383 SetOutputObject(output_object);
Darin Petkovc1a8b422010-07-19 11:34:49 -0700384 completer.set_code(kActionCodeSuccess);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000385 return;
386 }
387
388 if (status != "ok") {
389 LOG(ERROR) << "Unknown status: " << status;
390 return;
391 }
392
393 // In best-effort fashion, fetch the rest of the expected attributes
394 // from the updatecheck node, then return the object
395 output_object.update_exists = true;
Darin Petkovc1a8b422010-07-19 11:34:49 -0700396 completer.set_code(kActionCodeSuccess);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000397
398 output_object.display_version =
399 XmlGetProperty(updatecheck_node, "DisplayVersion");
400 output_object.codebase = XmlGetProperty(updatecheck_node, "codebase");
401 output_object.more_info_url = XmlGetProperty(updatecheck_node, "MoreInfo");
402 output_object.hash = XmlGetProperty(updatecheck_node, "hash");
403 output_object.size = ParseInt(XmlGetProperty(updatecheck_node, "size"));
404 output_object.needs_admin =
405 XmlGetProperty(updatecheck_node, "needsadmin") == "true";
406 output_object.prompt = XmlGetProperty(updatecheck_node, "Prompt") == "true";
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700407 output_object.is_delta =
408 XmlGetProperty(updatecheck_node, "IsDelta") == "true";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000409 SetOutputObject(output_object);
410 return;
411}
412
413}; // namespace chromeos_update_engine