blob: cb436a36cf326c6ca455c624db13610b04663e0a [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;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700537 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
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
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700578 // slow down the request rate from the server-side. Note that the PollInterval
579 // is not persisted, so it has to be sent by the server on every response to
580 // guarantee that the scheduler uses this value (otherwise, if the device got
581 // rebooted after the last server-indicated value, it'll revert to the default
582 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
583 // based on the assumption that we perform an update check every hour so that
584 // the max value of 8 will roughly be equivalent to one work day. If we decide
585 // to use PollInterval permanently, we should update the
586 // max_update_checks_allowed to take PollInterval into account. Note: The
587 // parsing for PollInterval happens even before parsing of the status because
588 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400589 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700590 &output_object->poll_interval);
591
David Zeuthen639aa362014-02-03 16:23:44 -0800592 // Check for the "elapsed_days" attribute in the "daystart"
593 // element. This is the number of days since Jan 1 2007, 0:00
594 // PST. If we don't have a persisted value of the Omaha InstallDate,
595 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400596 if (ParseInstallDate(parser_data, output_object) &&
597 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800598 // Since output_object->install_date_days is never negative, the
599 // elapsed_days -> install-date calculation is reduced to simply
600 // rounding down to the nearest number divisible by 7.
601 int remainder = output_object->install_date_days % 7;
602 int install_date_days_rounded =
603 output_object->install_date_days - remainder;
604 if (PersistInstallDate(system_state_,
605 install_date_days_rounded,
606 kProvisionedFromOmahaResponse)) {
607 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
608 << install_date_days_rounded << " days";
609 }
610 }
611
David Zeuthene8ed8632014-07-24 13:38:10 -0400612 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700613 return false;
614
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800615 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
616 // appends the package name to the URLs populated in this method.
David Zeuthene8ed8632014-07-24 13:38:10 -0400617 if (!ParseUrls(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700618 return false;
619
David Zeuthene8ed8632014-07-24 13:38:10 -0400620 if (!ParsePackage(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700621 return false;
622
David Zeuthene8ed8632014-07-24 13:38:10 -0400623 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700624 return false;
625
626 return true;
627}
628
David Zeuthene8ed8632014-07-24 13:38:10 -0400629bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700630 OmahaResponse* output_object,
631 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400632 const string& status = parser_data->updatecheck_status;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700633 if (status == "noupdate") {
634 LOG(INFO) << "No update.";
635 output_object->update_exists = false;
636 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700637 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700638 return false;
639 }
640
641 if (status != "ok") {
642 LOG(ERROR) << "Unknown Omaha response status: " << status;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700643 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700644 return false;
645 }
646
647 return true;
648}
649
David Zeuthene8ed8632014-07-24 13:38:10 -0400650bool OmahaRequestAction::ParseUrls(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700651 OmahaResponse* output_object,
652 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400653 if (parser_data->url_codebase.empty()) {
654 LOG(ERROR) << "No Omaha Response URLs";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700655 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700656 return false;
657 }
658
David Zeuthene8ed8632014-07-24 13:38:10 -0400659 LOG(INFO) << "Found " << parser_data->url_codebase.size() << " url(s)";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800660 output_object->payload_urls.clear();
David Zeuthene8ed8632014-07-24 13:38:10 -0400661 for (const auto& codebase : parser_data->url_codebase) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800662 if (codebase.empty()) {
663 LOG(ERROR) << "Omaha Response URL has empty codebase";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700664 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800665 return false;
666 }
667 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700668 }
669
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700670 return true;
671}
672
David Zeuthene8ed8632014-07-24 13:38:10 -0400673bool OmahaRequestAction::ParsePackage(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700674 OmahaResponse* output_object,
675 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400676 if (parser_data->package_name.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700677 LOG(ERROR) << "Omaha Response has empty package name";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700678 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700679 return false;
680 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800681
682 // Append the package name to each URL in our list so that we don't
683 // propagate the urlBase vs packageName distinctions beyond this point.
684 // From now on, we only need to use payload_urls.
David Zeuthene8ed8632014-07-24 13:38:10 -0400685 for (auto& payload_url : output_object->payload_urls)
686 payload_url += parser_data->package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700687
688 // Parse the payload size.
David Zeuthene8ed8632014-07-24 13:38:10 -0400689 off_t size = ParseInt(parser_data->package_size);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700690 if (size <= 0) {
691 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700692 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700693 return false;
694 }
695 output_object->size = size;
696
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800697 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700698
699 return true;
700}
701
David Zeuthene8ed8632014-07-24 13:38:10 -0400702bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700703 OmahaResponse* output_object,
704 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400705 output_object->version = parser_data->manifest_version;
Chris Sosa3b748432013-06-20 16:42:59 -0700706 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700707 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700708 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700709 return false;
710 }
711
712 LOG(INFO) << "Received omaha response to update to version "
713 << output_object->version;
714
David Zeuthene8ed8632014-07-24 13:38:10 -0400715 map<string, string> attrs = parser_data->action_postinstall_attrs;
716 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700717 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700718 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700719 return false;
720 }
721
David Zeuthene8ed8632014-07-24 13:38:10 -0400722 output_object->hash = attrs[kTagSha256];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700723 if (output_object->hash.empty()) {
724 LOG(ERROR) << "Omaha Response has empty sha256 value";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700725 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700726 return false;
727 }
728
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800729 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -0400730 output_object->more_info_url = attrs[kTagMoreInfo];
731 output_object->metadata_size = ParseInt(attrs[kTagMetadataSize]);
732 output_object->metadata_signature = attrs[kTagMetadataSignatureRsa];
733 output_object->prompt = ParseBool(attrs[kTagPrompt]);
734 output_object->deadline = attrs[kTagDeadline];
735 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700736 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -0400737 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700738 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -0400739 ParseBool(attrs[kTagDisableP2PForSharing]);
740 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800741
David Zeuthene8ed8632014-07-24 13:38:10 -0400742 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800743 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800744 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700745
David Zeuthene8ed8632014-07-24 13:38:10 -0400746 output_object->is_delta_payload = ParseBool(attrs[kTagIsDeltaPayload]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800747
748 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -0400749 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800750
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700751 return true;
752}
753
David Zeuthene8ed8632014-07-24 13:38:10 -0400754// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000755// and fill in the appropriate fields of the output object. Also, notifies
756// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700757void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
758 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000759 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800760 string current_response(response_buffer_.begin(), response_buffer_.end());
761 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700762
763 // Events are best effort transactions -- assume they always succeed.
764 if (IsEvent()) {
765 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800766 if (event_->result == OmahaEvent::kResultError && successful &&
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700767 system_state_->hardware()->IsOfficialBuild()) {
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800768 LOG(INFO) << "Signalling Crash Reporter.";
769 utils::ScheduleCrashReporterUpload();
770 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700771 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700772 return;
773 }
774
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700775 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700776 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700777 int code = GetHTTPResponseCode();
778 // Makes sure we send sane error values.
779 if (code < 0 || code >= 1000) {
780 code = 999;
781 }
David Zeuthena99981f2013-04-29 13:42:47 -0700782 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700783 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000784 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700785 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000786
David Zeuthene8ed8632014-07-24 13:38:10 -0400787 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400788 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400789 XML_SetUserData(parser, &parser_data);
790 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400791 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
David Zeuthene8ed8632014-07-24 13:38:10 -0400792 XML_Status res = XML_Parse(parser, &response_buffer_[0],
793 response_buffer_.size(), XML_TRUE);
794 XML_ParserFree(parser);
795
796 if (res != XML_STATUS_OK || parser_data.failed) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000797 LOG(ERROR) << "Omaha response not valid XML";
David Zeuthenf3e28012014-08-26 18:23:52 -0400798 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
799 if (response_buffer_.empty()) {
800 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
801 } else if (parser_data.entity_decl) {
802 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
803 }
804 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000805 return;
806 }
807
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700808 // If a ping was sent, update the last ping day preferences based on
809 // the server daystart response.
810 if (ShouldPing(ping_active_days_) ||
811 ShouldPing(ping_roll_call_days_) ||
812 ping_active_days_ == kPingTimeJump ||
813 ping_roll_call_days_ == kPingTimeJump) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400814 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700815 << "Failed to update the last ping day preferences!";
816 }
817
Thieu Le116fda32011-04-19 11:01:54 -0700818 if (!HasOutputPipe()) {
819 // Just set success to whether or not the http transfer succeeded,
820 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700821 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700822 return;
823 }
824
Darin Petkov6a5b3222010-07-13 14:55:28 -0700825 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400826 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000827 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700828 output_object.update_exists = true;
829 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000830
Chris Sosa77f79e82014-06-02 18:16:24 -0700831 if (ShouldIgnoreUpdate(output_object)) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700832 output_object.update_exists = false;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700833 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700834 return;
835 }
836
David Zeuthen8f191b22013-08-06 12:27:50 -0700837 // If Omaha says to disable p2p, respect that
838 if (output_object.disable_p2p_for_downloading) {
839 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
840 << "requested by Omaha.";
841 params_->set_use_p2p_for_downloading(false);
842 }
843 if (output_object.disable_p2p_for_sharing) {
844 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
845 << "requested by Omaha.";
846 params_->set_use_p2p_for_sharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700847 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800848
849 // Update the payload state with the current response. The payload state
850 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800851 // from what's stored already. We are updating the payload state as late
852 // as possible in this method so that if a new release gets pushed and then
853 // got pulled back due to some issues, we don't want to clear our internal
854 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800855 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800856 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800857
David Zeuthen8f191b22013-08-06 12:27:50 -0700858 // It could be we've already exceeded the deadline for when p2p is
859 // allowed or that we've tried too many times with p2p. Check that.
860 if (params_->use_p2p_for_downloading()) {
861 payload_state->P2PNewAttempt();
862 if (!payload_state->P2PAttemptAllowed()) {
863 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
864 << "of previous failures when using p2p.";
865 params_->set_use_p2p_for_downloading(false);
866 }
867 }
868
869 // From here on, we'll complete stuff in CompleteProcessing() so
870 // disable |completer| since we'll create a new one in that
871 // function.
872 completer.set_should_complete(false);
873
874 // If we're allowed to use p2p for downloading we do not pay
875 // attention to wall-clock-based waiting if the URL is indeed
876 // available via p2p. Therefore, check if the file is available via
877 // p2p before deferring...
878 if (params_->use_p2p_for_downloading()) {
879 LookupPayloadViaP2P(output_object);
880 } else {
881 CompleteProcessing();
882 }
883}
884
885void OmahaRequestAction::CompleteProcessing() {
886 ScopedActionCompleter completer(processor_, this);
887 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
888 PayloadStateInterface* payload_state = system_state_->payload_state();
889
890 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800891 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -0700892 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700893 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -0800894 return;
895 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700896
Chris Sosa20f005c2013-09-05 13:53:08 -0700897 if (payload_state->ShouldBackoffDownload()) {
898 output_object.update_exists = false;
899 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
900 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700901 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -0700902 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700903 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700904 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -0700905}
906
907void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
908 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
909 if (!url.empty()) {
910 params_->set_p2p_url(url);
911 } else {
912 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
913 << "because no suitable peer could be found.";
914 params_->set_use_p2p_for_downloading(false);
915 }
916 CompleteProcessing();
917}
918
919void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -0700920 // If the device is in the middle of an update, the state variables
921 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
922 // tracks the offset and length of the operation currently in
923 // progress. The offset is based from the end of the manifest which
924 // is kPrefsManifestMetadataSize bytes long.
925 //
926 // To make forward progress and avoid deadlocks, we need to find a
927 // peer that has at least the entire operation we're currently
928 // working on. Otherwise we may end up in a situation where two
929 // devices bounce back and forth downloading from each other,
930 // neither making any forward progress until one of them decides to
931 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
932 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -0700933 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -0700934 int64_t manifest_metadata_size = 0;
935 int64_t next_data_offset = 0;
936 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700937 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -0700938 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
939 &manifest_metadata_size) &&
940 manifest_metadata_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -0700941 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -0700942 &next_data_offset) &&
943 next_data_offset != -1 &&
944 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
945 &next_data_length)) {
946 minimum_size = manifest_metadata_size + next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -0700947 }
948
949 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700950 if (system_state_->p2p_manager()) {
David Zeuthen8f191b22013-08-06 12:27:50 -0700951 LOG(INFO) << "Checking if payload is available via p2p, file_id="
952 << file_id << " minimum_size=" << minimum_size;
953 system_state_->p2p_manager()->LookupUrlForFile(
954 file_id,
955 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -0800956 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -0700957 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
958 base::Unretained(this)));
959 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000960}
961
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700962bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -0700963 if (params_->interactive()) {
964 LOG(INFO) << "Not deferring download because update is interactive.";
965 return false;
966 }
967
David Zeuthen8f191b22013-08-06 12:27:50 -0700968 // If we're using p2p to download _and_ we have a p2p URL, we never
969 // defer the download. This is because the download will always
970 // happen from a peer on the LAN and we've been waiting in line for
971 // our turn.
972 if (params_->use_p2p_for_downloading() && !params_->p2p_url().empty()) {
973 LOG(INFO) << "Download not deferred because download "
974 << "will happen from a local peer (via p2p).";
975 return false;
976 }
977
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700978 // We should defer the downloads only if we've first satisfied the
979 // wall-clock-based-waiting period and then the update-check-based waiting
980 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700981 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -0700982 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
983 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700984 return false;
985 }
986
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700987 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700988 case kWallClockWaitNotSatisfied:
989 // We haven't even satisfied the first condition, passing the
990 // wall-clock-based waiting period, so we should defer the downloads
991 // until that happens.
992 LOG(INFO) << "wall-clock-based-wait not satisfied.";
993 return true;
994
995 case kWallClockWaitDoneButUpdateCheckWaitRequired:
996 LOG(INFO) << "wall-clock-based-wait satisfied and "
997 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700998 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700999
1000 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1001 // Wall-clock-based waiting period is satisfied, and it's determined
1002 // that we do not need the update-check-based wait. so no need to
1003 // defer downloads.
1004 LOG(INFO) << "wall-clock-based-wait satisfied and "
1005 << "update-check-based-wait is not required.";
1006 return false;
1007
1008 default:
1009 // Returning false for this default case so we err on the
1010 // side of downloading updates than deferring in case of any bugs.
1011 NOTREACHED();
1012 return false;
1013 }
1014}
1015
1016OmahaRequestAction::WallClockWaitResult
1017OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001018 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001019 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001020 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001021
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001022 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1023 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1024 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001025 // Note: This timestamp could be that of ANY update we saw in the past
1026 // (not necessarily this particular update we're considering to apply)
1027 // but never got to apply because of some reason (e.g. stop AU policy,
1028 // updates being pulled out from Omaha, changes in target version prefix,
1029 // new update being rolled out, etc.). But for the purposes of scattering
1030 // it doesn't matter which update the timestamp corresponds to. i.e.
1031 // the clock starts ticking the first time we see an update and we're
1032 // ready to apply when the random wait period is satisfied relative to
1033 // that first seen timestamp.
1034 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1035 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1036 << utils::ToString(update_first_seen_at);
1037 } else {
1038 // This seems like an unexpected error where the persisted value exists
1039 // but it's not readable for some reason. Just skip scattering in this
1040 // case to be safe.
1041 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1042 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1043 }
1044 } else {
1045 update_first_seen_at = Time::Now();
1046 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001047 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1048 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001049 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1050 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001051 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001052 // This seems like an unexpected error where the value cannot be
1053 // persisted for some reason. Just skip scattering in this
1054 // case to be safe.
1055 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1056 << utils::ToString(update_first_seen_at)
1057 << " cannot be persisted";
1058 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1059 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001060 }
1061
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001062 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001063 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001064 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001065
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001066 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001067 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001068 << ", Time Elapsed = "
1069 << utils::FormatSecs(elapsed_time.InSeconds())
1070 << ", MaxDaysToScatter = "
1071 << max_scatter_period.InDays();
1072
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001073 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001074 // The deadline is set for all rules which serve a delta update from a
1075 // previous FSI, which means this update will be applied mostly in OOBE
1076 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1077 // quickly.
1078 LOG(INFO) << "Not scattering as deadline flag is set";
1079 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1080 }
1081
1082 if (max_scatter_period.InDays() == 0) {
1083 // This means the Omaha rule creator decides that this rule
1084 // should not be scattered irrespective of the policy.
1085 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1086 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1087 }
1088
1089 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001090 // This means we've waited more than the upperbound wait in the rule
1091 // from the time we first saw a valid update available to us.
1092 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001093 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1094 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1095 }
1096
1097 // This means we are required to participate in scattering.
1098 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001099 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001100 if (remaining_wait_time.InSeconds() <= 0) {
1101 // Yes, it's our turn now.
1102 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1103
1104 // But we can't download until the update-check-count-based wait is also
1105 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001106 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001107 kWallClockWaitDoneButUpdateCheckWaitRequired :
1108 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1109 }
1110
1111 // Not our turn yet, so we have to wait until our turn to
1112 // help scatter the downloads across all clients of the enterprise.
1113 LOG(INFO) << "Update deferred for another "
1114 << utils::FormatSecs(remaining_wait_time.InSeconds())
1115 << " per policy.";
1116 return kWallClockWaitNotSatisfied;
1117}
1118
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001119bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001120 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001121
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001122 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1123 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1124 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001125 // We are unable to read the update check count from file for some reason.
1126 // So let's proceed anyway so as to not stall the update.
1127 LOG(ERROR) << "Unable to read update check count. "
1128 << "Skipping update-check-count-based-wait.";
1129 return true;
1130 }
1131 } else {
1132 // This file does not exist. This means we haven't started our update
1133 // check count down yet, so this is the right time to start the count down.
1134 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001135 params_->min_update_checks_needed(),
1136 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001137
1138 LOG(INFO) << "Randomly picked update check count value = "
1139 << update_check_count_value;
1140
1141 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001142 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1143 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001144 // We weren't able to write the update check count file for some reason.
1145 // So let's proceed anyway so as to not stall the update.
1146 LOG(ERROR) << "Unable to write update check count. "
1147 << "Skipping update-check-count-based-wait.";
1148 return true;
1149 }
1150 }
1151
1152 if (update_check_count_value == 0) {
1153 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1154 return true;
1155 }
1156
1157 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001158 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001159 // We err on the side of skipping scattering logic instead of stalling
1160 // a machine from receiving any updates in case of any unexpected state.
1161 LOG(ERROR) << "Invalid value for update check count detected. "
1162 << "Skipping update-check-count-based-wait.";
1163 return true;
1164 }
1165
1166 // Legal value, we need to wait for more update checks to happen
1167 // until this becomes 0.
1168 LOG(INFO) << "Deferring Omaha updates for another "
1169 << update_check_count_value
1170 << " update checks per policy";
1171 return false;
1172}
1173
David Zeuthen639aa362014-02-03 16:23:44 -08001174// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001175bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001176 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001177 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001178 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001179 &elapsed_days))
1180 return false;
1181
1182 if (elapsed_days < 0)
1183 return false;
1184
1185 output_object->install_date_days = elapsed_days;
1186 return true;
1187}
1188
1189// static
1190bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1191 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001192 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001193 return false;
1194
1195 return prefs->Exists(kPrefsInstallDateDays);
1196}
1197
1198// static
1199bool OmahaRequestAction::PersistInstallDate(
1200 SystemState *system_state,
1201 int install_date_days,
1202 InstallDateProvisioningSource source) {
1203 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1204
1205 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001206 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001207 return false;
1208
1209 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1210 return false;
1211
1212 string metric_name = "Installer.InstallDateProvisioningSource";
1213 system_state->metrics_lib()->SendEnumToUMA(
1214 metric_name,
David Zeuthen33bae492014-02-25 16:16:18 -08001215 static_cast<int>(source), // Sample.
1216 kProvisionedMax); // Maximum.
1217
1218 metric_name = metrics::kMetricInstallDateProvisioningSource;
1219 system_state->metrics_lib()->SendEnumToUMA(
1220 metric_name,
1221 static_cast<int>(source), // Sample.
1222 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001223
1224 return true;
1225}
1226
David Zeuthen33bae492014-02-25 16:16:18 -08001227void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1228 // We only want to report this on "update check".
1229 if (ping_only_ || event_ != nullptr)
1230 return;
1231
1232 metrics::CheckResult result = metrics::CheckResult::kUnset;
1233 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1234 metrics::DownloadErrorCode download_error_code =
1235 metrics::DownloadErrorCode::kUnset;
1236
1237 // Regular update attempt.
1238 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001239 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001240 // OK, we parsed the response successfully but that does
1241 // necessarily mean that an update is available.
1242 if (HasOutputPipe()) {
1243 const OmahaResponse& response = GetOutputObject();
1244 if (response.update_exists) {
1245 result = metrics::CheckResult::kUpdateAvailable;
1246 reaction = metrics::CheckReaction::kUpdating;
1247 } else {
1248 result = metrics::CheckResult::kNoUpdateAvailable;
1249 }
1250 } else {
1251 result = metrics::CheckResult::kNoUpdateAvailable;
1252 }
1253 break;
1254
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001255 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001256 result = metrics::CheckResult::kUpdateAvailable;
1257 reaction = metrics::CheckReaction::kIgnored;
1258 break;
1259
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001260 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001261 result = metrics::CheckResult::kUpdateAvailable;
1262 reaction = metrics::CheckReaction::kDeferring;
1263 break;
1264
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001265 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001266 result = metrics::CheckResult::kUpdateAvailable;
1267 reaction = metrics::CheckReaction::kBackingOff;
1268 break;
1269
1270 default:
1271 // We report two flavors of errors, "Download errors" and "Parsing
1272 // error". Try to convert to the former and if that doesn't work
1273 // we know it's the latter.
1274 metrics::DownloadErrorCode tmp_error = utils::GetDownloadErrorCode(code);
1275 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1276 result = metrics::CheckResult::kDownloadError;
1277 download_error_code = tmp_error;
1278 } else {
1279 result = metrics::CheckResult::kParsingError;
1280 }
1281 break;
1282 }
1283
1284 metrics::ReportUpdateCheckMetrics(system_state_,
1285 result, reaction, download_error_code);
1286}
1287
Chris Sosa77f79e82014-06-02 18:16:24 -07001288bool OmahaRequestAction::ShouldIgnoreUpdate(
1289 const OmahaResponse& response) const {
1290 if (params_->update_disabled()) {
1291 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
1292 return true;
1293 }
1294
1295 // Note: policy decision to not update to a version we rolled back from.
1296 string rollback_version =
1297 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001298 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001299 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001300 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001301 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1302 return true;
1303 }
1304 }
1305
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001306 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001307 LOG(INFO) << "Update is not allowed over current connection.";
1308 return true;
1309 }
1310
1311 // Note: We could technically delete the UpdateFirstSeenAt state when we
1312 // return true. If we do, it'll mean a device has to restart the
1313 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1314 // turned on again. On the other hand, it also increases the chance of update
1315 // starvation if an admin turns AU on/off more frequently. We choose to err on
1316 // the side of preventing starvation at the cost of not applying scattering in
1317 // those cases.
1318 return false;
1319}
1320
1321bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
1322 NetworkConnectionType type;
1323 NetworkTethering tethering;
1324 RealDBusWrapper dbus_iface;
1325 ConnectionManager* connection_manager = system_state_->connection_manager();
1326 if (!connection_manager->GetConnectionProperties(&dbus_iface,
1327 &type, &tethering)) {
1328 LOG(INFO) << "We could not determine our connection type. "
1329 << "Defaulting to allow updates.";
1330 return true;
1331 }
1332 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1333 LOG(INFO) << "We are connected via "
1334 << connection_manager->StringForConnectionType(type)
1335 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1336 return is_allowed;
1337}
1338
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001339} // namespace chromeos_update_engine