blob: c706a165ccd770fb631176bcfc2f68b6a08adfec [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
rspangler@google.com49fdf182009-10-10 00:57:34 +00009#include <sstream>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070010#include <string>
rspangler@google.com49fdf182009-10-10 00:57:34 +000011
David Zeuthen8f191b22013-08-06 12:27:50 -070012#include <base/bind.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070013#include <base/logging.h>
14#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070015#include <base/strings/string_number_conversions.h>
16#include <base/strings/string_util.h>
17#include <base/strings/stringprintf.h>
18#include <base/time/time.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000019#include <libxml/xpath.h>
20#include <libxml/xpathInternals.h>
21
22#include "update_engine/action_pipe.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070023#include "update_engine/constants.h"
J. Richard Barnette056b0ab2013-10-29 15:24:56 -070024#include "update_engine/hardware_interface.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070025#include "update_engine/omaha_hash_calculator.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070026#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070027#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080028#include "update_engine/payload_state_interface.h"
Darin Petkov1cbd78f2010-07-29 12:38:34 -070029#include "update_engine/prefs_interface.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000030#include "update_engine/utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000031
Darin Petkov1cbd78f2010-07-29 12:38:34 -070032using base::Time;
33using base::TimeDelta;
rspangler@google.com49fdf182009-10-10 00:57:34 +000034using std::string;
35
36namespace chromeos_update_engine {
37
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080038// List of custom pair tags that we interpret in the Omaha Response:
39static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080040static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070041static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080042// Deprecated: "IsDelta"
43static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080044static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
45static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
46// Deprecated: "ManifestSignatureRsa"
47// Deprecated: "ManifestSize"
48static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
49static const char* kTagMetadataSize = "MetadataSize";
50static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070051// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080052static const char* kTagPrompt = "Prompt";
53static const char* kTagSha256 = "sha256";
David Zeuthen8f191b22013-08-06 12:27:50 -070054static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
55static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
David Zeuthene7f89172013-10-31 10:21:04 -070056static const char* kTagPublicKeyRsa = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080057
rspangler@google.com49fdf182009-10-10 00:57:34 +000058namespace {
59
60const string kGupdateVersion("ChromeOSUpdateEngine-0.1.0.0");
61
62// This is handy for passing strings into libxml2
63#define ConstXMLStr(x) (reinterpret_cast<const xmlChar*>(x))
64
65// These are for scoped_ptr_malloc, which is like scoped_ptr, but allows
66// a custom free() function to be specified.
67class ScopedPtrXmlDocFree {
68 public:
69 inline void operator()(void* x) const {
70 xmlFreeDoc(reinterpret_cast<xmlDoc*>(x));
71 }
72};
73class ScopedPtrXmlFree {
74 public:
75 inline void operator()(void* x) const {
76 xmlFree(x);
77 }
78};
79class ScopedPtrXmlXPathObjectFree {
80 public:
81 inline void operator()(void* x) const {
82 xmlXPathFreeObject(reinterpret_cast<xmlXPathObject*>(x));
83 }
84};
85class ScopedPtrXmlXPathContextFree {
86 public:
87 inline void operator()(void* x) const {
88 xmlXPathFreeContext(reinterpret_cast<xmlXPathContext*>(x));
89 }
90};
91
Darin Petkov1cbd78f2010-07-29 12:38:34 -070092// Returns true if |ping_days| has a value that needs to be sent,
93// false otherwise.
94bool ShouldPing(int ping_days) {
95 return ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged;
96}
97
98// Returns an XML ping element attribute assignment with attribute
99// |name| and value |ping_days| if |ping_days| has a value that needs
100// to be sent, or an empty string otherwise.
101string GetPingAttribute(const string& name, int ping_days) {
102 if (ShouldPing(ping_days)) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700103 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700104 }
105 return "";
106}
107
108// Returns an XML ping element if any of the elapsed days need to be
109// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700110string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700111 string ping_active = GetPingAttribute("a", ping_active_days);
112 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
113 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700114 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700115 ping_active.c_str(),
116 ping_roll_call.c_str());
117 }
118 return "";
119}
120
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700121// Returns an XML that goes into the body of the <app> element of the Omaha
122// request based on the given parameters.
123string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700124 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700125 bool ping_only,
126 int ping_active_days,
127 int ping_roll_call_days,
128 PrefsInterface* prefs) {
129 string app_body;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700130 if (event == NULL) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700131 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700132 if (!ping_only) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700133 // not passing update_disabled to Omaha because we want to
134 // get the update and report with UpdateDeferred result so that
135 // borgmon charts show up updates that are deferred. This is also
136 // the expected behavior when we move to Omaha v3.0 protocol, so it'll
137 // be consistent.
Alex Vakulenko75039d72014-03-25 12:36:28 -0700138 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700139 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700140 "></updatecheck>\n",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700141 XmlEncode(params->target_version_prefix()).c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700142
Darin Petkov265f2902011-05-09 15:17:40 -0700143 // If this is the first update check after a reboot following a previous
144 // update, generate an event containing the previous version number. If
145 // the previous version preference file doesn't exist the event is still
146 // generated with a previous version of 0.0.0.0 -- this is relevant for
147 // older clients or new installs. The previous version event is not sent
148 // for ping-only requests because they come before the client has
149 // rebooted.
150 string prev_version;
151 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
152 prev_version = "0.0.0.0";
153 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700154
Alex Vakulenko75039d72014-03-25 12:36:28 -0700155 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700156 " <event eventtype=\"%d\" eventresult=\"%d\" "
157 "previousversion=\"%s\"></event>\n",
158 OmahaEvent::kTypeUpdateComplete,
159 OmahaEvent::kResultSuccessReboot,
160 XmlEncode(prev_version).c_str());
161 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
162 << "Unable to reset the previous version.";
Darin Petkov95508da2011-01-05 12:42:29 -0800163 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700164 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800165 // The error code is an optional attribute so append it only if the result
166 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700167 string error_code;
168 if (event->result != OmahaEvent::kResultSuccess) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700169 error_code = base::StringPrintf(" errorcode=\"%d\"", event->error_code);
Darin Petkove17f86b2010-07-20 09:12:01 -0700170 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700171 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700172 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700173 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700174 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700175
176 return app_body;
177}
178
179// Returns an XML that corresponds to the entire <app> node of the Omaha
180// request based on the given parameters.
181string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700182 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700183 bool ping_only,
184 int ping_active_days,
185 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800186 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700187 SystemState* system_state) {
188 string app_body = GetAppBody(event, params, ping_only, ping_active_days,
189 ping_roll_call_days, system_state->prefs());
190 string app_versions;
191
192 // If we are upgrading to a more stable channel and we are allowed to do
193 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
194 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700195 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700196 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
197 << "on downgrading to the version in the more stable channel";
198 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700199 XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700200 } else {
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700201 app_versions = "version=\"" + XmlEncode(params->app_version()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700202 }
203
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700204 string download_channel = params->download_channel();
205 string app_channels = "track=\"" + XmlEncode(download_channel) + "\" ";
206 if (params->current_channel() != download_channel)
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700207 app_channels +=
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700208 "from_track=\"" + XmlEncode(params->current_channel()) + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700209
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700210 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700211
David Zeuthen639aa362014-02-03 16:23:44 -0800212 // If install_date_days is not set (e.g. its value is -1 ), don't
213 // include the attribute.
214 string install_date_in_days_str = "";
215 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700216 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
217 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800218 }
219
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700220 string app_xml =
Jay Srinivasandb0acdf2013-04-02 14:47:45 -0700221 " <app appid=\"" + XmlEncode(params->GetAppId()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700222 app_versions +
223 app_channels +
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700224 "lang=\"" + XmlEncode(params->app_lang()) + "\" " +
225 "board=\"" + XmlEncode(params->os_board()) + "\" " +
226 "hardware_class=\"" + XmlEncode(params->hwid()) + "\" " +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700227 "delta_okay=\"" + delta_okay_str + "\" "
Chris Sosac1972482013-04-30 22:31:10 -0700228 "fw_version=\"" + XmlEncode(params->fw_version()) + "\" " +
229 "ec_version=\"" + XmlEncode(params->ec_version()) + "\" " +
David Zeuthen639aa362014-02-03 16:23:44 -0800230 install_date_in_days_str +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700231 ">\n" +
232 app_body +
233 " </app>\n";
234
235 return app_xml;
236}
237
238// Returns an XML that corresponds to the entire <os> node of the Omaha
239// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700240string GetOsXml(OmahaRequestParams* params) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700241 string os_xml =
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700242 " <os version=\"" + XmlEncode(params->os_version()) + "\" " +
243 "platform=\"" + XmlEncode(params->os_platform()) + "\" " +
244 "sp=\"" + XmlEncode(params->os_sp()) + "\">"
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700245 "</os>\n";
246 return os_xml;
247}
248
249// Returns an XML that corresponds to the entire Omaha request based on the
250// given parameters.
251string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700252 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700253 bool ping_only,
254 int ping_active_days,
255 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800256 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700257 SystemState* system_state) {
258 string os_xml = GetOsXml(params);
259 string app_xml = GetAppXml(event, params, ping_only, ping_active_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800260 ping_roll_call_days, install_date_in_days,
261 system_state);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700262
Alex Vakulenko75039d72014-03-25 12:36:28 -0700263 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700264 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700265
266 string request_xml =
267 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700268 "<request protocol=\"3.0\" "
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700269 "version=\"" + XmlEncode(kGupdateVersion) + "\" "
270 "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" " +
271 install_source +
272 "ismachine=\"1\">\n" +
273 os_xml +
274 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700275 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700276
277 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000278}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700279
rspangler@google.com49fdf182009-10-10 00:57:34 +0000280} // namespace {}
281
282// Encodes XML entities in a given string with libxml2. input must be
283// UTF-8 formatted. Output will be UTF-8 formatted.
284string XmlEncode(const string& input) {
Darin Petkov6a5b3222010-07-13 14:55:28 -0700285 // // TODO(adlr): if allocating a new xmlDoc each time is taking up too much
286 // // cpu, considering creating one and caching it.
287 // scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> xml_doc(
288 // xmlNewDoc(ConstXMLStr("1.0")));
289 // if (!xml_doc.get()) {
290 // LOG(ERROR) << "Unable to create xmlDoc";
291 // return "";
292 // }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000293 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
294 xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str())));
295 return string(reinterpret_cast<const char *>(str.get()));
296}
297
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800298OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700299 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700300 HttpFetcher* http_fetcher,
301 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800302 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700303 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700304 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700305 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700306 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700307 ping_roll_call_days_(0) {
308 params_ = system_state->request_params();
309}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000310
Darin Petkov6a5b3222010-07-13 14:55:28 -0700311OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000312
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700313// Calculates the value to use for the ping days parameter.
314int OmahaRequestAction::CalculatePingDays(const string& key) {
315 int days = kNeverPinged;
316 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800317 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700318 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
319 if (days < 0) {
320 // If |days| is negative, then the system clock must have jumped
321 // back in time since the ping was sent. Mark the value so that
322 // it doesn't get sent to the server but we still update the
323 // last ping daystart preference. This way the next ping time
324 // will be correct, hopefully.
325 days = kPingTimeJump;
326 LOG(WARNING) <<
327 "System clock jumped back in time. Resetting ping daystarts.";
328 }
329 }
330 return days;
331}
332
333void OmahaRequestAction::InitPingDays() {
334 // We send pings only along with update checks, not with events.
335 if (IsEvent()) {
336 return;
337 }
338 // TODO(petkov): Figure a way to distinguish active use pings
339 // vs. roll call pings. Currently, the two pings are identical. A
340 // fix needs to change this code as well as UpdateLastPingDays.
341 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
342 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
343}
344
David Zeuthen639aa362014-02-03 16:23:44 -0800345// static
346int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
347 PrefsInterface* prefs = system_state->prefs();
348 if (prefs == NULL)
349 return -1;
350
351 // If we have the value stored on disk, just return it.
352 int64_t stored_value;
353 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
354 // Convert and sanity-check.
355 int install_date_days = static_cast<int>(stored_value);
356 if (install_date_days >= 0)
357 return install_date_days;
358 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
359 << install_date_days << " looks suspicious.";
360 prefs->Delete(kPrefsInstallDateDays);
361 }
362
363 // Otherwise, if OOBE is not complete then do nothing and wait for
364 // ParseResponse() to call ParseInstallDate() and then
365 // PersistInstallDate() to set the kPrefsInstallDateDays state
366 // variable. Once that is done, we'll then report back in future
367 // Omaha requests. This works exactly because OOBE triggers an
368 // update check.
369 //
370 // However, if OOBE is complete and the kPrefsInstallDateDays state
371 // variable is not set, there are two possibilities
372 //
373 // 1. The update check in OOBE failed so we never got a response
374 // from Omaha (no network etc.); or
375 //
376 // 2. OOBE was done on an older version that didn't write to the
377 // kPrefsInstallDateDays state variable.
378 //
379 // In both cases, we approximate the install date by simply
380 // inspecting the timestamp of when OOBE happened.
381
382 Time time_of_oobe;
383 if (!system_state->IsOOBEComplete(&time_of_oobe)) {
384 LOG(INFO) << "Not generating Omaha InstallData as we have "
385 << "no prefs file and OOBE is not complete.";
386 return -1;
387 }
388
389 int num_days;
390 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
391 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
392 << "as its value '" << utils::ToString(time_of_oobe)
393 << "' looks suspicious.";
394 return -1;
395 }
396
397 // Persist this to disk, for future use.
398 if (!OmahaRequestAction::PersistInstallDate(system_state,
399 num_days,
400 kProvisionedFromOOBEMarker))
401 return -1;
402
403 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
404 << num_days << " days";
405
406 return num_days;
407}
408
Darin Petkov6a5b3222010-07-13 14:55:28 -0700409void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000410 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700411 InitPingDays();
Thieu Leb44e9e82011-06-06 14:34:04 -0700412 if (ping_only_ &&
413 !ShouldPing(ping_active_days_) &&
414 !ShouldPing(ping_roll_call_days_)) {
David Zeuthena99981f2013-04-29 13:42:47 -0700415 processor_->ActionComplete(this, kErrorCodeSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700416 return;
417 }
David Zeuthen639aa362014-02-03 16:23:44 -0800418
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700419 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700420 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700421 ping_only_,
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700422 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800423 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800424 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700425 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700426
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800427 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
428 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700429 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700430 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700431 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000432}
433
Darin Petkov6a5b3222010-07-13 14:55:28 -0700434void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000435 http_fetcher_->TerminateTransfer();
436}
437
438// We just store the response in the buffer. Once we've received all bytes,
439// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700440void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
441 const char* bytes,
442 int length) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000443 response_buffer_.reserve(response_buffer_.size() + length);
444 response_buffer_.insert(response_buffer_.end(), bytes, bytes + length);
445}
446
447namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000448// If non-NULL response, caller is responsible for calling xmlXPathFreeObject()
449// on the returned object.
450// This code is roughly based on the libxml tutorial at:
451// http://xmlsoft.org/tutorial/apd.html
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700452xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000453 xmlXPathObject* result = NULL;
454
455 scoped_ptr_malloc<xmlXPathContext, ScopedPtrXmlXPathContextFree> context(
456 xmlXPathNewContext(doc));
457 if (!context.get()) {
458 LOG(ERROR) << "xmlXPathNewContext() returned NULL";
459 return NULL;
460 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000461
462 result = xmlXPathEvalExpression(xpath, context.get());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000463 if (result == NULL) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700464 LOG(ERROR) << "Unable to find " << xpath << " in XML document";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000465 return NULL;
466 }
467 if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700468 LOG(INFO) << "Nodeset is empty for " << xpath;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000469 xmlXPathFreeObject(result);
470 return NULL;
471 }
472 return result;
473}
474
475// Returns the string value of a named attribute on a node, or empty string
476// if no such node exists. If the attribute exists and has a value of
477// empty string, there's no way to distinguish that from the attribute
478// not existing.
479string XmlGetProperty(xmlNode* node, const char* name) {
480 if (!xmlHasProp(node, ConstXMLStr(name)))
481 return "";
482 scoped_ptr_malloc<xmlChar, ScopedPtrXmlFree> str(
483 xmlGetProp(node, ConstXMLStr(name)));
484 string ret(reinterpret_cast<const char *>(str.get()));
485 return ret;
486}
487
488// Parses a 64 bit base-10 int from a string and returns it. Returns 0
489// on error. If the string contains "0", that's indistinguishable from
490// error.
491off_t ParseInt(const string& str) {
492 off_t ret = 0;
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700493 int rc = sscanf(str.c_str(), "%" PRIi64, &ret);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000494 if (rc < 1) {
495 // failure
496 return 0;
497 }
498 return ret;
499}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700500
501// Update the last ping day preferences based on the server daystart
502// response. Returns true on success, false otherwise.
503bool UpdateLastPingDays(xmlDoc* doc, PrefsInterface* prefs) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700504 static const char kDaystartNodeXpath[] = "/response/daystart";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700505
506 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700507 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kDaystartNodeXpath)));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700508 TEST_AND_RETURN_FALSE(xpath_nodeset.get());
509 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
510 TEST_AND_RETURN_FALSE(nodeset && nodeset->nodeNr >= 1);
511 xmlNode* daystart_node = nodeset->nodeTab[0];
512 TEST_AND_RETURN_FALSE(xmlHasProp(daystart_node,
513 ConstXMLStr("elapsed_seconds")));
514
515 int64_t elapsed_seconds = 0;
Chris Masone790e62e2010-08-12 10:41:18 -0700516 TEST_AND_RETURN_FALSE(base::StringToInt64(XmlGetProperty(daystart_node,
517 "elapsed_seconds"),
518 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700519 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
520
521 // Remember the local time that matches the server's last midnight
522 // time.
523 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
524 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
525 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
526 return true;
527}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000528} // namespace {}
529
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700530bool OmahaRequestAction::ParseResponse(xmlDoc* doc,
531 OmahaResponse* output_object,
532 ScopedActionCompleter* completer) {
533 static const char* kUpdatecheckNodeXpath("/response/app/updatecheck");
534
535 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
536 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath)));
537 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700538 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700539 return false;
540 }
541
542 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
543 CHECK(nodeset) << "XPath missing UpdateCheck NodeSet";
544 CHECK_GE(nodeset->nodeNr, 1);
545 xmlNode* update_check_node = nodeset->nodeTab[0];
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.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700561 base::StringToInt(XmlGetProperty(update_check_node, "PollInterval"),
562 &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.
568 if (ParseInstallDate(doc, output_object) && !HasInstallDate(system_state_)) {
569 // Since output_object->install_date_days is never negative, the
570 // elapsed_days -> install-date calculation is reduced to simply
571 // rounding down to the nearest number divisible by 7.
572 int remainder = output_object->install_date_days % 7;
573 int install_date_days_rounded =
574 output_object->install_date_days - remainder;
575 if (PersistInstallDate(system_state_,
576 install_date_days_rounded,
577 kProvisionedFromOmahaResponse)) {
578 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
579 << install_date_days_rounded << " days";
580 }
581 }
582
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700583 if (!ParseStatus(update_check_node, output_object, completer))
584 return false;
585
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800586 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
587 // appends the package name to the URLs populated in this method.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700588 if (!ParseUrls(doc, output_object, completer))
589 return false;
590
591 if (!ParsePackage(doc, output_object, completer))
592 return false;
593
594 if (!ParseParams(doc, output_object, completer))
595 return false;
596
597 return true;
598}
599
600bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node,
601 OmahaResponse* output_object,
602 ScopedActionCompleter* completer) {
603 // Get status.
604 if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) {
605 LOG(ERROR) << "Omaha Response missing status";
David Zeuthena99981f2013-04-29 13:42:47 -0700606 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700607 return false;
608 }
609
610 const string status(XmlGetProperty(update_check_node, "status"));
611 if (status == "noupdate") {
612 LOG(INFO) << "No update.";
613 output_object->update_exists = false;
614 SetOutputObject(*output_object);
David Zeuthena99981f2013-04-29 13:42:47 -0700615 completer->set_code(kErrorCodeSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700616 return false;
617 }
618
619 if (status != "ok") {
620 LOG(ERROR) << "Unknown Omaha response status: " << status;
David Zeuthena99981f2013-04-29 13:42:47 -0700621 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700622 return false;
623 }
624
625 return true;
626}
627
628bool OmahaRequestAction::ParseUrls(xmlDoc* doc,
629 OmahaResponse* output_object,
630 ScopedActionCompleter* completer) {
631 // Get the update URL.
632 static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url");
633
634 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
635 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath)));
636 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700637 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700638 return false;
639 }
640
641 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
642 CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath;
643 CHECK_GE(nodeset->nodeNr, 1);
644
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800645 LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)";
646 output_object->payload_urls.clear();
647 for (int i = 0; i < nodeset->nodeNr; i++) {
648 xmlNode* url_node = nodeset->nodeTab[i];
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800649 const string codebase(XmlGetProperty(url_node, "codebase"));
650 if (codebase.empty()) {
651 LOG(ERROR) << "Omaha Response URL has empty codebase";
David Zeuthena99981f2013-04-29 13:42:47 -0700652 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800653 return false;
654 }
655 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700656 }
657
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700658 return true;
659}
660
661bool OmahaRequestAction::ParsePackage(xmlDoc* doc,
662 OmahaResponse* output_object,
663 ScopedActionCompleter* completer) {
664 // Get the package node.
665 static const char* kPackageNodeXPath(
666 "/response/app/updatecheck/manifest/packages/package");
667
668 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
669 xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath)));
670 if (!xpath_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700671 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700672 return false;
673 }
674
675 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
676 CHECK(nodeset) << "XPath missing " << kPackageNodeXPath;
677 CHECK_GE(nodeset->nodeNr, 1);
678
679 // We only care about the first package.
680 LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)";
681 xmlNode* package_node = nodeset->nodeTab[0];
682
683 // Get package properties one by one.
684
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800685 // Parse the payload name to be appended to the base Url value.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700686 const string package_name(XmlGetProperty(package_node, "name"));
687 LOG(INFO) << "Omaha Response package name = " << package_name;
688 if (package_name.empty()) {
689 LOG(ERROR) << "Omaha Response has empty package name";
David Zeuthena99981f2013-04-29 13:42:47 -0700690 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700691 return false;
692 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800693
694 // Append the package name to each URL in our list so that we don't
695 // propagate the urlBase vs packageName distinctions beyond this point.
696 // From now on, we only need to use payload_urls.
Jay Srinivasan53173b92013-05-17 17:13:01 -0700697 for (size_t i = 0; i < output_object->payload_urls.size(); i++)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800698 output_object->payload_urls[i] += package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700699
700 // Parse the payload size.
701 off_t size = ParseInt(XmlGetProperty(package_node, "size"));
702 if (size <= 0) {
703 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
David Zeuthena99981f2013-04-29 13:42:47 -0700704 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700705 return false;
706 }
707 output_object->size = size;
708
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800709 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700710
711 return true;
712}
713
714bool OmahaRequestAction::ParseParams(xmlDoc* doc,
715 OmahaResponse* output_object,
716 ScopedActionCompleter* completer) {
Chris Sosa3b748432013-06-20 16:42:59 -0700717 // XPath location for response elements we care about.
718 static const char* kManifestNodeXPath("/response/app/updatecheck/manifest");\
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700719 static const char* kActionNodeXPath(
Chris Sosa3b748432013-06-20 16:42:59 -0700720 "/response/app/updatecheck/manifest/actions/action");
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700721
Chris Sosa3b748432013-06-20 16:42:59 -0700722 // Get the manifest node where version is present.
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700723 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
Chris Sosa3b748432013-06-20 16:42:59 -0700724 xpath_manifest_nodeset(GetNodeSet(doc, ConstXMLStr(kManifestNodeXPath)));
725 if (!xpath_manifest_nodeset.get()) {
David Zeuthena99981f2013-04-29 13:42:47 -0700726 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700727 return false;
728 }
729
Chris Sosa3b748432013-06-20 16:42:59 -0700730 // Grab the only matching node there should be from the xpath.
731 xmlNodeSet* nodeset = xpath_manifest_nodeset->nodesetval;
732 CHECK(nodeset) << "XPath missing " << kManifestNodeXPath;
733 CHECK_GE(nodeset->nodeNr, 1);
734 xmlNode* manifest_node = nodeset->nodeTab[0];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700735
Chris Sosa3b748432013-06-20 16:42:59 -0700736 // Set the version.
737 output_object->version = XmlGetProperty(manifest_node, kTagVersion);
738 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700739 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Chris Sosa3b748432013-06-20 16:42:59 -0700740 completer->set_code(kErrorCodeOmahaResponseInvalid);
741 return false;
742 }
743
744 LOG(INFO) << "Received omaha response to update to version "
745 << output_object->version;
746
747 // Grab the action nodes.
748 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
749 xpath_action_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath)));
750 if (!xpath_action_nodeset.get()) {
751 completer->set_code(kErrorCodeOmahaResponseInvalid);
752 return false;
753 }
754
755 // We only care about the action that has event "postinstall", because this is
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700756 // where Omaha puts all the generic name/value pairs in the rule.
Chris Sosa3b748432013-06-20 16:42:59 -0700757 nodeset = xpath_action_nodeset->nodesetval;
758 CHECK(nodeset) << "XPath missing " << kActionNodeXPath;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700759 LOG(INFO) << "Found " << nodeset->nodeNr
760 << " action(s). Processing the postinstall action.";
761
762 // pie_action_node holds the action node corresponding to the
763 // postinstall event action, if present.
764 xmlNode* pie_action_node = NULL;
765 for (int i = 0; i < nodeset->nodeNr; i++) {
766 xmlNode* action_node = nodeset->nodeTab[i];
767 if (XmlGetProperty(action_node, "event") == "postinstall") {
768 pie_action_node = action_node;
769 break;
770 }
771 }
772
773 if (!pie_action_node) {
774 LOG(ERROR) << "Omaha Response has no postinstall event action";
David Zeuthena99981f2013-04-29 13:42:47 -0700775 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700776 return false;
777 }
778
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800779 output_object->hash = XmlGetProperty(pie_action_node, kTagSha256);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700780 if (output_object->hash.empty()) {
781 LOG(ERROR) << "Omaha Response has empty sha256 value";
David Zeuthena99981f2013-04-29 13:42:47 -0700782 completer->set_code(kErrorCodeOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700783 return false;
784 }
785
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800786 // Get the optional properties one by one.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800787 output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700788 output_object->metadata_size =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800789 ParseInt(XmlGetProperty(pie_action_node, kTagMetadataSize));
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700790 output_object->metadata_signature =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800791 XmlGetProperty(pie_action_node, kTagMetadataSignatureRsa);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800792 output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true";
793 output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700794 output_object->max_days_to_scatter =
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800795 ParseInt(XmlGetProperty(pie_action_node, kTagMaxDaysToScatter));
David Zeuthen8f191b22013-08-06 12:27:50 -0700796 output_object->disable_p2p_for_downloading =
797 (XmlGetProperty(pie_action_node, kTagDisableP2PForDownloading) == "true");
798 output_object->disable_p2p_for_sharing =
799 (XmlGetProperty(pie_action_node, kTagDisableP2PForSharing) == "true");
David Zeuthene7f89172013-10-31 10:21:04 -0700800 output_object->public_key_rsa =
801 XmlGetProperty(pie_action_node, kTagPublicKeyRsa);
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800802
803 string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl);
Jay Srinivasan08262882012-12-28 19:29:43 -0800804 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800805 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700806
Jay Srinivasan08262882012-12-28 19:29:43 -0800807 output_object->is_delta_payload =
808 XmlGetProperty(pie_action_node, kTagIsDeltaPayload) == "true";
809
810 output_object->disable_payload_backoff =
811 XmlGetProperty(pie_action_node, kTagDisablePayloadBackoff) == "true";
812
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700813 return true;
814}
815
rspangler@google.com49fdf182009-10-10 00:57:34 +0000816// If the transfer was successful, this uses libxml2 to parse the response
817// and fill in the appropriate fields of the output object. Also, notifies
818// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700819void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
820 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000821 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800822 string current_response(response_buffer_.begin(), response_buffer_.end());
823 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700824
825 // Events are best effort transactions -- assume they always succeed.
826 if (IsEvent()) {
827 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800828 if (event_->result == OmahaEvent::kResultError && successful &&
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700829 system_state_->hardware()->IsOfficialBuild()) {
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800830 LOG(INFO) << "Signalling Crash Reporter.";
831 utils::ScheduleCrashReporterUpload();
832 }
David Zeuthena99981f2013-04-29 13:42:47 -0700833 completer.set_code(kErrorCodeSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700834 return;
835 }
836
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700837 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700838 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700839 int code = GetHTTPResponseCode();
840 // Makes sure we send sane error values.
841 if (code < 0 || code >= 1000) {
842 code = 999;
843 }
David Zeuthena99981f2013-04-29 13:42:47 -0700844 completer.set_code(static_cast<ErrorCode>(
845 kErrorCodeOmahaRequestHTTPResponseBase + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000846 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700847 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000848
849 // parse our response and fill the fields in the output object
850 scoped_ptr_malloc<xmlDoc, ScopedPtrXmlDocFree> doc(
851 xmlParseMemory(&response_buffer_[0], response_buffer_.size()));
852 if (!doc.get()) {
853 LOG(ERROR) << "Omaha response not valid XML";
Darin Petkovedc522e2010-11-05 09:35:17 -0700854 completer.set_code(response_buffer_.empty() ?
David Zeuthena99981f2013-04-29 13:42:47 -0700855 kErrorCodeOmahaRequestEmptyResponseError :
856 kErrorCodeOmahaRequestXMLParseError);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000857 return;
858 }
859
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700860 // If a ping was sent, update the last ping day preferences based on
861 // the server daystart response.
862 if (ShouldPing(ping_active_days_) ||
863 ShouldPing(ping_roll_call_days_) ||
864 ping_active_days_ == kPingTimeJump ||
865 ping_roll_call_days_ == kPingTimeJump) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800866 LOG_IF(ERROR, !UpdateLastPingDays(doc.get(), system_state_->prefs()))
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700867 << "Failed to update the last ping day preferences!";
868 }
869
Thieu Le116fda32011-04-19 11:01:54 -0700870 if (!HasOutputPipe()) {
871 // Just set success to whether or not the http transfer succeeded,
872 // which must be true at this point in the code.
David Zeuthena99981f2013-04-29 13:42:47 -0700873 completer.set_code(kErrorCodeSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700874 return;
875 }
876
Darin Petkov6a5b3222010-07-13 14:55:28 -0700877 OmahaResponse output_object;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700878 if (!ParseResponse(doc.get(), &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000879 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700880 output_object.update_exists = true;
881 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000882
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700883 if (params_->update_disabled()) {
Jay Srinivasan56d5aa42012-03-26 14:27:59 -0700884 LOG(INFO) << "Ignoring Omaha updates as updates are disabled by policy.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700885 output_object.update_exists = false;
David Zeuthena99981f2013-04-29 13:42:47 -0700886 completer.set_code(kErrorCodeOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan34b5d862012-07-23 11:43:22 -0700887 // Note: We could technically delete the UpdateFirstSeenAt state here.
888 // If we do, it'll mean a device has to restart the UpdateFirstSeenAt
889 // and thus help scattering take effect when the AU is turned on again.
890 // On the other hand, it also increases the chance of update starvation if
891 // an admin turns AU on/off more frequently. We choose to err on the side
892 // of preventing starvation at the cost of not applying scattering in
893 // those cases.
Jay Srinivasan0a708742012-03-20 11:26:12 -0700894 return;
895 }
896
David Zeuthen8f191b22013-08-06 12:27:50 -0700897 // If Omaha says to disable p2p, respect that
898 if (output_object.disable_p2p_for_downloading) {
899 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
900 << "requested by Omaha.";
901 params_->set_use_p2p_for_downloading(false);
902 }
903 if (output_object.disable_p2p_for_sharing) {
904 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
905 << "requested by Omaha.";
906 params_->set_use_p2p_for_sharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700907 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800908
909 // Update the payload state with the current response. The payload state
910 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800911 // from what's stored already. We are updating the payload state as late
912 // as possible in this method so that if a new release gets pushed and then
913 // got pulled back due to some issues, we don't want to clear our internal
914 // state unnecessarily.
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800915 PayloadStateInterface* payload_state = system_state_->payload_state();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800916 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800917
David Zeuthen8f191b22013-08-06 12:27:50 -0700918 // It could be we've already exceeded the deadline for when p2p is
919 // allowed or that we've tried too many times with p2p. Check that.
920 if (params_->use_p2p_for_downloading()) {
921 payload_state->P2PNewAttempt();
922 if (!payload_state->P2PAttemptAllowed()) {
923 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
924 << "of previous failures when using p2p.";
925 params_->set_use_p2p_for_downloading(false);
926 }
927 }
928
929 // From here on, we'll complete stuff in CompleteProcessing() so
930 // disable |completer| since we'll create a new one in that
931 // function.
932 completer.set_should_complete(false);
933
934 // If we're allowed to use p2p for downloading we do not pay
935 // attention to wall-clock-based waiting if the URL is indeed
936 // available via p2p. Therefore, check if the file is available via
937 // p2p before deferring...
938 if (params_->use_p2p_for_downloading()) {
939 LookupPayloadViaP2P(output_object);
940 } else {
941 CompleteProcessing();
942 }
943}
944
945void OmahaRequestAction::CompleteProcessing() {
946 ScopedActionCompleter completer(processor_, this);
947 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
948 PayloadStateInterface* payload_state = system_state_->payload_state();
949
950 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800951 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -0700952 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
953 completer.set_code(kErrorCodeOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -0800954 return;
955 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700956
Chris Sosa20f005c2013-09-05 13:53:08 -0700957 if (payload_state->ShouldBackoffDownload()) {
958 output_object.update_exists = false;
959 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
960 << "attempts";
961 completer.set_code(kErrorCodeOmahaUpdateDeferredForBackoff);
962 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700963 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700964 completer.set_code(kErrorCodeSuccess);
965}
966
967void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
968 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
969 if (!url.empty()) {
970 params_->set_p2p_url(url);
971 } else {
972 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
973 << "because no suitable peer could be found.";
974 params_->set_use_p2p_for_downloading(false);
975 }
976 CompleteProcessing();
977}
978
979void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -0700980 // If the device is in the middle of an update, the state variables
981 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
982 // tracks the offset and length of the operation currently in
983 // progress. The offset is based from the end of the manifest which
984 // is kPrefsManifestMetadataSize bytes long.
985 //
986 // To make forward progress and avoid deadlocks, we need to find a
987 // peer that has at least the entire operation we're currently
988 // working on. Otherwise we may end up in a situation where two
989 // devices bounce back and forth downloading from each other,
990 // neither making any forward progress until one of them decides to
991 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
992 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -0700993 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -0700994 int64_t manifest_metadata_size = 0;
995 int64_t next_data_offset = 0;
996 int64_t next_data_length = 0;
David Zeuthen8f191b22013-08-06 12:27:50 -0700997 if (system_state_ != NULL &&
David Zeuthen41996ad2013-09-24 15:43:24 -0700998 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
999 &manifest_metadata_size) &&
1000 manifest_metadata_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001001 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001002 &next_data_offset) &&
1003 next_data_offset != -1 &&
1004 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1005 &next_data_length)) {
1006 minimum_size = manifest_metadata_size + next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001007 }
1008
1009 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
1010 if (system_state_->p2p_manager() != NULL) {
1011 LOG(INFO) << "Checking if payload is available via p2p, file_id="
1012 << file_id << " minimum_size=" << minimum_size;
1013 system_state_->p2p_manager()->LookupUrlForFile(
1014 file_id,
1015 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001016 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001017 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1018 base::Unretained(this)));
1019 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001020}
1021
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001022bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001023 if (params_->interactive()) {
1024 LOG(INFO) << "Not deferring download because update is interactive.";
1025 return false;
1026 }
1027
David Zeuthen8f191b22013-08-06 12:27:50 -07001028 // If we're using p2p to download _and_ we have a p2p URL, we never
1029 // defer the download. This is because the download will always
1030 // happen from a peer on the LAN and we've been waiting in line for
1031 // our turn.
1032 if (params_->use_p2p_for_downloading() && !params_->p2p_url().empty()) {
1033 LOG(INFO) << "Download not deferred because download "
1034 << "will happen from a local peer (via p2p).";
1035 return false;
1036 }
1037
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001038 // We should defer the downloads only if we've first satisfied the
1039 // wall-clock-based-waiting period and then the update-check-based waiting
1040 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001041 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001042 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1043 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001044 return false;
1045 }
1046
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001047 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001048 case kWallClockWaitNotSatisfied:
1049 // We haven't even satisfied the first condition, passing the
1050 // wall-clock-based waiting period, so we should defer the downloads
1051 // until that happens.
1052 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1053 return true;
1054
1055 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1056 LOG(INFO) << "wall-clock-based-wait satisfied and "
1057 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001058 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001059
1060 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1061 // Wall-clock-based waiting period is satisfied, and it's determined
1062 // that we do not need the update-check-based wait. so no need to
1063 // defer downloads.
1064 LOG(INFO) << "wall-clock-based-wait satisfied and "
1065 << "update-check-based-wait is not required.";
1066 return false;
1067
1068 default:
1069 // Returning false for this default case so we err on the
1070 // side of downloading updates than deferring in case of any bugs.
1071 NOTREACHED();
1072 return false;
1073 }
1074}
1075
1076OmahaRequestAction::WallClockWaitResult
1077OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001078 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001079 Time update_first_seen_at;
1080 int64 update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001081
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001082 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1083 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1084 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001085 // Note: This timestamp could be that of ANY update we saw in the past
1086 // (not necessarily this particular update we're considering to apply)
1087 // but never got to apply because of some reason (e.g. stop AU policy,
1088 // updates being pulled out from Omaha, changes in target version prefix,
1089 // new update being rolled out, etc.). But for the purposes of scattering
1090 // it doesn't matter which update the timestamp corresponds to. i.e.
1091 // the clock starts ticking the first time we see an update and we're
1092 // ready to apply when the random wait period is satisfied relative to
1093 // that first seen timestamp.
1094 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1095 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1096 << utils::ToString(update_first_seen_at);
1097 } else {
1098 // This seems like an unexpected error where the persisted value exists
1099 // but it's not readable for some reason. Just skip scattering in this
1100 // case to be safe.
1101 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1102 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1103 }
1104 } else {
1105 update_first_seen_at = Time::Now();
1106 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001107 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1108 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001109 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1110 << utils::ToString(update_first_seen_at);
1111 }
1112 else {
1113 // This seems like an unexpected error where the value cannot be
1114 // persisted for some reason. Just skip scattering in this
1115 // case to be safe.
1116 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1117 << utils::ToString(update_first_seen_at)
1118 << " cannot be persisted";
1119 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1120 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001121 }
1122
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001123 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001124 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001125 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001126
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001127 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001128 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001129 << ", Time Elapsed = "
1130 << utils::FormatSecs(elapsed_time.InSeconds())
1131 << ", MaxDaysToScatter = "
1132 << max_scatter_period.InDays();
1133
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001134 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001135 // The deadline is set for all rules which serve a delta update from a
1136 // previous FSI, which means this update will be applied mostly in OOBE
1137 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1138 // quickly.
1139 LOG(INFO) << "Not scattering as deadline flag is set";
1140 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1141 }
1142
1143 if (max_scatter_period.InDays() == 0) {
1144 // This means the Omaha rule creator decides that this rule
1145 // should not be scattered irrespective of the policy.
1146 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1147 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1148 }
1149
1150 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001151 // This means we've waited more than the upperbound wait in the rule
1152 // from the time we first saw a valid update available to us.
1153 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001154 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1155 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1156 }
1157
1158 // This means we are required to participate in scattering.
1159 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001160 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001161 if (remaining_wait_time.InSeconds() <= 0) {
1162 // Yes, it's our turn now.
1163 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1164
1165 // But we can't download until the update-check-count-based wait is also
1166 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001167 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001168 kWallClockWaitDoneButUpdateCheckWaitRequired :
1169 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1170 }
1171
1172 // Not our turn yet, so we have to wait until our turn to
1173 // help scatter the downloads across all clients of the enterprise.
1174 LOG(INFO) << "Update deferred for another "
1175 << utils::FormatSecs(remaining_wait_time.InSeconds())
1176 << " per policy.";
1177 return kWallClockWaitNotSatisfied;
1178}
1179
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001180bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001181 int64 update_check_count_value;
1182
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001183 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1184 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1185 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001186 // We are unable to read the update check count from file for some reason.
1187 // So let's proceed anyway so as to not stall the update.
1188 LOG(ERROR) << "Unable to read update check count. "
1189 << "Skipping update-check-count-based-wait.";
1190 return true;
1191 }
1192 } else {
1193 // This file does not exist. This means we haven't started our update
1194 // check count down yet, so this is the right time to start the count down.
1195 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001196 params_->min_update_checks_needed(),
1197 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001198
1199 LOG(INFO) << "Randomly picked update check count value = "
1200 << update_check_count_value;
1201
1202 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001203 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1204 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001205 // We weren't able to write the update check count file for some reason.
1206 // So let's proceed anyway so as to not stall the update.
1207 LOG(ERROR) << "Unable to write update check count. "
1208 << "Skipping update-check-count-based-wait.";
1209 return true;
1210 }
1211 }
1212
1213 if (update_check_count_value == 0) {
1214 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1215 return true;
1216 }
1217
1218 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001219 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001220 // We err on the side of skipping scattering logic instead of stalling
1221 // a machine from receiving any updates in case of any unexpected state.
1222 LOG(ERROR) << "Invalid value for update check count detected. "
1223 << "Skipping update-check-count-based-wait.";
1224 return true;
1225 }
1226
1227 // Legal value, we need to wait for more update checks to happen
1228 // until this becomes 0.
1229 LOG(INFO) << "Deferring Omaha updates for another "
1230 << update_check_count_value
1231 << " update checks per policy";
1232 return false;
1233}
1234
David Zeuthen639aa362014-02-03 16:23:44 -08001235// static
1236bool OmahaRequestAction::ParseInstallDate(xmlDoc* doc,
1237 OmahaResponse* output_object) {
1238 scoped_ptr_malloc<xmlXPathObject, ScopedPtrXmlXPathObjectFree>
1239 xpath_nodeset(GetNodeSet(doc, ConstXMLStr("/response/daystart")));
1240
1241 if (xpath_nodeset.get() == NULL)
1242 return false;
1243
1244 xmlNodeSet* nodeset = xpath_nodeset->nodesetval;
1245 if (nodeset == NULL || nodeset->nodeNr < 1)
1246 return false;
1247
1248 xmlNode* daystart_node = nodeset->nodeTab[0];
1249 if (!xmlHasProp(daystart_node, ConstXMLStr("elapsed_days")))
1250 return false;
1251
1252 int64_t elapsed_days = 0;
1253 if (!base::StringToInt64(XmlGetProperty(daystart_node, "elapsed_days"),
1254 &elapsed_days))
1255 return false;
1256
1257 if (elapsed_days < 0)
1258 return false;
1259
1260 output_object->install_date_days = elapsed_days;
1261 return true;
1262}
1263
1264// static
1265bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1266 PrefsInterface* prefs = system_state->prefs();
1267 if (prefs == NULL)
1268 return false;
1269
1270 return prefs->Exists(kPrefsInstallDateDays);
1271}
1272
1273// static
1274bool OmahaRequestAction::PersistInstallDate(
1275 SystemState *system_state,
1276 int install_date_days,
1277 InstallDateProvisioningSource source) {
1278 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1279
1280 PrefsInterface* prefs = system_state->prefs();
1281 if (prefs == NULL)
1282 return false;
1283
1284 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1285 return false;
1286
1287 string metric_name = "Installer.InstallDateProvisioningSource";
1288 system_state->metrics_lib()->SendEnumToUMA(
1289 metric_name,
1290 static_cast<int>(source), // Sample.
1291 kProvisionedMax); // Maximum.
1292
1293 return true;
1294}
1295
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001296} // namespace chromeos_update_engine