blob: 7ccd0d5506aac71582b3abffb94e906765219c9c [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;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700104 if (event == NULL) {
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 {
259 // This is the state of the parser as it's processing the XML.
260 bool failed = false;
261 string current_path;
262
263 // These are the values extracted from the XML.
264 string updatecheck_status;
265 string updatecheck_poll_interval;
266 string daystart_elapsed_days;
267 string daystart_elapsed_seconds;
268 vector<string> url_codebase;
269 string package_name;
270 string package_size;
271 string manifest_version;
272 map<string, string> action_postinstall_attrs;
273};
274
275namespace {
276
277// Callback function invoked by expat.
278void ParserHandlerStart(void* user_data, const XML_Char* element,
279 const XML_Char** attr) {
280 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
281
282 if (data->failed)
283 return;
284
285 data->current_path += string("/") + element;
286
287 map<string, string> attrs;
288 if (attr != nullptr) {
289 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
290 string key = attr[n];
291 string value = attr[n + 1];
292 attrs[key] = value;
293 }
294 }
295
296 if (data->current_path == "/response/app/updatecheck") {
297 // There is only supposed to be a single <updatecheck> element.
298 data->updatecheck_status = attrs["status"];
299 data->updatecheck_poll_interval = attrs["PollInterval"];
300 } else if (data->current_path == "/response/daystart") {
301 // Get the install-date.
302 data->daystart_elapsed_days = attrs["elapsed_days"];
303 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
304 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
305 // Look at all <url> elements.
306 data->url_codebase.push_back(attrs["codebase"]);
307 } else if (data->package_name.empty() && data->current_path ==
308 "/response/app/updatecheck/manifest/packages/package") {
309 // Only look at the first <package>.
310 data->package_name = attrs["name"];
311 data->package_size = attrs["size"];
312 } else if (data->current_path == "/response/app/updatecheck/manifest") {
313 // Get the version.
314 data->manifest_version = attrs[kTagVersion];
315 } else if (data->current_path ==
316 "/response/app/updatecheck/manifest/actions/action") {
317 // We only care about the postinstall action.
318 if (attrs["event"] == "postinstall") {
319 data->action_postinstall_attrs = attrs;
320 }
321 }
322}
323
324// Callback function invoked by expat.
325void ParserHandlerEnd(void* user_data, const XML_Char* element) {
326 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
327 if (data->failed)
328 return;
329
330 const string path_suffix = string("/") + element;
331
332 if (!EndsWith(data->current_path, path_suffix, true)) {
333 LOG(ERROR) << "Unexpected end element '" << element
334 << "' with current_path='" << data->current_path << "'";
335 data->failed = true;
336 return;
337 }
338 data->current_path.resize(data->current_path.size() - path_suffix.size());
339}
340
341} // namespace
342
343// Escapes text so it can be included as character data and attribute
344// values. The |input| string must be valid UTF-8.
rspangler@google.com49fdf182009-10-10 00:57:34 +0000345string XmlEncode(const string& input) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400346 gchar* escaped = g_markup_escape_text(input.c_str(), input.size());
347 string ret = string(escaped);
348 g_free(escaped);
349 return ret;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000350}
351
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800352OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700353 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700354 HttpFetcher* http_fetcher,
355 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800356 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700357 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700358 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700359 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700360 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700361 ping_roll_call_days_(0) {
362 params_ = system_state->request_params();
363}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000364
Darin Petkov6a5b3222010-07-13 14:55:28 -0700365OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000366
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700367// Calculates the value to use for the ping days parameter.
368int OmahaRequestAction::CalculatePingDays(const string& key) {
369 int days = kNeverPinged;
370 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800371 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700372 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
373 if (days < 0) {
374 // If |days| is negative, then the system clock must have jumped
375 // back in time since the ping was sent. Mark the value so that
376 // it doesn't get sent to the server but we still update the
377 // last ping daystart preference. This way the next ping time
378 // will be correct, hopefully.
379 days = kPingTimeJump;
380 LOG(WARNING) <<
381 "System clock jumped back in time. Resetting ping daystarts.";
382 }
383 }
384 return days;
385}
386
387void OmahaRequestAction::InitPingDays() {
388 // We send pings only along with update checks, not with events.
389 if (IsEvent()) {
390 return;
391 }
392 // TODO(petkov): Figure a way to distinguish active use pings
393 // vs. roll call pings. Currently, the two pings are identical. A
394 // fix needs to change this code as well as UpdateLastPingDays.
395 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
396 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
397}
398
David Zeuthen639aa362014-02-03 16:23:44 -0800399// static
400int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
401 PrefsInterface* prefs = system_state->prefs();
402 if (prefs == NULL)
403 return -1;
404
405 // If we have the value stored on disk, just return it.
406 int64_t stored_value;
407 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
408 // Convert and sanity-check.
409 int install_date_days = static_cast<int>(stored_value);
410 if (install_date_days >= 0)
411 return install_date_days;
412 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
413 << install_date_days << " looks suspicious.";
414 prefs->Delete(kPrefsInstallDateDays);
415 }
416
417 // Otherwise, if OOBE is not complete then do nothing and wait for
418 // ParseResponse() to call ParseInstallDate() and then
419 // PersistInstallDate() to set the kPrefsInstallDateDays state
420 // variable. Once that is done, we'll then report back in future
421 // Omaha requests. This works exactly because OOBE triggers an
422 // update check.
423 //
424 // However, if OOBE is complete and the kPrefsInstallDateDays state
425 // variable is not set, there are two possibilities
426 //
427 // 1. The update check in OOBE failed so we never got a response
428 // from Omaha (no network etc.); or
429 //
430 // 2. OOBE was done on an older version that didn't write to the
431 // kPrefsInstallDateDays state variable.
432 //
433 // In both cases, we approximate the install date by simply
434 // inspecting the timestamp of when OOBE happened.
435
436 Time time_of_oobe;
Alex Deymobccbc382014-04-03 13:38:55 -0700437 if (!system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800438 LOG(INFO) << "Not generating Omaha InstallData as we have "
439 << "no prefs file and OOBE is not complete.";
440 return -1;
441 }
442
443 int num_days;
444 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
445 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
446 << "as its value '" << utils::ToString(time_of_oobe)
447 << "' looks suspicious.";
448 return -1;
449 }
450
451 // Persist this to disk, for future use.
452 if (!OmahaRequestAction::PersistInstallDate(system_state,
453 num_days,
454 kProvisionedFromOOBEMarker))
455 return -1;
456
457 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
458 << num_days << " days";
459
460 return num_days;
461}
462
Darin Petkov6a5b3222010-07-13 14:55:28 -0700463void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000464 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700465 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700466 if (ping_only_ &&
467 !ShouldPing(ping_active_days_) &&
468 !ShouldPing(ping_roll_call_days_)) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700469 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700470 return;
471 }
David Zeuthen639aa362014-02-03 16:23:44 -0800472
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700473 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700474 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700475 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700476 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800477 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800478 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700479 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700480
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800481 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
482 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700483 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700484 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700485 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000486}
487
Darin Petkov6a5b3222010-07-13 14:55:28 -0700488void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000489 http_fetcher_->TerminateTransfer();
490}
491
492// We just store the response in the buffer. Once we've received all bytes,
493// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700494void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
495 const char* bytes,
496 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000497 response_buffer_.reserve(response_buffer_.size() + length);
498 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
499}
500
501namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000502
503// Parses a 64 bit base-10 int from a string and returns it. Returns 0
504// on error. If the string contains "0", that's indistinguishable from
505// error.
506off_t ParseInt(const string& str) {
507 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700508 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000509 if (rc < 1) {
510 // failure
511 return 0;
512 }
513 return ret;
514}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700515
David Zeuthene8ed8632014-07-24 13:38:10 -0400516// Parses |str| and returns |true| if, and only if, its value is "true".
517bool ParseBool(const string& str) {
518 return str == "true";
519}
520
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700521// Update the last ping day preferences based on the server daystart
522// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400523bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700524 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400525 TEST_AND_RETURN_FALSE(
526 base::StringToInt64(parser_data->daystart_elapsed_seconds,
527 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700528 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
529
530 // Remember the local time that matches the server's last midnight
531 // time.
532 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
533 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
534 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
535 return true;
536}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700537} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000538
David Zeuthene8ed8632014-07-24 13:38:10 -0400539bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700540 OmahaResponse* output_object,
541 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400542 if (parser_data->updatecheck_status.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700543 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700544 return false;
545 }
546
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800547 // chromium-os:37289: The PollInterval is not supported by Omaha server
548 // currently. But still keeping this existing code in case we ever decide to
549 // slow down the request rate from the server-side. Note that the
550 // PollInterval is not persisted, so it has to be sent by the server on every
551 // response to guarantee that the UpdateCheckScheduler uses this value
552 // (otherwise, if the device got rebooted after the last server-indicated
553 // value, it'll revert to the default value). Also kDefaultMaxUpdateChecks
554 // value for the scattering logic is based on the assumption that we perform
555 // an update check every hour so that the max value of 8 will roughly be
556 // equivalent to one work day. If we decide to use PollInterval permanently,
557 // we should update the max_update_checks_allowed to take PollInterval into
558 // account. Note: The parsing for PollInterval happens even before parsing
559 // of the status because we may want to specify the PollInterval even when
560 // there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400561 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700562 &output_object->poll_interval);
563
David Zeuthen639aa362014-02-03 16:23:44 -0800564 // Check for the "elapsed_days" attribute in the "daystart"
565 // element. This is the number of days since Jan 1 2007, 0:00
566 // PST. If we don't have a persisted value of the Omaha InstallDate,
567 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400568 if (ParseInstallDate(parser_data, output_object) &&
569 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800570 // Since output_object->install_date_days is never negative, the
571 // elapsed_days -> install-date calculation is reduced to simply
572 // rounding down to the nearest number divisible by 7.
573 int remainder = output_object->install_date_days % 7;
574 int install_date_days_rounded =
575 output_object->install_date_days - remainder;
576 if (PersistInstallDate(system_state_,
577 install_date_days_rounded,
578 kProvisionedFromOmahaResponse)) {
579 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
580 << install_date_days_rounded << " days";
581 }
582 }
583
David Zeuthene8ed8632014-07-24 13:38:10 -0400584 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700585 return false;
586
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800587 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
588 // appends the package name to the URLs populated in this method.
David Zeuthene8ed8632014-07-24 13:38:10 -0400589 if (!ParseUrls(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700590 return false;
591
David Zeuthene8ed8632014-07-24 13:38:10 -0400592 if (!ParsePackage(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700593 return false;
594
David Zeuthene8ed8632014-07-24 13:38:10 -0400595 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700596 return false;
597
598 return true;
599}
600
David Zeuthene8ed8632014-07-24 13:38:10 -0400601bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700602 OmahaResponse* output_object,
603 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400604 const string& status = parser_data->updatecheck_status;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700605 if (status == "noupdate") {
606 LOG(INFO) << "No update.";
607 output_object->update_exists = false;
608 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700609 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700610 return false;
611 }
612
613 if (status != "ok") {
614 LOG(ERROR) << "Unknown Omaha response status: " << status;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700615 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700616 return false;
617 }
618
619 return true;
620}
621
David Zeuthene8ed8632014-07-24 13:38:10 -0400622bool OmahaRequestAction::ParseUrls(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700623 OmahaResponse* output_object,
624 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400625 if (parser_data->url_codebase.empty()) {
626 LOG(ERROR) << "No Omaha Response URLs";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700627 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700628 return false;
629 }
630
David Zeuthene8ed8632014-07-24 13:38:10 -0400631 LOG(INFO) << "Found " << parser_data->url_codebase.size() << " url(s)";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800632 output_object->payload_urls.clear();
David Zeuthene8ed8632014-07-24 13:38:10 -0400633 for (const auto& codebase : parser_data->url_codebase) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800634 if (codebase.empty()) {
635 LOG(ERROR) << "Omaha Response URL has empty codebase";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700636 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800637 return false;
638 }
639 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700640 }
641
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700642 return true;
643}
644
David Zeuthene8ed8632014-07-24 13:38:10 -0400645bool OmahaRequestAction::ParsePackage(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700646 OmahaResponse* output_object,
647 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400648 if (parser_data->package_name.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700649 LOG(ERROR) << "Omaha Response has empty package name";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700650 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700651 return false;
652 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800653
654 // Append the package name to each URL in our list so that we don't
655 // propagate the urlBase vs packageName distinctions beyond this point.
656 // From now on, we only need to use payload_urls.
David Zeuthene8ed8632014-07-24 13:38:10 -0400657 for (auto& payload_url : output_object->payload_urls)
658 payload_url += parser_data->package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700659
660 // Parse the payload size.
David Zeuthene8ed8632014-07-24 13:38:10 -0400661 off_t size = ParseInt(parser_data->package_size);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700662 if (size <= 0) {
663 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700664 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700665 return false;
666 }
667 output_object->size = size;
668
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800669 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700670
671 return true;
672}
673
David Zeuthene8ed8632014-07-24 13:38:10 -0400674bool OmahaRequestAction::ParseParams(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 output_object->version = parser_data->manifest_version;
Chris Sosa3b748432013-06-20 16:42:59 -0700678 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700679 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700680 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700681 return false;
682 }
683
684 LOG(INFO) << "Received omaha response to update to version "
685 << output_object->version;
686
David Zeuthene8ed8632014-07-24 13:38:10 -0400687 map<string, string> attrs = parser_data->action_postinstall_attrs;
688 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700689 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700690 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700691 return false;
692 }
693
David Zeuthene8ed8632014-07-24 13:38:10 -0400694 output_object->hash = attrs[kTagSha256];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700695 if (output_object->hash.empty()) {
696 LOG(ERROR) << "Omaha Response has empty sha256 value";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700697 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700698 return false;
699 }
700
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800701 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -0400702 output_object->more_info_url = attrs[kTagMoreInfo];
703 output_object->metadata_size = ParseInt(attrs[kTagMetadataSize]);
704 output_object->metadata_signature = attrs[kTagMetadataSignatureRsa];
705 output_object->prompt = ParseBool(attrs[kTagPrompt]);
706 output_object->deadline = attrs[kTagDeadline];
707 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700708 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -0400709 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700710 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -0400711 ParseBool(attrs[kTagDisableP2PForSharing]);
712 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800713
David Zeuthene8ed8632014-07-24 13:38:10 -0400714 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800715 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800716 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700717
David Zeuthene8ed8632014-07-24 13:38:10 -0400718 output_object->is_delta_payload = ParseBool(attrs[kTagIsDeltaPayload]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800719
720 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -0400721 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800722
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700723 return true;
724}
725
David Zeuthene8ed8632014-07-24 13:38:10 -0400726// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000727// and fill in the appropriate fields of the output object. Also, notifies
728// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700729void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
730 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000731 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800732 string current_response(response_buffer_.begin(), response_buffer_.end());
733 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700734
735 // Events are best effort transactions -- assume they always succeed.
736 if (IsEvent()) {
737 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800738 if (event_->result == OmahaEvent::kResultError && successful &&
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700739 system_state_->hardware()->IsOfficialBuild()) {
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800740 LOG(INFO) << "Signalling Crash Reporter.";
741 utils::ScheduleCrashReporterUpload();
742 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700743 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700744 return;
745 }
746
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700747 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700748 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700749 int code = GetHTTPResponseCode();
750 // Makes sure we send sane error values.
751 if (code < 0 || code >= 1000) {
752 code = 999;
753 }
David Zeuthena99981f2013-04-29 13:42:47 -0700754 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700755 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000756 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700757 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000758
David Zeuthene8ed8632014-07-24 13:38:10 -0400759 XML_Parser parser = XML_ParserCreate(nullptr);
760 OmahaParserData parser_data;
761 XML_SetUserData(parser, &parser_data);
762 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
763 XML_Status res = XML_Parse(parser, &response_buffer_[0],
764 response_buffer_.size(), XML_TRUE);
765 XML_ParserFree(parser);
766
767 if (res != XML_STATUS_OK || parser_data.failed) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000768 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700769 completer.set_code(response_buffer_.empty() ?
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700770 ErrorCode::kOmahaRequestEmptyResponseError :
771 ErrorCode::kOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000772 return;
773 }
774
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700775 // If a ping was sent, update the last ping day preferences based on
776 // the server daystart response.
777 if (ShouldPing(ping_active_days_) ||
778 ShouldPing(ping_roll_call_days_) ||
779 ping_active_days_ == kPingTimeJump ||
780 ping_roll_call_days_ == kPingTimeJump) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400781 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700782 << "Failed to update the last ping day preferences!";
783 }
784
Thieu Le116fda32011-04-19 11:01:54 -0700785 if (!HasOutputPipe()) {
786 // Just set success to whether or not the http transfer succeeded,
787 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700788 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700789 return;
790 }
791
Darin Petkov6a5b3222010-07-13 14:55:28 -0700792 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400793 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000794 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700795 output_object.update_exists = true;
796 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000797
Chris Sosa77f79e82014-06-02 18:16:24 -0700798 if (ShouldIgnoreUpdate(output_object)) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700799 output_object.update_exists = false;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700800 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700801 return;
802 }
803
David Zeuthen8f191b22013-08-06 12:27:50 -0700804 // If Omaha says to disable p2p, respect that
805 if (output_object.disable_p2p_for_downloading) {
806 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
807 << "requested by Omaha.";
808 params_->set_use_p2p_for_downloading(false);
809 }
810 if (output_object.disable_p2p_for_sharing) {
811 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
812 << "requested by Omaha.";
813 params_->set_use_p2p_for_sharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700814 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800815
816 // Update the payload state with the current response. The payload state
817 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800818 // from what's stored already. We are updating the payload state as late
819 // as possible in this method so that if a new release gets pushed and then
820 // got pulled back due to some issues, we don't want to clear our internal
821 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800822 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800823 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800824
David Zeuthen8f191b22013-08-06 12:27:50 -0700825 // It could be we've already exceeded the deadline for when p2p is
826 // allowed or that we've tried too many times with p2p. Check that.
827 if (params_->use_p2p_for_downloading()) {
828 payload_state->P2PNewAttempt();
829 if (!payload_state->P2PAttemptAllowed()) {
830 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
831 << "of previous failures when using p2p.";
832 params_->set_use_p2p_for_downloading(false);
833 }
834 }
835
836 // From here on, we'll complete stuff in CompleteProcessing() so
837 // disable |completer| since we'll create a new one in that
838 // function.
839 completer.set_should_complete(false);
840
841 // If we're allowed to use p2p for downloading we do not pay
842 // attention to wall-clock-based waiting if the URL is indeed
843 // available via p2p. Therefore, check if the file is available via
844 // p2p before deferring...
845 if (params_->use_p2p_for_downloading()) {
846 LookupPayloadViaP2P(output_object);
847 } else {
848 CompleteProcessing();
849 }
850}
851
852void OmahaRequestAction::CompleteProcessing() {
853 ScopedActionCompleter completer(processor_, this);
854 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
855 PayloadStateInterface* payload_state = system_state_->payload_state();
856
857 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800858 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -0700859 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700860 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -0800861 return;
862 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700863
Chris Sosa20f005c2013-09-05 13:53:08 -0700864 if (payload_state->ShouldBackoffDownload()) {
865 output_object.update_exists = false;
866 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
867 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700868 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -0700869 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700870 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700871 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -0700872}
873
874void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
875 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
876 if (!url.empty()) {
877 params_->set_p2p_url(url);
878 } else {
879 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
880 << "because no suitable peer could be found.";
881 params_->set_use_p2p_for_downloading(false);
882 }
883 CompleteProcessing();
884}
885
886void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -0700887 // If the device is in the middle of an update, the state variables
888 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
889 // tracks the offset and length of the operation currently in
890 // progress. The offset is based from the end of the manifest which
891 // is kPrefsManifestMetadataSize bytes long.
892 //
893 // To make forward progress and avoid deadlocks, we need to find a
894 // peer that has at least the entire operation we're currently
895 // working on. Otherwise we may end up in a situation where two
896 // devices bounce back and forth downloading from each other,
897 // neither making any forward progress until one of them decides to
898 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
899 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -0700900 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -0700901 int64_t manifest_metadata_size = 0;
902 int64_t next_data_offset = 0;
903 int64_t next_data_length = 0;
David Zeuthen8f191b22013-08-06 12:27:50 -0700904 if (system_state_ != NULL &&
David Zeuthen41996ad2013-09-24 15:43:24 -0700905 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
906 &manifest_metadata_size) &&
907 manifest_metadata_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -0700908 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -0700909 &next_data_offset) &&
910 next_data_offset != -1 &&
911 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
912 &next_data_length)) {
913 minimum_size = manifest_metadata_size + next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -0700914 }
915
916 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
917 if (system_state_->p2p_manager() != NULL) {
918 LOG(INFO) << "Checking if payload is available via p2p, file_id="
919 << file_id << " minimum_size=" << minimum_size;
920 system_state_->p2p_manager()->LookupUrlForFile(
921 file_id,
922 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -0800923 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -0700924 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
925 base::Unretained(this)));
926 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000927}
928
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700929bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -0700930 if (params_->interactive()) {
931 LOG(INFO) << "Not deferring download because update is interactive.";
932 return false;
933 }
934
David Zeuthen8f191b22013-08-06 12:27:50 -0700935 // If we're using p2p to download _and_ we have a p2p URL, we never
936 // defer the download. This is because the download will always
937 // happen from a peer on the LAN and we've been waiting in line for
938 // our turn.
939 if (params_->use_p2p_for_downloading() && !params_->p2p_url().empty()) {
940 LOG(INFO) << "Download not deferred because download "
941 << "will happen from a local peer (via p2p).";
942 return false;
943 }
944
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700945 // We should defer the downloads only if we've first satisfied the
946 // wall-clock-based-waiting period and then the update-check-based waiting
947 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700948 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -0700949 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
950 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700951 return false;
952 }
953
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700954 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700955 case kWallClockWaitNotSatisfied:
956 // We haven't even satisfied the first condition, passing the
957 // wall-clock-based waiting period, so we should defer the downloads
958 // until that happens.
959 LOG(INFO) << "wall-clock-based-wait not satisfied.";
960 return true;
961
962 case kWallClockWaitDoneButUpdateCheckWaitRequired:
963 LOG(INFO) << "wall-clock-based-wait satisfied and "
964 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700965 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700966
967 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
968 // Wall-clock-based waiting period is satisfied, and it's determined
969 // that we do not need the update-check-based wait. so no need to
970 // defer downloads.
971 LOG(INFO) << "wall-clock-based-wait satisfied and "
972 << "update-check-based-wait is not required.";
973 return false;
974
975 default:
976 // Returning false for this default case so we err on the
977 // side of downloading updates than deferring in case of any bugs.
978 NOTREACHED();
979 return false;
980 }
981}
982
983OmahaRequestAction::WallClockWaitResult
984OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700985 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700986 Time update_first_seen_at;
987 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700988
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800989 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
990 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
991 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700992 // Note: This timestamp could be that of ANY update we saw in the past
993 // (not necessarily this particular update we're considering to apply)
994 // but never got to apply because of some reason (e.g. stop AU policy,
995 // updates being pulled out from Omaha, changes in target version prefix,
996 // new update being rolled out, etc.). But for the purposes of scattering
997 // it doesn't matter which update the timestamp corresponds to. i.e.
998 // the clock starts ticking the first time we see an update and we're
999 // ready to apply when the random wait period is satisfied relative to
1000 // that first seen timestamp.
1001 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1002 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1003 << utils::ToString(update_first_seen_at);
1004 } else {
1005 // This seems like an unexpected error where the persisted value exists
1006 // but it's not readable for some reason. Just skip scattering in this
1007 // case to be safe.
1008 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1009 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1010 }
1011 } else {
1012 update_first_seen_at = Time::Now();
1013 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001014 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1015 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001016 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1017 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001018 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001019 // This seems like an unexpected error where the value cannot be
1020 // persisted for some reason. Just skip scattering in this
1021 // case to be safe.
1022 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1023 << utils::ToString(update_first_seen_at)
1024 << " cannot be persisted";
1025 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1026 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001027 }
1028
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001029 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001030 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001031 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001032
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001033 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001034 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001035 << ", Time Elapsed = "
1036 << utils::FormatSecs(elapsed_time.InSeconds())
1037 << ", MaxDaysToScatter = "
1038 << max_scatter_period.InDays();
1039
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001040 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001041 // The deadline is set for all rules which serve a delta update from a
1042 // previous FSI, which means this update will be applied mostly in OOBE
1043 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1044 // quickly.
1045 LOG(INFO) << "Not scattering as deadline flag is set";
1046 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1047 }
1048
1049 if (max_scatter_period.InDays() == 0) {
1050 // This means the Omaha rule creator decides that this rule
1051 // should not be scattered irrespective of the policy.
1052 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1053 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1054 }
1055
1056 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001057 // This means we've waited more than the upperbound wait in the rule
1058 // from the time we first saw a valid update available to us.
1059 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001060 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1061 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1062 }
1063
1064 // This means we are required to participate in scattering.
1065 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001066 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001067 if (remaining_wait_time.InSeconds() <= 0) {
1068 // Yes, it's our turn now.
1069 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1070
1071 // But we can't download until the update-check-count-based wait is also
1072 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001073 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001074 kWallClockWaitDoneButUpdateCheckWaitRequired :
1075 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1076 }
1077
1078 // Not our turn yet, so we have to wait until our turn to
1079 // help scatter the downloads across all clients of the enterprise.
1080 LOG(INFO) << "Update deferred for another "
1081 << utils::FormatSecs(remaining_wait_time.InSeconds())
1082 << " per policy.";
1083 return kWallClockWaitNotSatisfied;
1084}
1085
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001086bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001087 int64 update_check_count_value;
1088
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001089 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1090 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1091 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001092 // We are unable to read the update check count from file for some reason.
1093 // So let's proceed anyway so as to not stall the update.
1094 LOG(ERROR) << "Unable to read update check count. "
1095 << "Skipping update-check-count-based-wait.";
1096 return true;
1097 }
1098 } else {
1099 // This file does not exist. This means we haven't started our update
1100 // check count down yet, so this is the right time to start the count down.
1101 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001102 params_->min_update_checks_needed(),
1103 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001104
1105 LOG(INFO) << "Randomly picked update check count value = "
1106 << update_check_count_value;
1107
1108 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001109 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1110 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001111 // We weren't able to write the update check count file for some reason.
1112 // So let's proceed anyway so as to not stall the update.
1113 LOG(ERROR) << "Unable to write update check count. "
1114 << "Skipping update-check-count-based-wait.";
1115 return true;
1116 }
1117 }
1118
1119 if (update_check_count_value == 0) {
1120 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1121 return true;
1122 }
1123
1124 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001125 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001126 // We err on the side of skipping scattering logic instead of stalling
1127 // a machine from receiving any updates in case of any unexpected state.
1128 LOG(ERROR) << "Invalid value for update check count detected. "
1129 << "Skipping update-check-count-based-wait.";
1130 return true;
1131 }
1132
1133 // Legal value, we need to wait for more update checks to happen
1134 // until this becomes 0.
1135 LOG(INFO) << "Deferring Omaha updates for another "
1136 << update_check_count_value
1137 << " update checks per policy";
1138 return false;
1139}
1140
David Zeuthen639aa362014-02-03 16:23:44 -08001141// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001142bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001143 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001144 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001145 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001146 &elapsed_days))
1147 return false;
1148
1149 if (elapsed_days < 0)
1150 return false;
1151
1152 output_object->install_date_days = elapsed_days;
1153 return true;
1154}
1155
1156// static
1157bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1158 PrefsInterface* prefs = system_state->prefs();
1159 if (prefs == NULL)
1160 return false;
1161
1162 return prefs->Exists(kPrefsInstallDateDays);
1163}
1164
1165// static
1166bool OmahaRequestAction::PersistInstallDate(
1167 SystemState *system_state,
1168 int install_date_days,
1169 InstallDateProvisioningSource source) {
1170 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1171
1172 PrefsInterface* prefs = system_state->prefs();
1173 if (prefs == NULL)
1174 return false;
1175
1176 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1177 return false;
1178
1179 string metric_name = "Installer.InstallDateProvisioningSource";
1180 system_state->metrics_lib()->SendEnumToUMA(
1181 metric_name,
David Zeuthen33bae492014-02-25 16:16:18 -08001182 static_cast<int>(source), // Sample.
1183 kProvisionedMax); // Maximum.
1184
1185 metric_name = metrics::kMetricInstallDateProvisioningSource;
1186 system_state->metrics_lib()->SendEnumToUMA(
1187 metric_name,
1188 static_cast<int>(source), // Sample.
1189 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001190
1191 return true;
1192}
1193
David Zeuthen33bae492014-02-25 16:16:18 -08001194void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1195 // We only want to report this on "update check".
1196 if (ping_only_ || event_ != nullptr)
1197 return;
1198
1199 metrics::CheckResult result = metrics::CheckResult::kUnset;
1200 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1201 metrics::DownloadErrorCode download_error_code =
1202 metrics::DownloadErrorCode::kUnset;
1203
1204 // Regular update attempt.
1205 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001206 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001207 // OK, we parsed the response successfully but that does
1208 // necessarily mean that an update is available.
1209 if (HasOutputPipe()) {
1210 const OmahaResponse& response = GetOutputObject();
1211 if (response.update_exists) {
1212 result = metrics::CheckResult::kUpdateAvailable;
1213 reaction = metrics::CheckReaction::kUpdating;
1214 } else {
1215 result = metrics::CheckResult::kNoUpdateAvailable;
1216 }
1217 } else {
1218 result = metrics::CheckResult::kNoUpdateAvailable;
1219 }
1220 break;
1221
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001222 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001223 result = metrics::CheckResult::kUpdateAvailable;
1224 reaction = metrics::CheckReaction::kIgnored;
1225 break;
1226
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001227 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001228 result = metrics::CheckResult::kUpdateAvailable;
1229 reaction = metrics::CheckReaction::kDeferring;
1230 break;
1231
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001232 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001233 result = metrics::CheckResult::kUpdateAvailable;
1234 reaction = metrics::CheckReaction::kBackingOff;
1235 break;
1236
1237 default:
1238 // We report two flavors of errors, "Download errors" and "Parsing
1239 // error". Try to convert to the former and if that doesn't work
1240 // we know it's the latter.
1241 metrics::DownloadErrorCode tmp_error = utils::GetDownloadErrorCode(code);
1242 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1243 result = metrics::CheckResult::kDownloadError;
1244 download_error_code = tmp_error;
1245 } else {
1246 result = metrics::CheckResult::kParsingError;
1247 }
1248 break;
1249 }
1250
1251 metrics::ReportUpdateCheckMetrics(system_state_,
1252 result, reaction, download_error_code);
1253}
1254
Chris Sosa77f79e82014-06-02 18:16:24 -07001255bool OmahaRequestAction::ShouldIgnoreUpdate(
1256 const OmahaResponse& response) const {
1257 if (params_->update_disabled()) {
1258 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
1259 return true;
1260 }
1261
1262 // Note: policy decision to not update to a version we rolled back from.
1263 string rollback_version =
1264 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001265 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001266 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001267 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001268 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1269 return true;
1270 }
1271 }
1272
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001273 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001274 LOG(INFO) << "Update is not allowed over current connection.";
1275 return true;
1276 }
1277
1278 // Note: We could technically delete the UpdateFirstSeenAt state when we
1279 // return true. If we do, it'll mean a device has to restart the
1280 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1281 // turned on again. On the other hand, it also increases the chance of update
1282 // starvation if an admin turns AU on/off more frequently. We choose to err on
1283 // the side of preventing starvation at the cost of not applying scattering in
1284 // those cases.
1285 return false;
1286}
1287
1288bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
1289 NetworkConnectionType type;
1290 NetworkTethering tethering;
1291 RealDBusWrapper dbus_iface;
1292 ConnectionManager* connection_manager = system_state_->connection_manager();
1293 if (!connection_manager->GetConnectionProperties(&dbus_iface,
1294 &type, &tethering)) {
1295 LOG(INFO) << "We could not determine our connection type. "
1296 << "Defaulting to allow updates.";
1297 return true;
1298 }
1299 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1300 LOG(INFO) << "We are connected via "
1301 << connection_manager->StringForConnectionType(type)
1302 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1303 return is_allowed;
1304}
1305
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001306} // namespace chromeos_update_engine