blob: a4942a67bfed48c2609c7462b22bc41b17fbd67f [file] [log] [blame]
rspangler@google.com49fdf182009-10-10 00:57:34 +00001// Copyright (c) 2009 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "update_engine/update_check_action.h"
6#include <sstream>
7
8#include <libxml/parser.h>
9#include <libxml/xpath.h>
10#include <libxml/xpathInternals.h>
11
12#include "update_engine/action_pipe.h"
13
14using std::string;
15
16namespace chromeos_update_engine {
17
18const char* const UpdateCheckParams::kAppId(
19 "87efface-864d-49a5-9bb3-4b050a7c227a");
20const char* const UpdateCheckParams::kOsPlatform("Chrome OS");
21const char* const UpdateCheckParams::kOsVersion("Indy");
22
23namespace {
24
25const string kGupdateVersion("ChromeOSUpdateEngine-0.1.0.0");
26
27// This is handy for passing strings into libxml2
28#define ConstXMLStr(x) (reinterpret_cast<const xmlChar*>(x))
29
30// These are for scoped_ptr_malloc, which is like scoped_ptr, but allows
31// a custom free() function to be specified.
32class ScopedPtrXmlDocFree {
33 public:
34 inline void operator()(void* x) const {
35 xmlFreeDoc(reinterpret_cast<xmlDoc*>(x));
36 }
37};
38class ScopedPtrXmlFree {
39 public:
40 inline void operator()(void* x) const {
41 xmlFree(x);
42 }
43};
44class ScopedPtrXmlXPathObjectFree {
45 public:
46 inline void operator()(void* x) const {
47 xmlXPathFreeObject(reinterpret_cast<xmlXPathObject*>(x));
48 }
49};
50class ScopedPtrXmlXPathContextFree {
51 public:
52 inline void operator()(void* x) const {
53 xmlXPathFreeContext(reinterpret_cast<xmlXPathContext*>(x));
54 }
55};
56
57// Returns a properly formatted omaha request for an update check
58string FormatRequest(const UpdateCheckParams& params) {
59 return string("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
60 "<o:gupdate xmlns:o=\"http://www.google.com/update2/request\" "
61 "version=\"" + XmlEncode(kGupdateVersion) + "\" protocol=\"2.0\" "
62 "machineid=\"") + XmlEncode(params.machine_id) + "\" ismachine=\"1\" "
63 "userid=\"" + XmlEncode(params.user_id) + "\">\n"
64 " <o:os version=\"" + XmlEncode(params.os_version) + "\" platform=\"" +
65 XmlEncode(params.os_platform) + "\" sp=\"" +
66 XmlEncode(params.os_sp) + "\"></o:os>\n"
67 " <o:app appid=\"" + XmlEncode(params.app_id) + "\" version=\"" +
68 XmlEncode(params.app_version) + "\" "
69 "lang=\"" + XmlEncode(params.app_lang) + "\" track=\"" +
70 XmlEncode(params.app_track) + "\">\n"
71 " <o:ping active=\"0\"></o:ping>\n"
72 " <o:updatecheck></o:updatecheck>\n"
73 " </o:app>\n"
74 "</o:gupdate>\n";
75}
76} // namespace {}
77
78// Encodes XML entities in a given string with libxml2. input must be
79// UTF-8 formatted. Output will be UTF-8 formatted.
80string XmlEncode(const string& input) {
81// // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
82// // cpu, considering creating one and caching it.
83// scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
84// xmlNewDoc(ConstXMLStr("1.0")));
85// if (!xml_doc.get()) {
86// LOG(ERROR) << "Unable to create xmlDoc";
87// return "";
88// }
89 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
90 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
91 return string(reinterpret_cast<const char *>(str.get()));
92}
93
94UpdateCheckAction::UpdateCheckAction(const UpdateCheckParams& params,
95 HttpFetcher* http_fetcher)
96 : params_(params), http_fetcher_(http_fetcher) {}
97
98UpdateCheckAction::~UpdateCheckAction() {}
99
100void UpdateCheckAction::PerformAction() {
101 http_fetcher_->set_delegate(this);
102 string request_post(FormatRequest(params_));
103 http_fetcher_->SetPostData(request_post.data(), request_post.size());
104 http_fetcher_->BeginTransfer("https://tools.google.com/service/update2");
105}
106
107void UpdateCheckAction::TerminateProcessing() {
108 http_fetcher_->TerminateTransfer();
109}
110
111// We just store the response in the buffer. Once we've received all bytes,
112// we'll look in the buffer and decide what to do.
113void UpdateCheckAction::ReceivedBytes(HttpFetcher *fetcher,
114 const char* bytes,
115 int length) {
116 response_buffer_.reserve(response_buffer_.size() + length);
117 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
118}
119
120namespace {
121// A little object to call ActionComplete on the ActionProcessor when
122// it's destructed.
123class ScopedActionCompleter {
124 public:
125 explicit ScopedActionCompleter(ActionProcessor* processor,
126 AbstractAction* action)
127 : processor_(processor), action_(action), success_(false) {}
128 ~ScopedActionCompleter() {
129 processor_->ActionComplete(action_, success_);
130 }
131 void set_success(bool success) {
132 success_ = success;
133 }
134 private:
135 ActionProcessor* processor_;
136 AbstractAction* action_;
137 bool success_;
138 DISALLOW_COPY_AND_ASSIGN(ScopedActionCompleter);
139};
140
141// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
142// on the returned object.
143// This code is roughly based on the libxml tutorial at:
144// http://xmlsoft.org/tutorial/apd.html
145xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath,
146 const xmlChar* ns, const xmlChar* ns_url) {
147 xmlXPathObject* result = NULL;
148
149 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
150 xmlXPathNewContext(doc));
151 if (!context.get()) {
152 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
153 return NULL;
154 }
155 if (xmlXPathRegisterNs(context.get(), ns, ns_url) < 0) {
156 LOG(ERROR) << "xmlXPathRegisterNs() returned error";
157 return NULL;
158 }
159
160 result = xmlXPathEvalExpression(xpath, context.get());
161
162 if (result == NULL) {
163 LOG(ERROR) << "xmlXPathEvalExpression returned error";
164 return NULL;
165 }
166 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
167 LOG(INFO) << "xpath not found in doc";
168 xmlXPathFreeObject(result);
169 return NULL;
170 }
171 return result;
172}
173
174// Returns the string value of a named attribute on a node, or empty string
175// if no such node exists. If the attribute exists and has a value of
176// empty string, there's no way to distinguish that from the attribute
177// not existing.
178string XmlGetProperty(xmlNode* node, const char* name) {
179 if (!xmlHasProp(node, ConstXMLStr(name)))
180 return "";
181 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
182 xmlGetProp(node, ConstXMLStr(name)));
183 string ret(reinterpret_cast<const char *>(str.get()));
184 return ret;
185}
186
187// Parses a 64 bit base-10 int from a string and returns it. Returns 0
188// on error. If the string contains "0", that's indistinguishable from
189// error.
190off_t ParseInt(const string& str) {
191 off_t ret = 0;
192
193 int rc = sscanf(str.c_str(), "%lld", &ret);
194 if (rc < 1) {
195 // failure
196 return 0;
197 }
198 return ret;
199}
200} // namespace {}
201
202// If the transfer was successful, this uses libxml2 to parse the response
203// and fill in the appropriate fields of the output object. Also, notifies
204// the processor that we're done.
205void UpdateCheckAction::TransferComplete(HttpFetcher *fetcher,
206 bool successful) {
207 ScopedActionCompleter completer(processor_, this);
208 if (!successful)
209 return;
210 if (!HasOutputPipe()) {
211 // Just set success to whether or not the http transfer succeeded,
212 // which must be true at this point in the code.
213 completer.set_success(true);
214 return;
215 }
216
217 // parse our response and fill the fields in the output object
218 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
219 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
220 if (!doc.get()) {
221 LOG(ERROR) << "Omaha response not valid XML";
222 return;
223 }
224
225 static const char* kNamespace("x");
226 static const char* kUpdatecheckNodeXpath("/x:gupdate/x:app/x:updatecheck");
227 static const char* kNsUrl("http://www.google.com/update2/response");
228
229 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
230 xpath_nodeset(GetNodeSet(doc.get(),
231 ConstXMLStr(kUpdatecheckNodeXpath),
232 ConstXMLStr(kNamespace),
233 ConstXMLStr(kNsUrl)));
234 if (!xpath_nodeset.get()) {
235 return;
236 }
237 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
238 CHECK(nodeset) << "XPath missing NodeSet";
239 CHECK_GE(nodeset->nodeNr, 1);
240
241 xmlNode* updatecheck_node = nodeset->nodeTab[0];
242 // get status
243 if (!xmlHasProp(updatecheck_node, ConstXMLStr("status"))) {
244 LOG(ERROR) << "Response missing status";
245 return;
246 }
247
248 const string status(XmlGetProperty(updatecheck_node, "status"));
249 UpdateCheckResponse output_object;
250 if (status == "noupdate") {
251 LOG(INFO) << "No update.";
252 output_object.update_exists = false;
253 SetOutputObject(output_object);
254 completer.set_success(true);
255 return;
256 }
257
258 if (status != "ok") {
259 LOG(ERROR) << "Unknown status: " << status;
260 return;
261 }
262
263 // In best-effort fashion, fetch the rest of the expected attributes
264 // from the updatecheck node, then return the object
265 output_object.update_exists = true;
266 completer.set_success(true);
267
268 output_object.display_version =
269 XmlGetProperty(updatecheck_node, "DisplayVersion");
270 output_object.codebase = XmlGetProperty(updatecheck_node, "codebase");
271 output_object.more_info_url = XmlGetProperty(updatecheck_node, "MoreInfo");
272 output_object.hash = XmlGetProperty(updatecheck_node, "hash");
273 output_object.size = ParseInt(XmlGetProperty(updatecheck_node, "size"));
274 output_object.needs_admin =
275 XmlGetProperty(updatecheck_node, "needsadmin") == "true";
276 output_object.prompt = XmlGetProperty(updatecheck_node, "Prompt") == "true";
277 SetOutputObject(output_object);
278 return;
279}
280
281}; // namespace chromeos_update_engine