blob: ede4e64aa51f65a6651907e34211d7e9b7202c12 [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) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700107 // not passing update_disabled to Omaha because we want to
108 // get the update and report with UpdateDeferred result so that
109 // borgmon charts show up updates that are deferred. This is also
110 // the expected behavior when we move to Omaha v3.0 protocol, so it'll
111 // be consistent.
Alex Vakulenko75039d72014-03-25 12:36:28 -0700112 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700113 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700114 "></updatecheck>\n",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700115 XmlEncode(params->target_version_prefix()).c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700116
Darin Petkov265f2902011-05-09 15:17:40 -0700117 // If this is the first update check after a reboot following a previous
118 // update, generate an event containing the previous version number. If
119 // the previous version preference file doesn't exist the event is still
120 // generated with a previous version of 0.0.0.0 -- this is relevant for
121 // older clients or new installs. The previous version event is not sent
122 // for ping-only requests because they come before the client has
123 // rebooted.
124 string prev_version;
125 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
126 prev_version = "0.0.0.0";
127 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700128
Alex Vakulenko75039d72014-03-25 12:36:28 -0700129 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700130 " <event eventtype=\"%d\" eventresult=\"%d\" "
131 "previousversion=\"%s\"></event>\n",
132 OmahaEvent::kTypeUpdateComplete,
133 OmahaEvent::kResultSuccessReboot,
134 XmlEncode(prev_version).c_str());
135 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
136 << "Unable to reset the previous version.";
Darin Petkov95508da2011-01-05 12:42:29 -0800137 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700138 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800139 // The error code is an optional attribute so append it only if the result
140 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700141 string error_code;
142 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700143 error_code = base::StringPrintf(" errorcode=\"%d\"",
144 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700145 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700146 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700147 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700148 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700149 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700150
151 return app_body;
152}
153
154// Returns an XML that corresponds to the entire <app> node of the Omaha
155// request based on the given parameters.
156string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700157 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700158 bool ping_only,
159 int ping_active_days,
160 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800161 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700162 SystemState* system_state) {
163 string app_body = GetAppBody(event, params, ping_only, ping_active_days,
164 ping_roll_call_days, system_state->prefs());
165 string app_versions;
166
167 // If we are upgrading to a more stable channel and we are allowed to do
168 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
169 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700170 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700171 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
172 << "on downgrading to the version in the more stable channel";
173 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700174 XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700175 } else {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700176 app_versions = "version=\"" + XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700177 }
178
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700179 string download_channel = params->download_channel();
180 string app_channels = "track=\"" + XmlEncode(download_channel) + "\" ";
181 if (params->current_channel() != download_channel)
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700182 app_channels +=
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700183 "from_track=\"" + XmlEncode(params->current_channel()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700184
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700185 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700186
David Zeuthen639aa362014-02-03 16:23:44 -0800187 // If install_date_days is not set (e.g. its value is -1 ), don't
188 // include the attribute.
189 string install_date_in_days_str = "";
190 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700191 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
192 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800193 }
194
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700195 string app_xml =
Jay Srinivasandb0acdf2013-04-02 14:47:45 -0700196 " <app appid=\"" + XmlEncode(params->GetAppId()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700197 app_versions +
198 app_channels +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700199 "lang=\"" + XmlEncode(params->app_lang()) + "\" " +
200 "board=\"" + XmlEncode(params->os_board()) + "\" " +
201 "hardware_class=\"" + XmlEncode(params->hwid()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700202 "delta_okay=\"" + delta_okay_str + "\" "
Chris Sosac1972482013-04-30 22:31:10 -0700203 "fw_version=\"" + XmlEncode(params->fw_version()) + "\" " +
204 "ec_version=\"" + XmlEncode(params->ec_version()) + "\" " +
David Zeuthen639aa362014-02-03 16:23:44 -0800205 install_date_in_days_str +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700206 ">\n" +
207 app_body +
208 " </app>\n";
209
210 return app_xml;
211}
212
213// Returns an XML that corresponds to the entire <os> node of the Omaha
214// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700215string GetOsXml(OmahaRequestParams* params) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700216 string os_xml =
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700217 " <os version=\"" + XmlEncode(params->os_version()) + "\" " +
218 "platform=\"" + XmlEncode(params->os_platform()) + "\" " +
219 "sp=\"" + XmlEncode(params->os_sp()) + "\">"
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700220 "</os>\n";
221 return os_xml;
222}
223
224// Returns an XML that corresponds to the entire Omaha request based on the
225// given parameters.
226string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700227 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700228 bool ping_only,
229 int ping_active_days,
230 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800231 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700232 SystemState* system_state) {
233 string os_xml = GetOsXml(params);
234 string app_xml = GetAppXml(event, params, ping_only, ping_active_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800235 ping_roll_call_days, install_date_in_days,
236 system_state);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700237
Alex Vakulenko75039d72014-03-25 12:36:28 -0700238 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700239 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700240
241 string request_xml =
242 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700243 "<request protocol=\"3.0\" "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700244 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
245 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" " +
246 install_source +
247 "ismachine=\"1\">\n" +
248 os_xml +
249 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700250 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700251
252 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000253}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700254
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700255} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000256
David Zeuthene8ed8632014-07-24 13:38:10 -0400257// Struct used for holding data obtained when parsing the XML.
258struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400259 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
260
261 // Pointer to the expat XML_Parser object.
262 XML_Parser xml_parser;
263
David Zeuthene8ed8632014-07-24 13:38:10 -0400264 // This is the state of the parser as it's processing the XML.
265 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400266 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400267 string current_path;
268
269 // These are the values extracted from the XML.
270 string updatecheck_status;
271 string updatecheck_poll_interval;
272 string daystart_elapsed_days;
273 string daystart_elapsed_seconds;
274 vector<string> url_codebase;
275 string package_name;
276 string package_size;
277 string manifest_version;
278 map<string, string> action_postinstall_attrs;
279};
280
281namespace {
282
283// Callback function invoked by expat.
284void ParserHandlerStart(void* user_data, const XML_Char* element,
285 const XML_Char** attr) {
286 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
287
288 if (data->failed)
289 return;
290
291 data->current_path += string("/") + element;
292
293 map<string, string> attrs;
294 if (attr != nullptr) {
295 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
296 string key = attr[n];
297 string value = attr[n + 1];
298 attrs[key] = value;
299 }
300 }
301
302 if (data->current_path == "/response/app/updatecheck") {
303 // There is only supposed to be a single <updatecheck> element.
304 data->updatecheck_status = attrs["status"];
305 data->updatecheck_poll_interval = attrs["PollInterval"];
306 } else if (data->current_path == "/response/daystart") {
307 // Get the install-date.
308 data->daystart_elapsed_days = attrs["elapsed_days"];
309 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
310 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
311 // Look at all <url> elements.
312 data->url_codebase.push_back(attrs["codebase"]);
313 } else if (data->package_name.empty() && data->current_path ==
314 "/response/app/updatecheck/manifest/packages/package") {
315 // Only look at the first <package>.
316 data->package_name = attrs["name"];
317 data->package_size = attrs["size"];
318 } else if (data->current_path == "/response/app/updatecheck/manifest") {
319 // Get the version.
320 data->manifest_version = attrs[kTagVersion];
321 } else if (data->current_path ==
322 "/response/app/updatecheck/manifest/actions/action") {
323 // We only care about the postinstall action.
324 if (attrs["event"] == "postinstall") {
325 data->action_postinstall_attrs = attrs;
326 }
327 }
328}
329
330// Callback function invoked by expat.
331void ParserHandlerEnd(void* user_data, const XML_Char* element) {
332 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
333 if (data->failed)
334 return;
335
336 const string path_suffix = string("/") + element;
337
338 if (!EndsWith(data->current_path, path_suffix, true)) {
339 LOG(ERROR) << "Unexpected end element '" << element
340 << "' with current_path='" << data->current_path << "'";
341 data->failed = true;
342 return;
343 }
344 data->current_path.resize(data->current_path.size() - path_suffix.size());
345}
346
David Zeuthenf3e28012014-08-26 18:23:52 -0400347// Callback function invoked by expat.
348//
349// This is called for entity declarations. Since Omaha is guaranteed
350// to never return any XML with entities our course of action is to
351// just stop parsing. This avoids potential resource exhaustion
352// problems AKA the "billion laughs". CVE-2013-0340.
353void ParserHandlerEntityDecl(void *user_data,
354 const XML_Char *entity_name,
355 int is_parameter_entity,
356 const XML_Char *value,
357 int value_length,
358 const XML_Char *base,
359 const XML_Char *system_id,
360 const XML_Char *public_id,
361 const XML_Char *notation_name) {
362 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
363
364 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
365 data->failed = true;
366 data->entity_decl = true;
367 XML_StopParser(data->xml_parser, false);
368}
369
David Zeuthene8ed8632014-07-24 13:38:10 -0400370} // namespace
371
372// Escapes text so it can be included as character data and attribute
373// values. The |input| string must be valid UTF-8.
rspangler@google.com49fdf182009-10-10 00:57:34 +0000374string XmlEncode(const string& input) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400375 gchar* escaped = g_markup_escape_text(input.c_str(), input.size());
376 string ret = string(escaped);
377 g_free(escaped);
378 return ret;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000379}
380
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800381OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700382 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700383 HttpFetcher* http_fetcher,
384 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800385 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700386 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700387 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700388 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700389 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700390 ping_roll_call_days_(0) {
391 params_ = system_state->request_params();
392}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000393
Darin Petkov6a5b3222010-07-13 14:55:28 -0700394OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000395
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700396// Calculates the value to use for the ping days parameter.
397int OmahaRequestAction::CalculatePingDays(const string& key) {
398 int days = kNeverPinged;
399 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800400 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700401 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
402 if (days < 0) {
403 // If |days| is negative, then the system clock must have jumped
404 // back in time since the ping was sent. Mark the value so that
405 // it doesn't get sent to the server but we still update the
406 // last ping daystart preference. This way the next ping time
407 // will be correct, hopefully.
408 days = kPingTimeJump;
409 LOG(WARNING) <<
410 "System clock jumped back in time. Resetting ping daystarts.";
411 }
412 }
413 return days;
414}
415
416void OmahaRequestAction::InitPingDays() {
417 // We send pings only along with update checks, not with events.
418 if (IsEvent()) {
419 return;
420 }
421 // TODO(petkov): Figure a way to distinguish active use pings
422 // vs. roll call pings. Currently, the two pings are identical. A
423 // fix needs to change this code as well as UpdateLastPingDays.
424 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
425 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
426}
427
David Zeuthen639aa362014-02-03 16:23:44 -0800428// static
429int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
430 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700431 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800432 return -1;
433
434 // If we have the value stored on disk, just return it.
435 int64_t stored_value;
436 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
437 // Convert and sanity-check.
438 int install_date_days = static_cast<int>(stored_value);
439 if (install_date_days >= 0)
440 return install_date_days;
441 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
442 << install_date_days << " looks suspicious.";
443 prefs->Delete(kPrefsInstallDateDays);
444 }
445
446 // Otherwise, if OOBE is not complete then do nothing and wait for
447 // ParseResponse() to call ParseInstallDate() and then
448 // PersistInstallDate() to set the kPrefsInstallDateDays state
449 // variable. Once that is done, we'll then report back in future
450 // Omaha requests. This works exactly because OOBE triggers an
451 // update check.
452 //
453 // However, if OOBE is complete and the kPrefsInstallDateDays state
454 // variable is not set, there are two possibilities
455 //
456 // 1. The update check in OOBE failed so we never got a response
457 // from Omaha (no network etc.); or
458 //
459 // 2. OOBE was done on an older version that didn't write to the
460 // kPrefsInstallDateDays state variable.
461 //
462 // In both cases, we approximate the install date by simply
463 // inspecting the timestamp of when OOBE happened.
464
465 Time time_of_oobe;
Alex Deymobccbc382014-04-03 13:38:55 -0700466 if (!system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800467 LOG(INFO) << "Not generating Omaha InstallData as we have "
468 << "no prefs file and OOBE is not complete.";
469 return -1;
470 }
471
472 int num_days;
473 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
474 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
475 << "as its value '" << utils::ToString(time_of_oobe)
476 << "' looks suspicious.";
477 return -1;
478 }
479
480 // Persist this to disk, for future use.
481 if (!OmahaRequestAction::PersistInstallDate(system_state,
482 num_days,
483 kProvisionedFromOOBEMarker))
484 return -1;
485
486 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
487 << num_days << " days";
488
489 return num_days;
490}
491
Darin Petkov6a5b3222010-07-13 14:55:28 -0700492void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000493 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700494 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700495 if (ping_only_ &&
496 !ShouldPing(ping_active_days_) &&
497 !ShouldPing(ping_roll_call_days_)) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700498 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700499 return;
500 }
David Zeuthen639aa362014-02-03 16:23:44 -0800501
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700502 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700503 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700504 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700505 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800506 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800507 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700508 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700509
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800510 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
511 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700512 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700513 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700514 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000515}
516
Darin Petkov6a5b3222010-07-13 14:55:28 -0700517void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000518 http_fetcher_->TerminateTransfer();
519}
520
521// We just store the response in the buffer. Once we've received all bytes,
522// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700523void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
524 const char* bytes,
525 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000526 response_buffer_.reserve(response_buffer_.size() + length);
527 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
528}
529
530namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000531
532// Parses a 64 bit base-10 int from a string and returns it. Returns 0
533// on error. If the string contains "0", that's indistinguishable from
534// error.
535off_t ParseInt(const string& str) {
536 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700537 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000538 if (rc < 1) {
539 // failure
540 return 0;
541 }
542 return ret;
543}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700544
David Zeuthene8ed8632014-07-24 13:38:10 -0400545// Parses |str| and returns |true| if, and only if, its value is "true".
546bool ParseBool(const string& str) {
547 return str == "true";
548}
549
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700550// Update the last ping day preferences based on the server daystart
551// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400552bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700553 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400554 TEST_AND_RETURN_FALSE(
555 base::StringToInt64(parser_data->daystart_elapsed_seconds,
556 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700557 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
558
559 // Remember the local time that matches the server's last midnight
560 // time.
561 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
562 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
563 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
564 return true;
565}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700566} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000567
David Zeuthene8ed8632014-07-24 13:38:10 -0400568bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700569 OmahaResponse* output_object,
570 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400571 if (parser_data->updatecheck_status.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700572 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700573 return false;
574 }
575
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800576 // chromium-os:37289: The PollInterval is not supported by Omaha server
577 // currently. But still keeping this existing code in case we ever decide to
578 // slow down the request rate from the server-side. Note that the
579 // PollInterval is not persisted, so it has to be sent by the server on every
580 // response to guarantee that the UpdateCheckScheduler uses this value
581 // (otherwise, if the device got rebooted after the last server-indicated
582 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
583 // value for the scattering logic is based on the assumption that we perform
584 // an update check every hour so that the max value of 8 will roughly be
585 // equivalent to one work day. If we decide to use PollInterval permanently,
586 // we should update the max_update_checks_allowed to take PollInterval into
587 // account. Note: The parsing for PollInterval happens even before parsing
588 // of the status because we may want to specify the PollInterval even when
589 // there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400590 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700591 &output_object->poll_interval);
592
David Zeuthen639aa362014-02-03 16:23:44 -0800593 // Check for the "elapsed_days" attribute in the "daystart"
594 // element. This is the number of days since Jan 1 2007, 0:00
595 // PST. If we don't have a persisted value of the Omaha InstallDate,
596 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400597 if (ParseInstallDate(parser_data, output_object) &&
598 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800599 // Since output_object->install_date_days is never negative, the
600 // elapsed_days -> install-date calculation is reduced to simply
601 // rounding down to the nearest number divisible by 7.
602 int remainder = output_object->install_date_days % 7;
603 int install_date_days_rounded =
604 output_object->install_date_days - remainder;
605 if (PersistInstallDate(system_state_,
606 install_date_days_rounded,
607 kProvisionedFromOmahaResponse)) {
608 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
609 << install_date_days_rounded << " days";
610 }
611 }
612
David Zeuthene8ed8632014-07-24 13:38:10 -0400613 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700614 return false;
615
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800616 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
617 // appends the package name to the URLs populated in this method.
David Zeuthene8ed8632014-07-24 13:38:10 -0400618 if (!ParseUrls(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700619 return false;
620
David Zeuthene8ed8632014-07-24 13:38:10 -0400621 if (!ParsePackage(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700622 return false;
623
David Zeuthene8ed8632014-07-24 13:38:10 -0400624 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700625 return false;
626
627 return true;
628}
629
David Zeuthene8ed8632014-07-24 13:38:10 -0400630bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700631 OmahaResponse* output_object,
632 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400633 const string& status = parser_data->updatecheck_status;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700634 if (status == "noupdate") {
635 LOG(INFO) << "No update.";
636 output_object->update_exists = false;
637 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700638 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700639 return false;
640 }
641
642 if (status != "ok") {
643 LOG(ERROR) << "Unknown Omaha response status: " << status;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700644 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700645 return false;
646 }
647
648 return true;
649}
650
David Zeuthene8ed8632014-07-24 13:38:10 -0400651bool OmahaRequestAction::ParseUrls(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700652 OmahaResponse* output_object,
653 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400654 if (parser_data->url_codebase.empty()) {
655 LOG(ERROR) << "No Omaha Response URLs";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700656 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700657 return false;
658 }
659
David Zeuthene8ed8632014-07-24 13:38:10 -0400660 LOG(INFO) << "Found " << parser_data->url_codebase.size() << " url(s)";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800661 output_object->payload_urls.clear();
David Zeuthene8ed8632014-07-24 13:38:10 -0400662 for (const auto& codebase : parser_data->url_codebase) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800663 if (codebase.empty()) {
664 LOG(ERROR) << "Omaha Response URL has empty codebase";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700665 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800666 return false;
667 }
668 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700669 }
670
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700671 return true;
672}
673
David Zeuthene8ed8632014-07-24 13:38:10 -0400674bool OmahaRequestAction::ParsePackage(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700675 OmahaResponse* output_object,
676 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400677 if (parser_data->package_name.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700678 LOG(ERROR) << "Omaha Response has empty package name";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700679 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700680 return false;
681 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800682
683 // Append the package name to each URL in our list so that we don't
684 // propagate the urlBase vs packageName distinctions beyond this point.
685 // From now on, we only need to use payload_urls.
David Zeuthene8ed8632014-07-24 13:38:10 -0400686 for (auto& payload_url : output_object->payload_urls)
687 payload_url += parser_data->package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700688
689 // Parse the payload size.
David Zeuthene8ed8632014-07-24 13:38:10 -0400690 off_t size = ParseInt(parser_data->package_size);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700691 if (size <= 0) {
692 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700693 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700694 return false;
695 }
696 output_object->size = size;
697
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800698 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700699
700 return true;
701}
702
David Zeuthene8ed8632014-07-24 13:38:10 -0400703bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700704 OmahaResponse* output_object,
705 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400706 output_object->version = parser_data->manifest_version;
Chris Sosa3b748432013-06-20 16:42:59 -0700707 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700708 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700709 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700710 return false;
711 }
712
713 LOG(INFO) << "Received omaha response to update to version "
714 << output_object->version;
715
David Zeuthene8ed8632014-07-24 13:38:10 -0400716 map<string, string> attrs = parser_data->action_postinstall_attrs;
717 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700718 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700719 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700720 return false;
721 }
722
David Zeuthene8ed8632014-07-24 13:38:10 -0400723 output_object->hash = attrs[kTagSha256];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700724 if (output_object->hash.empty()) {
725 LOG(ERROR) << "Omaha Response has empty sha256 value";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700726 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700727 return false;
728 }
729
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800730 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -0400731 output_object->more_info_url = attrs[kTagMoreInfo];
732 output_object->metadata_size = ParseInt(attrs[kTagMetadataSize]);
733 output_object->metadata_signature = attrs[kTagMetadataSignatureRsa];
734 output_object->prompt = ParseBool(attrs[kTagPrompt]);
735 output_object->deadline = attrs[kTagDeadline];
736 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700737 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -0400738 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700739 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -0400740 ParseBool(attrs[kTagDisableP2PForSharing]);
741 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800742
David Zeuthene8ed8632014-07-24 13:38:10 -0400743 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800744 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800745 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700746
David Zeuthene8ed8632014-07-24 13:38:10 -0400747 output_object->is_delta_payload = ParseBool(attrs[kTagIsDeltaPayload]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800748
749 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -0400750 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800751
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700752 return true;
753}
754
David Zeuthene8ed8632014-07-24 13:38:10 -0400755// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000756// and fill in the appropriate fields of the output object. Also, notifies
757// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700758void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
759 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000760 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800761 string current_response(response_buffer_.begin(), response_buffer_.end());
762 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700763
764 // Events are best effort transactions -- assume they always succeed.
765 if (IsEvent()) {
766 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800767 if (event_->result == OmahaEvent::kResultError && successful &&
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700768 system_state_->hardware()->IsOfficialBuild()) {
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800769 LOG(INFO) << "Signalling Crash Reporter.";
770 utils::ScheduleCrashReporterUpload();
771 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700772 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700773 return;
774 }
775
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700776 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700777 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700778 int code = GetHTTPResponseCode();
779 // Makes sure we send sane error values.
780 if (code < 0 || code >= 1000) {
781 code = 999;
782 }
David Zeuthena99981f2013-04-29 13:42:47 -0700783 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700784 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000785 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700786 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000787
David Zeuthene8ed8632014-07-24 13:38:10 -0400788 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400789 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400790 XML_SetUserData(parser, &parser_data);
791 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400792 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
David Zeuthene8ed8632014-07-24 13:38:10 -0400793 XML_Status res = XML_Parse(parser, &response_buffer_[0],
794 response_buffer_.size(), XML_TRUE);
795 XML_ParserFree(parser);
796
797 if (res != XML_STATUS_OK || parser_data.failed) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000798 LOG(ERROR) << "Omaha response not valid XML";
David Zeuthenf3e28012014-08-26 18:23:52 -0400799 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
800 if (response_buffer_.empty()) {
801 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
802 } else if (parser_data.entity_decl) {
803 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
804 }
805 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000806 return;
807 }
808
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700809 // If a ping was sent, update the last ping day preferences based on
810 // the server daystart response.
811 if (ShouldPing(ping_active_days_) ||
812 ShouldPing(ping_roll_call_days_) ||
813 ping_active_days_ == kPingTimeJump ||
814 ping_roll_call_days_ == kPingTimeJump) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400815 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700816 << "Failed to update the last ping day preferences!";
817 }
818
Thieu Le116fda32011-04-19 11:01:54 -0700819 if (!HasOutputPipe()) {
820 // Just set success to whether or not the http transfer succeeded,
821 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700822 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700823 return;
824 }
825
Darin Petkov6a5b3222010-07-13 14:55:28 -0700826 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400827 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000828 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700829 output_object.update_exists = true;
830 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000831
Chris Sosa77f79e82014-06-02 18:16:24 -0700832 if (ShouldIgnoreUpdate(output_object)) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700833 output_object.update_exists = false;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700834 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700835 return;
836 }
837
David Zeuthen8f191b22013-08-06 12:27:50 -0700838 // If Omaha says to disable p2p, respect that
839 if (output_object.disable_p2p_for_downloading) {
840 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
841 << "requested by Omaha.";
842 params_->set_use_p2p_for_downloading(false);
843 }
844 if (output_object.disable_p2p_for_sharing) {
845 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
846 << "requested by Omaha.";
847 params_->set_use_p2p_for_sharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700848 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800849
850 // Update the payload state with the current response. The payload state
851 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800852 // from what's stored already. We are updating the payload state as late
853 // as possible in this method so that if a new release gets pushed and then
854 // got pulled back due to some issues, we don't want to clear our internal
855 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800856 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800857 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800858
David Zeuthen8f191b22013-08-06 12:27:50 -0700859 // It could be we've already exceeded the deadline for when p2p is
860 // allowed or that we've tried too many times with p2p. Check that.
861 if (params_->use_p2p_for_downloading()) {
862 payload_state->P2PNewAttempt();
863 if (!payload_state->P2PAttemptAllowed()) {
864 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
865 << "of previous failures when using p2p.";
866 params_->set_use_p2p_for_downloading(false);
867 }
868 }
869
870 // From here on, we'll complete stuff in CompleteProcessing() so
871 // disable |completer| since we'll create a new one in that
872 // function.
873 completer.set_should_complete(false);
874
875 // If we're allowed to use p2p for downloading we do not pay
876 // attention to wall-clock-based waiting if the URL is indeed
877 // available via p2p. Therefore, check if the file is available via
878 // p2p before deferring...
879 if (params_->use_p2p_for_downloading()) {
880 LookupPayloadViaP2P(output_object);
881 } else {
882 CompleteProcessing();
883 }
884}
885
886void OmahaRequestAction::CompleteProcessing() {
887 ScopedActionCompleter completer(processor_, this);
888 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
889 PayloadStateInterface* payload_state = system_state_->payload_state();
890
891 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800892 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -0700893 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700894 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -0800895 return;
896 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700897
Chris Sosa20f005c2013-09-05 13:53:08 -0700898 if (payload_state->ShouldBackoffDownload()) {
899 output_object.update_exists = false;
900 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
901 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700902 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -0700903 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700904 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700905 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -0700906}
907
908void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
909 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
910 if (!url.empty()) {
911 params_->set_p2p_url(url);
912 } else {
913 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
914 << "because no suitable peer could be found.";
915 params_->set_use_p2p_for_downloading(false);
916 }
917 CompleteProcessing();
918}
919
920void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -0700921 // If the device is in the middle of an update, the state variables
922 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
923 // tracks the offset and length of the operation currently in
924 // progress. The offset is based from the end of the manifest which
925 // is kPrefsManifestMetadataSize bytes long.
926 //
927 // To make forward progress and avoid deadlocks, we need to find a
928 // peer that has at least the entire operation we're currently
929 // working on. Otherwise we may end up in a situation where two
930 // devices bounce back and forth downloading from each other,
931 // neither making any forward progress until one of them decides to
932 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
933 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -0700934 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -0700935 int64_t manifest_metadata_size = 0;
936 int64_t next_data_offset = 0;
937 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700938 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -0700939 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
940 &manifest_metadata_size) &&
941 manifest_metadata_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -0700942 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -0700943 &next_data_offset) &&
944 next_data_offset != -1 &&
945 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
946 &next_data_length)) {
947 minimum_size = manifest_metadata_size + next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -0700948 }
949
950 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700951 if (system_state_->p2p_manager()) {
David Zeuthen8f191b22013-08-06 12:27:50 -0700952 LOG(INFO) << "Checking if payload is available via p2p, file_id="
953 << file_id << " minimum_size=" << minimum_size;
954 system_state_->p2p_manager()->LookupUrlForFile(
955 file_id,
956 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -0800957 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -0700958 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
959 base::Unretained(this)));
960 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000961}
962
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700963bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -0700964 if (params_->interactive()) {
965 LOG(INFO) << "Not deferring download because update is interactive.";
966 return false;
967 }
968
David Zeuthen8f191b22013-08-06 12:27:50 -0700969 // If we're using p2p to download _and_ we have a p2p URL, we never
970 // defer the download. This is because the download will always
971 // happen from a peer on the LAN and we've been waiting in line for
972 // our turn.
973 if (params_->use_p2p_for_downloading() && !params_->p2p_url().empty()) {
974 LOG(INFO) << "Download not deferred because download "
975 << "will happen from a local peer (via p2p).";
976 return false;
977 }
978
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700979 // We should defer the downloads only if we've first satisfied the
980 // wall-clock-based-waiting period and then the update-check-based waiting
981 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700982 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -0700983 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
984 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700985 return false;
986 }
987
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700988 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700989 case kWallClockWaitNotSatisfied:
990 // We haven't even satisfied the first condition, passing the
991 // wall-clock-based waiting period, so we should defer the downloads
992 // until that happens.
993 LOG(INFO) << "wall-clock-based-wait not satisfied.";
994 return true;
995
996 case kWallClockWaitDoneButUpdateCheckWaitRequired:
997 LOG(INFO) << "wall-clock-based-wait satisfied and "
998 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700999 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001000
1001 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1002 // Wall-clock-based waiting period is satisfied, and it's determined
1003 // that we do not need the update-check-based wait. so no need to
1004 // defer downloads.
1005 LOG(INFO) << "wall-clock-based-wait satisfied and "
1006 << "update-check-based-wait is not required.";
1007 return false;
1008
1009 default:
1010 // Returning false for this default case so we err on the
1011 // side of downloading updates than deferring in case of any bugs.
1012 NOTREACHED();
1013 return false;
1014 }
1015}
1016
1017OmahaRequestAction::WallClockWaitResult
1018OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001019 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001020 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001021 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001022
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001023 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1024 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1025 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001026 // Note: This timestamp could be that of ANY update we saw in the past
1027 // (not necessarily this particular update we're considering to apply)
1028 // but never got to apply because of some reason (e.g. stop AU policy,
1029 // updates being pulled out from Omaha, changes in target version prefix,
1030 // new update being rolled out, etc.). But for the purposes of scattering
1031 // it doesn't matter which update the timestamp corresponds to. i.e.
1032 // the clock starts ticking the first time we see an update and we're
1033 // ready to apply when the random wait period is satisfied relative to
1034 // that first seen timestamp.
1035 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1036 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1037 << utils::ToString(update_first_seen_at);
1038 } else {
1039 // This seems like an unexpected error where the persisted value exists
1040 // but it's not readable for some reason. Just skip scattering in this
1041 // case to be safe.
1042 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1043 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1044 }
1045 } else {
1046 update_first_seen_at = Time::Now();
1047 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001048 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1049 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001050 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1051 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001052 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001053 // This seems like an unexpected error where the value cannot be
1054 // persisted for some reason. Just skip scattering in this
1055 // case to be safe.
1056 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1057 << utils::ToString(update_first_seen_at)
1058 << " cannot be persisted";
1059 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1060 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001061 }
1062
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001063 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001064 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001065 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001066
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001067 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001068 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001069 << ", Time Elapsed = "
1070 << utils::FormatSecs(elapsed_time.InSeconds())
1071 << ", MaxDaysToScatter = "
1072 << max_scatter_period.InDays();
1073
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001074 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001075 // The deadline is set for all rules which serve a delta update from a
1076 // previous FSI, which means this update will be applied mostly in OOBE
1077 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1078 // quickly.
1079 LOG(INFO) << "Not scattering as deadline flag is set";
1080 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1081 }
1082
1083 if (max_scatter_period.InDays() == 0) {
1084 // This means the Omaha rule creator decides that this rule
1085 // should not be scattered irrespective of the policy.
1086 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1087 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1088 }
1089
1090 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001091 // This means we've waited more than the upperbound wait in the rule
1092 // from the time we first saw a valid update available to us.
1093 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001094 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1095 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1096 }
1097
1098 // This means we are required to participate in scattering.
1099 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001100 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001101 if (remaining_wait_time.InSeconds() <= 0) {
1102 // Yes, it's our turn now.
1103 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1104
1105 // But we can't download until the update-check-count-based wait is also
1106 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001107 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001108 kWallClockWaitDoneButUpdateCheckWaitRequired :
1109 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1110 }
1111
1112 // Not our turn yet, so we have to wait until our turn to
1113 // help scatter the downloads across all clients of the enterprise.
1114 LOG(INFO) << "Update deferred for another "
1115 << utils::FormatSecs(remaining_wait_time.InSeconds())
1116 << " per policy.";
1117 return kWallClockWaitNotSatisfied;
1118}
1119
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001120bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001121 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001122
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001123 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1124 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1125 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001126 // We are unable to read the update check count from file for some reason.
1127 // So let's proceed anyway so as to not stall the update.
1128 LOG(ERROR) << "Unable to read update check count. "
1129 << "Skipping update-check-count-based-wait.";
1130 return true;
1131 }
1132 } else {
1133 // This file does not exist. This means we haven't started our update
1134 // check count down yet, so this is the right time to start the count down.
1135 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001136 params_->min_update_checks_needed(),
1137 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001138
1139 LOG(INFO) << "Randomly picked update check count value = "
1140 << update_check_count_value;
1141
1142 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001143 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1144 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001145 // We weren't able to write the update check count file for some reason.
1146 // So let's proceed anyway so as to not stall the update.
1147 LOG(ERROR) << "Unable to write update check count. "
1148 << "Skipping update-check-count-based-wait.";
1149 return true;
1150 }
1151 }
1152
1153 if (update_check_count_value == 0) {
1154 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1155 return true;
1156 }
1157
1158 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001159 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001160 // We err on the side of skipping scattering logic instead of stalling
1161 // a machine from receiving any updates in case of any unexpected state.
1162 LOG(ERROR) << "Invalid value for update check count detected. "
1163 << "Skipping update-check-count-based-wait.";
1164 return true;
1165 }
1166
1167 // Legal value, we need to wait for more update checks to happen
1168 // until this becomes 0.
1169 LOG(INFO) << "Deferring Omaha updates for another "
1170 << update_check_count_value
1171 << " update checks per policy";
1172 return false;
1173}
1174
David Zeuthen639aa362014-02-03 16:23:44 -08001175// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001176bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001177 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001178 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001179 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001180 &elapsed_days))
1181 return false;
1182
1183 if (elapsed_days < 0)
1184 return false;
1185
1186 output_object->install_date_days = elapsed_days;
1187 return true;
1188}
1189
1190// static
1191bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1192 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001193 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001194 return false;
1195
1196 return prefs->Exists(kPrefsInstallDateDays);
1197}
1198
1199// static
1200bool OmahaRequestAction::PersistInstallDate(
1201 SystemState *system_state,
1202 int install_date_days,
1203 InstallDateProvisioningSource source) {
1204 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1205
1206 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001207 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001208 return false;
1209
1210 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1211 return false;
1212
1213 string metric_name = "Installer.InstallDateProvisioningSource";
1214 system_state->metrics_lib()->SendEnumToUMA(
1215 metric_name,
David Zeuthen33bae492014-02-25 16:16:18 -08001216 static_cast<int>(source), // Sample.
1217 kProvisionedMax); // Maximum.
1218
1219 metric_name = metrics::kMetricInstallDateProvisioningSource;
1220 system_state->metrics_lib()->SendEnumToUMA(
1221 metric_name,
1222 static_cast<int>(source), // Sample.
1223 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001224
1225 return true;
1226}
1227
David Zeuthen33bae492014-02-25 16:16:18 -08001228void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1229 // We only want to report this on "update check".
1230 if (ping_only_ || event_ != nullptr)
1231 return;
1232
1233 metrics::CheckResult result = metrics::CheckResult::kUnset;
1234 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1235 metrics::DownloadErrorCode download_error_code =
1236 metrics::DownloadErrorCode::kUnset;
1237
1238 // Regular update attempt.
1239 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001240 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001241 // OK, we parsed the response successfully but that does
1242 // necessarily mean that an update is available.
1243 if (HasOutputPipe()) {
1244 const OmahaResponse& response = GetOutputObject();
1245 if (response.update_exists) {
1246 result = metrics::CheckResult::kUpdateAvailable;
1247 reaction = metrics::CheckReaction::kUpdating;
1248 } else {
1249 result = metrics::CheckResult::kNoUpdateAvailable;
1250 }
1251 } else {
1252 result = metrics::CheckResult::kNoUpdateAvailable;
1253 }
1254 break;
1255
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001256 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001257 result = metrics::CheckResult::kUpdateAvailable;
1258 reaction = metrics::CheckReaction::kIgnored;
1259 break;
1260
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001261 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001262 result = metrics::CheckResult::kUpdateAvailable;
1263 reaction = metrics::CheckReaction::kDeferring;
1264 break;
1265
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001266 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001267 result = metrics::CheckResult::kUpdateAvailable;
1268 reaction = metrics::CheckReaction::kBackingOff;
1269 break;
1270
1271 default:
1272 // We report two flavors of errors, "Download errors" and "Parsing
1273 // error". Try to convert to the former and if that doesn't work
1274 // we know it's the latter.
1275 metrics::DownloadErrorCode tmp_error = utils::GetDownloadErrorCode(code);
1276 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1277 result = metrics::CheckResult::kDownloadError;
1278 download_error_code = tmp_error;
1279 } else {
1280 result = metrics::CheckResult::kParsingError;
1281 }
1282 break;
1283 }
1284
1285 metrics::ReportUpdateCheckMetrics(system_state_,
1286 result, reaction, download_error_code);
1287}
1288
Chris Sosa77f79e82014-06-02 18:16:24 -07001289bool OmahaRequestAction::ShouldIgnoreUpdate(
1290 const OmahaResponse& response) const {
1291 if (params_->update_disabled()) {
1292 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
1293 return true;
1294 }
1295
1296 // Note: policy decision to not update to a version we rolled back from.
1297 string rollback_version =
1298 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001299 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001300 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001301 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001302 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1303 return true;
1304 }
1305 }
1306
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001307 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001308 LOG(INFO) << "Update is not allowed over current connection.";
1309 return true;
1310 }
1311
1312 // Note: We could technically delete the UpdateFirstSeenAt state when we
1313 // return true. If we do, it'll mean a device has to restart the
1314 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1315 // turned on again. On the other hand, it also increases the chance of update
1316 // starvation if an admin turns AU on/off more frequently. We choose to err on
1317 // the side of preventing starvation at the cost of not applying scattering in
1318 // those cases.
1319 return false;
1320}
1321
1322bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
1323 NetworkConnectionType type;
1324 NetworkTethering tethering;
1325 RealDBusWrapper dbus_iface;
1326 ConnectionManager* connection_manager = system_state_->connection_manager();
1327 if (!connection_manager->GetConnectionProperties(&dbus_iface,
1328 &type, &tethering)) {
1329 LOG(INFO) << "We could not determine our connection type. "
1330 << "Defaulting to allow updates.";
1331 return true;
1332 }
1333 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1334 LOG(INFO) << "We are connected via "
1335 << connection_manager->StringForConnectionType(type)
1336 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1337 return is_allowed;
1338}
1339
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001340} // namespace chromeos_update_engine