blob: e4b8a7b6fcedfad545bdec950125775fc1c3be50 [file] [log] [blame]
Mike Frysinger8155d082012-04-06 15:23:18 -04001// Copyright (c) 2012 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
David Zeuthene8ed8632014-07-24 13:38:10 -04009#include <map>
rspangler@google.com49fdf182009-10-10 00:57:34 +000010#include <sstream>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070011#include <string>
David Zeuthene8ed8632014-07-24 13:38:10 -040012#include <vector>
rspangler@google.com49fdf182009-10-10 00:57:34 +000013
David Zeuthen8f191b22013-08-06 12:27:50 -070014#include <base/bind.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070015#include <base/logging.h>
16#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070017#include <base/strings/string_number_conversions.h>
18#include <base/strings/string_util.h>
19#include <base/strings/stringprintf.h>
20#include <base/time/time.h>
David Zeuthene8ed8632014-07-24 13:38:10 -040021#include <expat.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000022
23#include "update_engine/action_pipe.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070024#include "update_engine/constants.h"
J. Richard Barnette056b0ab2013-10-29 15:24:56 -070025#include "update_engine/hardware_interface.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070026#include "update_engine/omaha_hash_calculator.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070027#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070028#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080029#include "update_engine/payload_state_interface.h"
Darin Petkov1cbd78f2010-07-29 12:38:34 -070030#include "update_engine/prefs_interface.h"
Chris Sosa77f79e82014-06-02 18:16:24 -070031#include "update_engine/real_dbus_wrapper.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000032#include "update_engine/utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000033
Darin Petkov1cbd78f2010-07-29 12:38:34 -070034using base::Time;
35using base::TimeDelta;
David Zeuthene8ed8632014-07-24 13:38:10 -040036using std::map;
rspangler@google.com49fdf182009-10-10 00:57:34 +000037using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040038using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000039
40namespace chromeos_update_engine {
41
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080042// List of custom pair tags that we interpret in the Omaha Response:
43static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080044static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070045static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080046// Deprecated: "IsDelta"
47static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080048static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
49static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
50// Deprecated: "ManifestSignatureRsa"
51// Deprecated: "ManifestSize"
52static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
53static const char* kTagMetadataSize = "MetadataSize";
54static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070055// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080056static const char* kTagPrompt = "Prompt";
57static const char* kTagSha256 = "sha256";
David Zeuthen8f191b22013-08-06 12:27:50 -070058static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
59static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
David Zeuthene7f89172013-10-31 10:21:04 -070060static const char* kTagPublicKeyRsa = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080061
rspangler@google.com49fdf182009-10-10 00:57:34 +000062namespace {
63
Alex Vakulenkod2779df2014-06-16 13:19:00 -070064static const char* const kGupdateVersion = "ChromeOSUpdateEngine-0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +000065
Darin Petkov1cbd78f2010-07-29 12:38:34 -070066// Returns true if |ping_days| has a value that needs to be sent,
67// false otherwise.
68bool ShouldPing(int ping_days) {
69 return ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged;
70}
71
72// Returns an XML ping element attribute assignment with attribute
73// |name| and value |ping_days| if |ping_days| has a value that needs
74// to be sent, or an empty string otherwise.
75string GetPingAttribute(const string& name, int ping_days) {
76 if (ShouldPing(ping_days)) {
Alex Vakulenko75039d72014-03-25 12:36:28 -070077 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -070078 }
79 return "";
80}
81
82// Returns an XML ping element if any of the elapsed days need to be
83// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -070084string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -070085 string ping_active = GetPingAttribute("a", ping_active_days);
86 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
87 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -070088 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Darin Petkov1cbd78f2010-07-29 12:38:34 -070089 ping_active.c_str(),
90 ping_roll_call.c_str());
91 }
92 return "";
93}
94
Jay Srinivasanae4697c2013-03-18 17:08:08 -070095// Returns an XML that goes into the body of the <app> element of the Omaha
96// request based on the given parameters.
97string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -070098 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -070099 bool ping_only,
100 int ping_active_days,
101 int ping_roll_call_days,
102 PrefsInterface* prefs) {
103 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700104 if (event == nullptr) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700105 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700106 if (!ping_only) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700107 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700108 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700109 "></updatecheck>\n",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700110 XmlEncode(params->target_version_prefix()).c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700111
Darin Petkov265f2902011-05-09 15:17:40 -0700112 // If this is the first update check after a reboot following a previous
113 // update, generate an event containing the previous version number. If
114 // the previous version preference file doesn't exist the event is still
115 // generated with a previous version of 0.0.0.0 -- this is relevant for
116 // older clients or new installs. The previous version event is not sent
117 // for ping-only requests because they come before the client has
118 // rebooted.
119 string prev_version;
120 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
121 prev_version = "0.0.0.0";
122 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700123
Alex Vakulenko75039d72014-03-25 12:36:28 -0700124 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700125 " <event eventtype=\"%d\" eventresult=\"%d\" "
126 "previousversion=\"%s\"></event>\n",
127 OmahaEvent::kTypeUpdateComplete,
128 OmahaEvent::kResultSuccessReboot,
129 XmlEncode(prev_version).c_str());
130 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
131 << "Unable to reset the previous version.";
Darin Petkov95508da2011-01-05 12:42:29 -0800132 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700133 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800134 // The error code is an optional attribute so append it only if the result
135 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700136 string error_code;
137 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700138 error_code = base::StringPrintf(" errorcode=\"%d\"",
139 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700140 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700141 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700142 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700143 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700144 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700145
146 return app_body;
147}
148
149// Returns an XML that corresponds to the entire <app> node of the Omaha
150// request based on the given parameters.
151string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700152 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700153 bool ping_only,
154 int ping_active_days,
155 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800156 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700157 SystemState* system_state) {
158 string app_body = GetAppBody(event, params, ping_only, ping_active_days,
159 ping_roll_call_days, system_state->prefs());
160 string app_versions;
161
162 // If we are upgrading to a more stable channel and we are allowed to do
163 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
164 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700165 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700166 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
167 << "on downgrading to the version in the more stable channel";
168 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700169 XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700170 } else {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700171 app_versions = "version=\"" + XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700172 }
173
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700174 string download_channel = params->download_channel();
175 string app_channels = "track=\"" + XmlEncode(download_channel) + "\" ";
176 if (params->current_channel() != download_channel)
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700177 app_channels +=
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700178 "from_track=\"" + XmlEncode(params->current_channel()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700179
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700180 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700181
David Zeuthen639aa362014-02-03 16:23:44 -0800182 // If install_date_days is not set (e.g. its value is -1 ), don't
183 // include the attribute.
184 string install_date_in_days_str = "";
185 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700186 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
187 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800188 }
189
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700190 string app_xml =
Jay Srinivasandb0acdf2013-04-02 14:47:45 -0700191 " <app appid=\"" + XmlEncode(params->GetAppId()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700192 app_versions +
193 app_channels +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700194 "lang=\"" + XmlEncode(params->app_lang()) + "\" " +
195 "board=\"" + XmlEncode(params->os_board()) + "\" " +
196 "hardware_class=\"" + XmlEncode(params->hwid()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700197 "delta_okay=\"" + delta_okay_str + "\" "
Chris Sosac1972482013-04-30 22:31:10 -0700198 "fw_version=\"" + XmlEncode(params->fw_version()) + "\" " +
199 "ec_version=\"" + XmlEncode(params->ec_version()) + "\" " +
David Zeuthen639aa362014-02-03 16:23:44 -0800200 install_date_in_days_str +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700201 ">\n" +
202 app_body +
203 " </app>\n";
204
205 return app_xml;
206}
207
208// Returns an XML that corresponds to the entire <os> node of the Omaha
209// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700210string GetOsXml(OmahaRequestParams* params) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700211 string os_xml =
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700212 " <os version=\"" + XmlEncode(params->os_version()) + "\" " +
213 "platform=\"" + XmlEncode(params->os_platform()) + "\" " +
214 "sp=\"" + XmlEncode(params->os_sp()) + "\">"
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700215 "</os>\n";
216 return os_xml;
217}
218
219// Returns an XML that corresponds to the entire Omaha request based on the
220// given parameters.
221string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700222 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700223 bool ping_only,
224 int ping_active_days,
225 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800226 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700227 SystemState* system_state) {
228 string os_xml = GetOsXml(params);
229 string app_xml = GetAppXml(event, params, ping_only, ping_active_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800230 ping_roll_call_days, install_date_in_days,
231 system_state);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700232
Alex Vakulenko75039d72014-03-25 12:36:28 -0700233 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700234 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700235
236 string request_xml =
237 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700238 "<request protocol=\"3.0\" "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700239 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
240 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" " +
241 install_source +
242 "ismachine=\"1\">\n" +
243 os_xml +
244 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700245 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700246
247 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000248}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700249
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700250} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000251
David Zeuthene8ed8632014-07-24 13:38:10 -0400252// Struct used for holding data obtained when parsing the XML.
253struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400254 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
255
256 // Pointer to the expat XML_Parser object.
257 XML_Parser xml_parser;
258
David Zeuthene8ed8632014-07-24 13:38:10 -0400259 // This is the state of the parser as it's processing the XML.
260 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400261 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400262 string current_path;
263
264 // These are the values extracted from the XML.
265 string updatecheck_status;
266 string updatecheck_poll_interval;
267 string daystart_elapsed_days;
268 string daystart_elapsed_seconds;
269 vector<string> url_codebase;
270 string package_name;
271 string package_size;
272 string manifest_version;
273 map<string, string> action_postinstall_attrs;
274};
275
276namespace {
277
278// Callback function invoked by expat.
279void ParserHandlerStart(void* user_data, const XML_Char* element,
280 const XML_Char** attr) {
281 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
282
283 if (data->failed)
284 return;
285
286 data->current_path += string("/") + element;
287
288 map<string, string> attrs;
289 if (attr != nullptr) {
290 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
291 string key = attr[n];
292 string value = attr[n + 1];
293 attrs[key] = value;
294 }
295 }
296
297 if (data->current_path == "/response/app/updatecheck") {
298 // There is only supposed to be a single <updatecheck> element.
299 data->updatecheck_status = attrs["status"];
300 data->updatecheck_poll_interval = attrs["PollInterval"];
301 } else if (data->current_path == "/response/daystart") {
302 // Get the install-date.
303 data->daystart_elapsed_days = attrs["elapsed_days"];
304 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
305 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
306 // Look at all <url> elements.
307 data->url_codebase.push_back(attrs["codebase"]);
308 } else if (data->package_name.empty() && data->current_path ==
309 "/response/app/updatecheck/manifest/packages/package") {
310 // Only look at the first <package>.
311 data->package_name = attrs["name"];
312 data->package_size = attrs["size"];
313 } else if (data->current_path == "/response/app/updatecheck/manifest") {
314 // Get the version.
315 data->manifest_version = attrs[kTagVersion];
316 } else if (data->current_path ==
317 "/response/app/updatecheck/manifest/actions/action") {
318 // We only care about the postinstall action.
319 if (attrs["event"] == "postinstall") {
320 data->action_postinstall_attrs = attrs;
321 }
322 }
323}
324
325// Callback function invoked by expat.
326void ParserHandlerEnd(void* user_data, const XML_Char* element) {
327 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
328 if (data->failed)
329 return;
330
331 const string path_suffix = string("/") + element;
332
333 if (!EndsWith(data->current_path, path_suffix, true)) {
334 LOG(ERROR) << "Unexpected end element '" << element
335 << "' with current_path='" << data->current_path << "'";
336 data->failed = true;
337 return;
338 }
339 data->current_path.resize(data->current_path.size() - path_suffix.size());
340}
341
David Zeuthenf3e28012014-08-26 18:23:52 -0400342// Callback function invoked by expat.
343//
344// This is called for entity declarations. Since Omaha is guaranteed
345// to never return any XML with entities our course of action is to
346// just stop parsing. This avoids potential resource exhaustion
347// problems AKA the "billion laughs". CVE-2013-0340.
348void ParserHandlerEntityDecl(void *user_data,
349 const XML_Char *entity_name,
350 int is_parameter_entity,
351 const XML_Char *value,
352 int value_length,
353 const XML_Char *base,
354 const XML_Char *system_id,
355 const XML_Char *public_id,
356 const XML_Char *notation_name) {
357 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
358
359 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
360 data->failed = true;
361 data->entity_decl = true;
362 XML_StopParser(data->xml_parser, false);
363}
364
David Zeuthene8ed8632014-07-24 13:38:10 -0400365} // namespace
366
367// Escapes text so it can be included as character data and attribute
368// values. The |input| string must be valid UTF-8.
rspangler@google.com49fdf182009-10-10 00:57:34 +0000369string XmlEncode(const string& input) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400370 gchar* escaped = g_markup_escape_text(input.c_str(), input.size());
371 string ret = string(escaped);
372 g_free(escaped);
373 return ret;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000374}
375
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800376OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700377 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700378 HttpFetcher* http_fetcher,
379 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800380 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700381 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700382 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700383 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700384 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700385 ping_roll_call_days_(0) {
386 params_ = system_state->request_params();
387}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000388
Darin Petkov6a5b3222010-07-13 14:55:28 -0700389OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000390
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700391// Calculates the value to use for the ping days parameter.
392int OmahaRequestAction::CalculatePingDays(const string& key) {
393 int days = kNeverPinged;
394 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800395 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700396 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
397 if (days < 0) {
398 // If |days| is negative, then the system clock must have jumped
399 // back in time since the ping was sent. Mark the value so that
400 // it doesn't get sent to the server but we still update the
401 // last ping daystart preference. This way the next ping time
402 // will be correct, hopefully.
403 days = kPingTimeJump;
404 LOG(WARNING) <<
405 "System clock jumped back in time. Resetting ping daystarts.";
406 }
407 }
408 return days;
409}
410
411void OmahaRequestAction::InitPingDays() {
412 // We send pings only along with update checks, not with events.
413 if (IsEvent()) {
414 return;
415 }
416 // TODO(petkov): Figure a way to distinguish active use pings
417 // vs. roll call pings. Currently, the two pings are identical. A
418 // fix needs to change this code as well as UpdateLastPingDays.
419 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
420 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
421}
422
David Zeuthen639aa362014-02-03 16:23:44 -0800423// static
424int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
425 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700426 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800427 return -1;
428
429 // If we have the value stored on disk, just return it.
430 int64_t stored_value;
431 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
432 // Convert and sanity-check.
433 int install_date_days = static_cast<int>(stored_value);
434 if (install_date_days >= 0)
435 return install_date_days;
436 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
437 << install_date_days << " looks suspicious.";
438 prefs->Delete(kPrefsInstallDateDays);
439 }
440
441 // Otherwise, if OOBE is not complete then do nothing and wait for
442 // ParseResponse() to call ParseInstallDate() and then
443 // PersistInstallDate() to set the kPrefsInstallDateDays state
444 // variable. Once that is done, we'll then report back in future
445 // Omaha requests. This works exactly because OOBE triggers an
446 // update check.
447 //
448 // However, if OOBE is complete and the kPrefsInstallDateDays state
449 // variable is not set, there are two possibilities
450 //
451 // 1. The update check in OOBE failed so we never got a response
452 // from Omaha (no network etc.); or
453 //
454 // 2. OOBE was done on an older version that didn't write to the
455 // kPrefsInstallDateDays state variable.
456 //
457 // In both cases, we approximate the install date by simply
458 // inspecting the timestamp of when OOBE happened.
459
460 Time time_of_oobe;
Alex Deymobccbc382014-04-03 13:38:55 -0700461 if (!system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800462 LOG(INFO) << "Not generating Omaha InstallData as we have "
463 << "no prefs file and OOBE is not complete.";
464 return -1;
465 }
466
467 int num_days;
468 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
469 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
470 << "as its value '" << utils::ToString(time_of_oobe)
471 << "' looks suspicious.";
472 return -1;
473 }
474
475 // Persist this to disk, for future use.
476 if (!OmahaRequestAction::PersistInstallDate(system_state,
477 num_days,
478 kProvisionedFromOOBEMarker))
479 return -1;
480
481 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
482 << num_days << " days";
483
484 return num_days;
485}
486
Darin Petkov6a5b3222010-07-13 14:55:28 -0700487void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000488 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700489 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700490 if (ping_only_ &&
491 !ShouldPing(ping_active_days_) &&
492 !ShouldPing(ping_roll_call_days_)) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700493 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700494 return;
495 }
David Zeuthen639aa362014-02-03 16:23:44 -0800496
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700497 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700498 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700499 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700500 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800501 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800502 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700503 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700504
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800505 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
506 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700507 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700508 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700509 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000510}
511
Darin Petkov6a5b3222010-07-13 14:55:28 -0700512void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000513 http_fetcher_->TerminateTransfer();
514}
515
516// We just store the response in the buffer. Once we've received all bytes,
517// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700518void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
519 const char* bytes,
520 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000521 response_buffer_.reserve(response_buffer_.size() + length);
522 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
523}
524
525namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000526
527// Parses a 64 bit base-10 int from a string and returns it. Returns 0
528// on error. If the string contains "0", that's indistinguishable from
529// error.
530off_t ParseInt(const string& str) {
531 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700532 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000533 if (rc < 1) {
534 // failure
535 return 0;
536 }
537 return ret;
538}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700539
David Zeuthene8ed8632014-07-24 13:38:10 -0400540// Parses |str| and returns |true| if, and only if, its value is "true".
541bool ParseBool(const string& str) {
542 return str == "true";
543}
544
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700545// Update the last ping day preferences based on the server daystart
546// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400547bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700548 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400549 TEST_AND_RETURN_FALSE(
550 base::StringToInt64(parser_data->daystart_elapsed_seconds,
551 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700552 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
553
554 // Remember the local time that matches the server's last midnight
555 // time.
556 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
557 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
558 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
559 return true;
560}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700561} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000562
David Zeuthene8ed8632014-07-24 13:38:10 -0400563bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700564 OmahaResponse* output_object,
565 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400566 if (parser_data->updatecheck_status.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700567 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700568 return false;
569 }
570
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800571 // chromium-os:37289: The PollInterval is not supported by Omaha server
572 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700573 // slow down the request rate from the server-side. Note that the PollInterval
574 // is not persisted, so it has to be sent by the server on every response to
575 // guarantee that the scheduler uses this value (otherwise, if the device got
576 // rebooted after the last server-indicated value, it'll revert to the default
577 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
578 // based on the assumption that we perform an update check every hour so that
579 // the max value of 8 will roughly be equivalent to one work day. If we decide
580 // to use PollInterval permanently, we should update the
581 // max_update_checks_allowed to take PollInterval into account. Note: The
582 // parsing for PollInterval happens even before parsing of the status because
583 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400584 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700585 &output_object->poll_interval);
586
David Zeuthen639aa362014-02-03 16:23:44 -0800587 // Check for the "elapsed_days" attribute in the "daystart"
588 // element. This is the number of days since Jan 1 2007, 0:00
589 // PST. If we don't have a persisted value of the Omaha InstallDate,
590 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400591 if (ParseInstallDate(parser_data, output_object) &&
592 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800593 // Since output_object->install_date_days is never negative, the
594 // elapsed_days -> install-date calculation is reduced to simply
595 // rounding down to the nearest number divisible by 7.
596 int remainder = output_object->install_date_days % 7;
597 int install_date_days_rounded =
598 output_object->install_date_days - remainder;
599 if (PersistInstallDate(system_state_,
600 install_date_days_rounded,
601 kProvisionedFromOmahaResponse)) {
602 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
603 << install_date_days_rounded << " days";
604 }
605 }
606
David Zeuthene8ed8632014-07-24 13:38:10 -0400607 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700608 return false;
609
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800610 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
611 // appends the package name to the URLs populated in this method.
David Zeuthene8ed8632014-07-24 13:38:10 -0400612 if (!ParseUrls(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700613 return false;
614
David Zeuthene8ed8632014-07-24 13:38:10 -0400615 if (!ParsePackage(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700616 return false;
617
David Zeuthene8ed8632014-07-24 13:38:10 -0400618 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700619 return false;
620
621 return true;
622}
623
David Zeuthene8ed8632014-07-24 13:38:10 -0400624bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700625 OmahaResponse* output_object,
626 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400627 const string& status = parser_data->updatecheck_status;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700628 if (status == "noupdate") {
629 LOG(INFO) << "No update.";
630 output_object->update_exists = false;
631 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700632 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700633 return false;
634 }
635
636 if (status != "ok") {
637 LOG(ERROR) << "Unknown Omaha response status: " << status;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700638 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700639 return false;
640 }
641
642 return true;
643}
644
David Zeuthene8ed8632014-07-24 13:38:10 -0400645bool OmahaRequestAction::ParseUrls(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700646 OmahaResponse* output_object,
647 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400648 if (parser_data->url_codebase.empty()) {
649 LOG(ERROR) << "No Omaha Response URLs";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700650 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700651 return false;
652 }
653
David Zeuthene8ed8632014-07-24 13:38:10 -0400654 LOG(INFO) << "Found " << parser_data->url_codebase.size() << " url(s)";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800655 output_object->payload_urls.clear();
David Zeuthene8ed8632014-07-24 13:38:10 -0400656 for (const auto& codebase : parser_data->url_codebase) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800657 if (codebase.empty()) {
658 LOG(ERROR) << "Omaha Response URL has empty codebase";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700659 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800660 return false;
661 }
662 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700663 }
664
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700665 return true;
666}
667
David Zeuthene8ed8632014-07-24 13:38:10 -0400668bool OmahaRequestAction::ParsePackage(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700669 OmahaResponse* output_object,
670 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400671 if (parser_data->package_name.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700672 LOG(ERROR) << "Omaha Response has empty package name";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700673 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700674 return false;
675 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800676
677 // Append the package name to each URL in our list so that we don't
678 // propagate the urlBase vs packageName distinctions beyond this point.
679 // From now on, we only need to use payload_urls.
David Zeuthene8ed8632014-07-24 13:38:10 -0400680 for (auto& payload_url : output_object->payload_urls)
681 payload_url += parser_data->package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700682
683 // Parse the payload size.
David Zeuthene8ed8632014-07-24 13:38:10 -0400684 off_t size = ParseInt(parser_data->package_size);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700685 if (size <= 0) {
686 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700687 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700688 return false;
689 }
690 output_object->size = size;
691
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800692 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700693
694 return true;
695}
696
David Zeuthene8ed8632014-07-24 13:38:10 -0400697bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700698 OmahaResponse* output_object,
699 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400700 output_object->version = parser_data->manifest_version;
Chris Sosa3b748432013-06-20 16:42:59 -0700701 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700702 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700703 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700704 return false;
705 }
706
707 LOG(INFO) << "Received omaha response to update to version "
708 << output_object->version;
709
David Zeuthene8ed8632014-07-24 13:38:10 -0400710 map<string, string> attrs = parser_data->action_postinstall_attrs;
711 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700712 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700713 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700714 return false;
715 }
716
David Zeuthene8ed8632014-07-24 13:38:10 -0400717 output_object->hash = attrs[kTagSha256];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700718 if (output_object->hash.empty()) {
719 LOG(ERROR) << "Omaha Response has empty sha256 value";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700720 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700721 return false;
722 }
723
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800724 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -0400725 output_object->more_info_url = attrs[kTagMoreInfo];
726 output_object->metadata_size = ParseInt(attrs[kTagMetadataSize]);
727 output_object->metadata_signature = attrs[kTagMetadataSignatureRsa];
728 output_object->prompt = ParseBool(attrs[kTagPrompt]);
729 output_object->deadline = attrs[kTagDeadline];
730 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700731 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -0400732 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700733 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -0400734 ParseBool(attrs[kTagDisableP2PForSharing]);
735 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800736
David Zeuthene8ed8632014-07-24 13:38:10 -0400737 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800738 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800739 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700740
David Zeuthene8ed8632014-07-24 13:38:10 -0400741 output_object->is_delta_payload = ParseBool(attrs[kTagIsDeltaPayload]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800742
743 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -0400744 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800745
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700746 return true;
747}
748
David Zeuthene8ed8632014-07-24 13:38:10 -0400749// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000750// and fill in the appropriate fields of the output object. Also, notifies
751// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700752void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
753 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000754 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800755 string current_response(response_buffer_.begin(), response_buffer_.end());
756 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700757
758 // Events are best effort transactions -- assume they always succeed.
759 if (IsEvent()) {
760 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800761 if (event_->result == OmahaEvent::kResultError && successful &&
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700762 system_state_->hardware()->IsOfficialBuild()) {
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800763 LOG(INFO) << "Signalling Crash Reporter.";
764 utils::ScheduleCrashReporterUpload();
765 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700766 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700767 return;
768 }
769
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700770 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700771 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700772 int code = GetHTTPResponseCode();
773 // Makes sure we send sane error values.
774 if (code < 0 || code >= 1000) {
775 code = 999;
776 }
David Zeuthena99981f2013-04-29 13:42:47 -0700777 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700778 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000779 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700780 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000781
David Zeuthene8ed8632014-07-24 13:38:10 -0400782 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400783 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400784 XML_SetUserData(parser, &parser_data);
785 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400786 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
David Zeuthene8ed8632014-07-24 13:38:10 -0400787 XML_Status res = XML_Parse(parser, &response_buffer_[0],
788 response_buffer_.size(), XML_TRUE);
789 XML_ParserFree(parser);
790
791 if (res != XML_STATUS_OK || parser_data.failed) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000792 LOG(ERROR) << "Omaha response not valid XML";
David Zeuthenf3e28012014-08-26 18:23:52 -0400793 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
794 if (response_buffer_.empty()) {
795 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
796 } else if (parser_data.entity_decl) {
797 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
798 }
799 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000800 return;
801 }
802
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700803 // If a ping was sent, update the last ping day preferences based on
804 // the server daystart response.
805 if (ShouldPing(ping_active_days_) ||
806 ShouldPing(ping_roll_call_days_) ||
807 ping_active_days_ == kPingTimeJump ||
808 ping_roll_call_days_ == kPingTimeJump) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400809 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700810 << "Failed to update the last ping day preferences!";
811 }
812
Thieu Le116fda32011-04-19 11:01:54 -0700813 if (!HasOutputPipe()) {
814 // Just set success to whether or not the http transfer succeeded,
815 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700816 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700817 return;
818 }
819
Darin Petkov6a5b3222010-07-13 14:55:28 -0700820 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400821 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000822 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700823 output_object.update_exists = true;
824 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000825
Chris Sosa77f79e82014-06-02 18:16:24 -0700826 if (ShouldIgnoreUpdate(output_object)) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700827 output_object.update_exists = false;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700828 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700829 return;
830 }
831
David Zeuthen8f191b22013-08-06 12:27:50 -0700832 // If Omaha says to disable p2p, respect that
833 if (output_object.disable_p2p_for_downloading) {
834 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
835 << "requested by Omaha.";
836 params_->set_use_p2p_for_downloading(false);
837 }
838 if (output_object.disable_p2p_for_sharing) {
839 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
840 << "requested by Omaha.";
841 params_->set_use_p2p_for_sharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700842 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800843
844 // Update the payload state with the current response. The payload state
845 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800846 // from what's stored already. We are updating the payload state as late
847 // as possible in this method so that if a new release gets pushed and then
848 // got pulled back due to some issues, we don't want to clear our internal
849 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800850 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800851 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800852
David Zeuthen8f191b22013-08-06 12:27:50 -0700853 // It could be we've already exceeded the deadline for when p2p is
854 // allowed or that we've tried too many times with p2p. Check that.
855 if (params_->use_p2p_for_downloading()) {
856 payload_state->P2PNewAttempt();
857 if (!payload_state->P2PAttemptAllowed()) {
858 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
859 << "of previous failures when using p2p.";
860 params_->set_use_p2p_for_downloading(false);
861 }
862 }
863
864 // From here on, we'll complete stuff in CompleteProcessing() so
865 // disable |completer| since we'll create a new one in that
866 // function.
867 completer.set_should_complete(false);
868
869 // If we're allowed to use p2p for downloading we do not pay
870 // attention to wall-clock-based waiting if the URL is indeed
871 // available via p2p. Therefore, check if the file is available via
872 // p2p before deferring...
873 if (params_->use_p2p_for_downloading()) {
874 LookupPayloadViaP2P(output_object);
875 } else {
876 CompleteProcessing();
877 }
878}
879
880void OmahaRequestAction::CompleteProcessing() {
881 ScopedActionCompleter completer(processor_, this);
882 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
883 PayloadStateInterface* payload_state = system_state_->payload_state();
884
885 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800886 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -0700887 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700888 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -0800889 return;
890 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700891
Chris Sosa20f005c2013-09-05 13:53:08 -0700892 if (payload_state->ShouldBackoffDownload()) {
893 output_object.update_exists = false;
894 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
895 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700896 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -0700897 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700898 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700899 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -0700900}
901
902void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
903 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
904 if (!url.empty()) {
905 params_->set_p2p_url(url);
906 } else {
907 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
908 << "because no suitable peer could be found.";
909 params_->set_use_p2p_for_downloading(false);
910 }
911 CompleteProcessing();
912}
913
914void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -0700915 // If the device is in the middle of an update, the state variables
916 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
917 // tracks the offset and length of the operation currently in
918 // progress. The offset is based from the end of the manifest which
919 // is kPrefsManifestMetadataSize bytes long.
920 //
921 // To make forward progress and avoid deadlocks, we need to find a
922 // peer that has at least the entire operation we're currently
923 // working on. Otherwise we may end up in a situation where two
924 // devices bounce back and forth downloading from each other,
925 // neither making any forward progress until one of them decides to
926 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
927 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -0700928 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -0700929 int64_t manifest_metadata_size = 0;
930 int64_t next_data_offset = 0;
931 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700932 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -0700933 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
934 &manifest_metadata_size) &&
935 manifest_metadata_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -0700936 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -0700937 &next_data_offset) &&
938 next_data_offset != -1 &&
939 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
940 &next_data_length)) {
941 minimum_size = manifest_metadata_size + next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -0700942 }
943
944 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700945 if (system_state_->p2p_manager()) {
David Zeuthen8f191b22013-08-06 12:27:50 -0700946 LOG(INFO) << "Checking if payload is available via p2p, file_id="
947 << file_id << " minimum_size=" << minimum_size;
948 system_state_->p2p_manager()->LookupUrlForFile(
949 file_id,
950 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -0800951 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -0700952 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
953 base::Unretained(this)));
954 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000955}
956
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700957bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -0700958 if (params_->interactive()) {
959 LOG(INFO) << "Not deferring download because update is interactive.";
960 return false;
961 }
962
David Zeuthen8f191b22013-08-06 12:27:50 -0700963 // If we're using p2p to download _and_ we have a p2p URL, we never
964 // defer the download. This is because the download will always
965 // happen from a peer on the LAN and we've been waiting in line for
966 // our turn.
967 if (params_->use_p2p_for_downloading() && !params_->p2p_url().empty()) {
968 LOG(INFO) << "Download not deferred because download "
969 << "will happen from a local peer (via p2p).";
970 return false;
971 }
972
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700973 // We should defer the downloads only if we've first satisfied the
974 // wall-clock-based-waiting period and then the update-check-based waiting
975 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700976 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -0700977 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
978 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700979 return false;
980 }
981
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700982 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700983 case kWallClockWaitNotSatisfied:
984 // We haven't even satisfied the first condition, passing the
985 // wall-clock-based waiting period, so we should defer the downloads
986 // until that happens.
987 LOG(INFO) << "wall-clock-based-wait not satisfied.";
988 return true;
989
990 case kWallClockWaitDoneButUpdateCheckWaitRequired:
991 LOG(INFO) << "wall-clock-based-wait satisfied and "
992 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700993 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700994
995 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
996 // Wall-clock-based waiting period is satisfied, and it's determined
997 // that we do not need the update-check-based wait. so no need to
998 // defer downloads.
999 LOG(INFO) << "wall-clock-based-wait satisfied and "
1000 << "update-check-based-wait is not required.";
1001 return false;
1002
1003 default:
1004 // Returning false for this default case so we err on the
1005 // side of downloading updates than deferring in case of any bugs.
1006 NOTREACHED();
1007 return false;
1008 }
1009}
1010
1011OmahaRequestAction::WallClockWaitResult
1012OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001013 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001014 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001015 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001016
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001017 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1018 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1019 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001020 // Note: This timestamp could be that of ANY update we saw in the past
1021 // (not necessarily this particular update we're considering to apply)
1022 // but never got to apply because of some reason (e.g. stop AU policy,
1023 // updates being pulled out from Omaha, changes in target version prefix,
1024 // new update being rolled out, etc.). But for the purposes of scattering
1025 // it doesn't matter which update the timestamp corresponds to. i.e.
1026 // the clock starts ticking the first time we see an update and we're
1027 // ready to apply when the random wait period is satisfied relative to
1028 // that first seen timestamp.
1029 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1030 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1031 << utils::ToString(update_first_seen_at);
1032 } else {
1033 // This seems like an unexpected error where the persisted value exists
1034 // but it's not readable for some reason. Just skip scattering in this
1035 // case to be safe.
1036 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1037 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1038 }
1039 } else {
1040 update_first_seen_at = Time::Now();
1041 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001042 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1043 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001044 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1045 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001046 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001047 // This seems like an unexpected error where the value cannot be
1048 // persisted for some reason. Just skip scattering in this
1049 // case to be safe.
1050 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1051 << utils::ToString(update_first_seen_at)
1052 << " cannot be persisted";
1053 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1054 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001055 }
1056
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001057 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001058 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001059 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001060
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001061 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001062 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001063 << ", Time Elapsed = "
1064 << utils::FormatSecs(elapsed_time.InSeconds())
1065 << ", MaxDaysToScatter = "
1066 << max_scatter_period.InDays();
1067
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001068 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001069 // The deadline is set for all rules which serve a delta update from a
1070 // previous FSI, which means this update will be applied mostly in OOBE
1071 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1072 // quickly.
1073 LOG(INFO) << "Not scattering as deadline flag is set";
1074 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1075 }
1076
1077 if (max_scatter_period.InDays() == 0) {
1078 // This means the Omaha rule creator decides that this rule
1079 // should not be scattered irrespective of the policy.
1080 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1081 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1082 }
1083
1084 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001085 // This means we've waited more than the upperbound wait in the rule
1086 // from the time we first saw a valid update available to us.
1087 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001088 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1089 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1090 }
1091
1092 // This means we are required to participate in scattering.
1093 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001094 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001095 if (remaining_wait_time.InSeconds() <= 0) {
1096 // Yes, it's our turn now.
1097 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1098
1099 // But we can't download until the update-check-count-based wait is also
1100 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001101 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001102 kWallClockWaitDoneButUpdateCheckWaitRequired :
1103 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1104 }
1105
1106 // Not our turn yet, so we have to wait until our turn to
1107 // help scatter the downloads across all clients of the enterprise.
1108 LOG(INFO) << "Update deferred for another "
1109 << utils::FormatSecs(remaining_wait_time.InSeconds())
1110 << " per policy.";
1111 return kWallClockWaitNotSatisfied;
1112}
1113
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001114bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001115 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001116
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001117 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1118 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1119 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001120 // We are unable to read the update check count from file for some reason.
1121 // So let's proceed anyway so as to not stall the update.
1122 LOG(ERROR) << "Unable to read update check count. "
1123 << "Skipping update-check-count-based-wait.";
1124 return true;
1125 }
1126 } else {
1127 // This file does not exist. This means we haven't started our update
1128 // check count down yet, so this is the right time to start the count down.
1129 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001130 params_->min_update_checks_needed(),
1131 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001132
1133 LOG(INFO) << "Randomly picked update check count value = "
1134 << update_check_count_value;
1135
1136 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001137 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1138 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001139 // We weren't able to write the update check count file for some reason.
1140 // So let's proceed anyway so as to not stall the update.
1141 LOG(ERROR) << "Unable to write update check count. "
1142 << "Skipping update-check-count-based-wait.";
1143 return true;
1144 }
1145 }
1146
1147 if (update_check_count_value == 0) {
1148 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1149 return true;
1150 }
1151
1152 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001153 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001154 // We err on the side of skipping scattering logic instead of stalling
1155 // a machine from receiving any updates in case of any unexpected state.
1156 LOG(ERROR) << "Invalid value for update check count detected. "
1157 << "Skipping update-check-count-based-wait.";
1158 return true;
1159 }
1160
1161 // Legal value, we need to wait for more update checks to happen
1162 // until this becomes 0.
1163 LOG(INFO) << "Deferring Omaha updates for another "
1164 << update_check_count_value
1165 << " update checks per policy";
1166 return false;
1167}
1168
David Zeuthen639aa362014-02-03 16:23:44 -08001169// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001170bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001171 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001172 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001173 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001174 &elapsed_days))
1175 return false;
1176
1177 if (elapsed_days < 0)
1178 return false;
1179
1180 output_object->install_date_days = elapsed_days;
1181 return true;
1182}
1183
1184// static
1185bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1186 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001187 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001188 return false;
1189
1190 return prefs->Exists(kPrefsInstallDateDays);
1191}
1192
1193// static
1194bool OmahaRequestAction::PersistInstallDate(
1195 SystemState *system_state,
1196 int install_date_days,
1197 InstallDateProvisioningSource source) {
1198 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1199
1200 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001201 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001202 return false;
1203
1204 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1205 return false;
1206
1207 string metric_name = "Installer.InstallDateProvisioningSource";
1208 system_state->metrics_lib()->SendEnumToUMA(
1209 metric_name,
David Zeuthen33bae492014-02-25 16:16:18 -08001210 static_cast<int>(source), // Sample.
1211 kProvisionedMax); // Maximum.
1212
1213 metric_name = metrics::kMetricInstallDateProvisioningSource;
1214 system_state->metrics_lib()->SendEnumToUMA(
1215 metric_name,
1216 static_cast<int>(source), // Sample.
1217 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001218
1219 return true;
1220}
1221
David Zeuthen33bae492014-02-25 16:16:18 -08001222void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1223 // We only want to report this on "update check".
1224 if (ping_only_ || event_ != nullptr)
1225 return;
1226
1227 metrics::CheckResult result = metrics::CheckResult::kUnset;
1228 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1229 metrics::DownloadErrorCode download_error_code =
1230 metrics::DownloadErrorCode::kUnset;
1231
1232 // Regular update attempt.
1233 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001234 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001235 // OK, we parsed the response successfully but that does
1236 // necessarily mean that an update is available.
1237 if (HasOutputPipe()) {
1238 const OmahaResponse& response = GetOutputObject();
1239 if (response.update_exists) {
1240 result = metrics::CheckResult::kUpdateAvailable;
1241 reaction = metrics::CheckReaction::kUpdating;
1242 } else {
1243 result = metrics::CheckResult::kNoUpdateAvailable;
1244 }
1245 } else {
1246 result = metrics::CheckResult::kNoUpdateAvailable;
1247 }
1248 break;
1249
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001250 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001251 result = metrics::CheckResult::kUpdateAvailable;
1252 reaction = metrics::CheckReaction::kIgnored;
1253 break;
1254
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001255 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001256 result = metrics::CheckResult::kUpdateAvailable;
1257 reaction = metrics::CheckReaction::kDeferring;
1258 break;
1259
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001260 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001261 result = metrics::CheckResult::kUpdateAvailable;
1262 reaction = metrics::CheckReaction::kBackingOff;
1263 break;
1264
1265 default:
1266 // We report two flavors of errors, "Download errors" and "Parsing
1267 // error". Try to convert to the former and if that doesn't work
1268 // we know it's the latter.
1269 metrics::DownloadErrorCode tmp_error = utils::GetDownloadErrorCode(code);
1270 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1271 result = metrics::CheckResult::kDownloadError;
1272 download_error_code = tmp_error;
1273 } else {
1274 result = metrics::CheckResult::kParsingError;
1275 }
1276 break;
1277 }
1278
1279 metrics::ReportUpdateCheckMetrics(system_state_,
1280 result, reaction, download_error_code);
1281}
1282
Chris Sosa77f79e82014-06-02 18:16:24 -07001283bool OmahaRequestAction::ShouldIgnoreUpdate(
1284 const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001285 // Note: policy decision to not update to a version we rolled back from.
1286 string rollback_version =
1287 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001288 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001289 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001290 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001291 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1292 return true;
1293 }
1294 }
1295
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001296 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001297 LOG(INFO) << "Update is not allowed over current connection.";
1298 return true;
1299 }
1300
1301 // Note: We could technically delete the UpdateFirstSeenAt state when we
1302 // return true. If we do, it'll mean a device has to restart the
1303 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1304 // turned on again. On the other hand, it also increases the chance of update
1305 // starvation if an admin turns AU on/off more frequently. We choose to err on
1306 // the side of preventing starvation at the cost of not applying scattering in
1307 // those cases.
1308 return false;
1309}
1310
1311bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
1312 NetworkConnectionType type;
1313 NetworkTethering tethering;
1314 RealDBusWrapper dbus_iface;
1315 ConnectionManager* connection_manager = system_state_->connection_manager();
1316 if (!connection_manager->GetConnectionProperties(&dbus_iface,
1317 &type, &tethering)) {
1318 LOG(INFO) << "We could not determine our connection type. "
1319 << "Defaulting to allow updates.";
1320 return true;
1321 }
1322 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1323 LOG(INFO) << "We are connected via "
1324 << connection_manager->StringForConnectionType(type)
1325 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1326 return is_allowed;
1327}
1328
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001329} // namespace chromeos_update_engine