update_attempter.cc revision 33e91e78bfe98c063b0c3b6d590976e275685686
1//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//      http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16
17#include "update_engine/update_attempter.h"
18
19#include <stdint.h>
20
21#include <algorithm>
22#include <memory>
23#include <set>
24#include <string>
25#include <utility>
26#include <vector>
27
28#include <base/bind.h>
29#include <base/files/file_util.h>
30#include <base/logging.h>
31#include <base/rand_util.h>
32#include <base/strings/string_util.h>
33#include <base/strings/stringprintf.h>
34#include <brillo/bind_lambda.h>
35#include <brillo/make_unique_ptr.h>
36#include <brillo/message_loops/message_loop.h>
37#include <debugd/dbus-constants.h>
38#include <policy/device_policy.h>
39#include <policy/libpolicy.h>
40#include <power_manager/dbus-constants.h>
41#include <power_manager/dbus-proxies.h>
42#include <update_engine/dbus-constants.h>
43
44#include "update_engine/common/boot_control_interface.h"
45#include "update_engine/common/certificate_checker.h"
46#include "update_engine/common/clock_interface.h"
47#include "update_engine/common/constants.h"
48#include "update_engine/common/hardware_interface.h"
49#include "update_engine/common/libcurl_http_fetcher.h"
50#include "update_engine/common/multi_range_http_fetcher.h"
51#include "update_engine/common/platform_constants.h"
52#include "update_engine/common/prefs_interface.h"
53#include "update_engine/common/subprocess.h"
54#include "update_engine/common/utils.h"
55#include "update_engine/dbus_service.h"
56#include "update_engine/metrics.h"
57#include "update_engine/omaha_request_action.h"
58#include "update_engine/omaha_request_params.h"
59#include "update_engine/omaha_response_handler_action.h"
60#include "update_engine/p2p_manager.h"
61#include "update_engine/payload_consumer/download_action.h"
62#include "update_engine/payload_consumer/filesystem_verifier_action.h"
63#include "update_engine/payload_consumer/postinstall_runner_action.h"
64#include "update_engine/payload_state_interface.h"
65#include "update_engine/system_state.h"
66#include "update_engine/update_manager/policy.h"
67#include "update_engine/update_manager/update_manager.h"
68#include "update_engine/update_status_utils.h"
69
70using base::Bind;
71using base::Callback;
72using base::Time;
73using base::TimeDelta;
74using base::TimeTicks;
75using brillo::MessageLoop;
76using chromeos_update_manager::EvalStatus;
77using chromeos_update_manager::Policy;
78using chromeos_update_manager::UpdateCheckParams;
79using std::set;
80using std::shared_ptr;
81using std::string;
82using std::vector;
83
84namespace chromeos_update_engine {
85
86const int UpdateAttempter::kMaxDeltaUpdateFailures = 3;
87
88namespace {
89const int kMaxConsecutiveObeyProxyRequests = 20;
90
91// By default autest bypasses scattering. If we want to test scattering,
92// use kScheduledAUTestURLRequest. The URL used is same in both cases, but
93// different params are passed to CheckForUpdate().
94const char kAUTestURLRequest[] = "autest";
95const char kScheduledAUTestURLRequest[] = "autest-scheduled";
96}  // namespace
97
98// Turns a generic ErrorCode::kError to a generic error code specific
99// to |action| (e.g., ErrorCode::kFilesystemVerifierError). If |code| is
100// not ErrorCode::kError, or the action is not matched, returns |code|
101// unchanged.
102ErrorCode GetErrorCodeForAction(AbstractAction* action,
103                                     ErrorCode code) {
104  if (code != ErrorCode::kError)
105    return code;
106
107  const string type = action->Type();
108  if (type == OmahaRequestAction::StaticType())
109    return ErrorCode::kOmahaRequestError;
110  if (type == OmahaResponseHandlerAction::StaticType())
111    return ErrorCode::kOmahaResponseHandlerError;
112  if (type == FilesystemVerifierAction::StaticType())
113    return ErrorCode::kFilesystemVerifierError;
114  if (type == PostinstallRunnerAction::StaticType())
115    return ErrorCode::kPostinstallRunnerError;
116
117  return code;
118}
119
120UpdateAttempter::UpdateAttempter(
121    SystemState* system_state,
122    CertificateChecker* cert_checker,
123    LibCrosProxy* libcros_proxy,
124    org::chromium::debugdProxyInterface* debugd_proxy)
125    : processor_(new ActionProcessor()),
126      system_state_(system_state),
127      cert_checker_(cert_checker),
128      chrome_proxy_resolver_(libcros_proxy),
129      debugd_proxy_(debugd_proxy) {
130}
131
132UpdateAttempter::~UpdateAttempter() {
133  // CertificateChecker might not be initialized in unittests.
134  if (cert_checker_)
135    cert_checker_->SetObserver(nullptr);
136  CleanupCpuSharesManagement();
137  // Release ourselves as the ActionProcessor's delegate to prevent
138  // re-scheduling the updates due to the processing stopped.
139  processor_->set_delegate(nullptr);
140}
141
142void UpdateAttempter::Init() {
143  // Pulling from the SystemState can only be done after construction, since
144  // this is an aggregate of various objects (such as the UpdateAttempter),
145  // which requires them all to be constructed prior to it being used.
146  prefs_ = system_state_->prefs();
147  omaha_request_params_ = system_state_->request_params();
148
149  if (cert_checker_)
150    cert_checker_->SetObserver(this);
151
152  // In case of update_engine restart without a reboot we need to restore the
153  // reboot needed state.
154  if (GetBootTimeAtUpdate(nullptr))
155    status_ = UpdateStatus::UPDATED_NEED_REBOOT;
156  else
157    status_ = UpdateStatus::IDLE;
158}
159
160void UpdateAttempter::ScheduleUpdates() {
161  if (IsUpdateRunningOrScheduled())
162    return;
163
164  chromeos_update_manager::UpdateManager* const update_manager =
165      system_state_->update_manager();
166  CHECK(update_manager);
167  Callback<void(EvalStatus, const UpdateCheckParams&)> callback = Bind(
168      &UpdateAttempter::OnUpdateScheduled, base::Unretained(this));
169  // We limit the async policy request to a reasonably short time, to avoid a
170  // starvation due to a transient bug.
171  update_manager->AsyncPolicyRequest(callback, &Policy::UpdateCheckAllowed);
172  waiting_for_scheduled_check_ = true;
173}
174
175void UpdateAttempter::CertificateChecked(ServerToCheck server_to_check,
176                                         CertificateCheckResult result) {
177  metrics::ReportCertificateCheckMetrics(system_state_,
178                                         server_to_check,
179                                         result);
180}
181
182bool UpdateAttempter::CheckAndReportDailyMetrics() {
183  int64_t stored_value;
184  Time now = system_state_->clock()->GetWallclockTime();
185  if (system_state_->prefs()->Exists(kPrefsDailyMetricsLastReportedAt) &&
186      system_state_->prefs()->GetInt64(kPrefsDailyMetricsLastReportedAt,
187                                       &stored_value)) {
188    Time last_reported_at = Time::FromInternalValue(stored_value);
189    TimeDelta time_reported_since = now - last_reported_at;
190    if (time_reported_since.InSeconds() < 0) {
191      LOG(WARNING) << "Last reported daily metrics "
192                   << utils::FormatTimeDelta(time_reported_since) << " ago "
193                   << "which is negative. Either the system clock is wrong or "
194                   << "the kPrefsDailyMetricsLastReportedAt state variable "
195                   << "is wrong.";
196      // In this case, report daily metrics to reset.
197    } else {
198      if (time_reported_since.InSeconds() < 24*60*60) {
199        LOG(INFO) << "Last reported daily metrics "
200                  << utils::FormatTimeDelta(time_reported_since) << " ago.";
201        return false;
202      }
203      LOG(INFO) << "Last reported daily metrics "
204                << utils::FormatTimeDelta(time_reported_since) << " ago, "
205                << "which is more than 24 hours ago.";
206    }
207  }
208
209  LOG(INFO) << "Reporting daily metrics.";
210  system_state_->prefs()->SetInt64(kPrefsDailyMetricsLastReportedAt,
211                                   now.ToInternalValue());
212
213  ReportOSAge();
214
215  return true;
216}
217
218void UpdateAttempter::ReportOSAge() {
219  struct stat sb;
220
221  if (system_state_ == nullptr)
222    return;
223
224  if (stat("/etc/lsb-release", &sb) != 0) {
225    PLOG(ERROR) << "Error getting file status for /etc/lsb-release "
226                << "(Note: this may happen in some unit tests)";
227    return;
228  }
229
230  Time lsb_release_timestamp = utils::TimeFromStructTimespec(&sb.st_ctim);
231  Time now = system_state_->clock()->GetWallclockTime();
232  TimeDelta age = now - lsb_release_timestamp;
233  if (age.InSeconds() < 0) {
234    LOG(ERROR) << "The OS age (" << utils::FormatTimeDelta(age)
235               << ") is negative. Maybe the clock is wrong? "
236               << "(Note: this may happen in some unit tests.)";
237    return;
238  }
239
240  metrics::ReportDailyMetrics(system_state_, age);
241}
242
243void UpdateAttempter::Update(const string& app_version,
244                             const string& omaha_url,
245                             const string& target_channel,
246                             const string& target_version_prefix,
247                             bool obey_proxies,
248                             bool interactive) {
249  // This is normally called frequently enough so it's appropriate to use as a
250  // hook for reporting daily metrics.
251  // TODO(garnold) This should be hooked to a separate (reliable and consistent)
252  // timeout event.
253  CheckAndReportDailyMetrics();
254
255  // Notify of the new update attempt, clearing prior interactive requests.
256  if (forced_update_pending_callback_.get())
257    forced_update_pending_callback_->Run(false, false);
258
259  chrome_proxy_resolver_.Init();
260  fake_update_success_ = false;
261  if (status_ == UpdateStatus::UPDATED_NEED_REBOOT) {
262    // Although we have applied an update, we still want to ping Omaha
263    // to ensure the number of active statistics is accurate.
264    //
265    // Also convey to the UpdateEngine.Check.Result metric that we're
266    // not performing an update check because of this.
267    LOG(INFO) << "Not updating b/c we already updated and we're waiting for "
268              << "reboot, we'll ping Omaha instead";
269    metrics::ReportUpdateCheckMetrics(system_state_,
270                                      metrics::CheckResult::kRebootPending,
271                                      metrics::CheckReaction::kUnset,
272                                      metrics::DownloadErrorCode::kUnset);
273    PingOmaha();
274    return;
275  }
276  if (status_ != UpdateStatus::IDLE) {
277    // Update in progress. Do nothing
278    return;
279  }
280
281  if (!CalculateUpdateParams(app_version,
282                             omaha_url,
283                             target_channel,
284                             target_version_prefix,
285                             obey_proxies,
286                             interactive)) {
287    return;
288  }
289
290  BuildUpdateActions(interactive);
291
292  SetStatusAndNotify(UpdateStatus::CHECKING_FOR_UPDATE);
293
294  // Update the last check time here; it may be re-updated when an Omaha
295  // response is received, but this will prevent us from repeatedly scheduling
296  // checks in the case where a response is not received.
297  UpdateLastCheckedTime();
298
299  // Just in case we didn't update boot flags yet, make sure they're updated
300  // before any update processing starts.
301  start_action_processor_ = true;
302  UpdateBootFlags();
303}
304
305void UpdateAttempter::RefreshDevicePolicy() {
306  // Lazy initialize the policy provider, or reload the latest policy data.
307  if (!policy_provider_.get())
308    policy_provider_.reset(new policy::PolicyProvider());
309  policy_provider_->Reload();
310
311  const policy::DevicePolicy* device_policy = nullptr;
312  if (policy_provider_->device_policy_is_loaded())
313    device_policy = &policy_provider_->GetDevicePolicy();
314
315  if (device_policy)
316    LOG(INFO) << "Device policies/settings present";
317  else
318    LOG(INFO) << "No device policies/settings present.";
319
320  system_state_->set_device_policy(device_policy);
321  system_state_->p2p_manager()->SetDevicePolicy(device_policy);
322}
323
324void UpdateAttempter::CalculateP2PParams(bool interactive) {
325  bool use_p2p_for_downloading = false;
326  bool use_p2p_for_sharing = false;
327
328  // Never use p2p for downloading in interactive checks unless the
329  // developer has opted in for it via a marker file.
330  //
331  // (Why would a developer want to opt in? If he's working on the
332  // update_engine or p2p codebases so he can actually test his
333  // code.).
334
335  if (system_state_ != nullptr) {
336    if (!system_state_->p2p_manager()->IsP2PEnabled()) {
337      LOG(INFO) << "p2p is not enabled - disallowing p2p for both"
338                << " downloading and sharing.";
339    } else {
340      // Allow p2p for sharing, even in interactive checks.
341      use_p2p_for_sharing = true;
342      if (!interactive) {
343        LOG(INFO) << "Non-interactive check - allowing p2p for downloading";
344        use_p2p_for_downloading = true;
345      } else {
346        LOG(INFO) << "Forcibly disabling use of p2p for downloading "
347                  << "since this update attempt is interactive.";
348      }
349    }
350  }
351
352  PayloadStateInterface* const payload_state = system_state_->payload_state();
353  payload_state->SetUsingP2PForDownloading(use_p2p_for_downloading);
354  payload_state->SetUsingP2PForSharing(use_p2p_for_sharing);
355}
356
357bool UpdateAttempter::CalculateUpdateParams(const string& app_version,
358                                            const string& omaha_url,
359                                            const string& target_channel,
360                                            const string& target_version_prefix,
361                                            bool obey_proxies,
362                                            bool interactive) {
363  http_response_code_ = 0;
364  PayloadStateInterface* const payload_state = system_state_->payload_state();
365
366  // Refresh the policy before computing all the update parameters.
367  RefreshDevicePolicy();
368
369  // Set the target version prefix, if provided.
370  if (!target_version_prefix.empty())
371    omaha_request_params_->set_target_version_prefix(target_version_prefix);
372
373  CalculateScatteringParams(interactive);
374
375  CalculateP2PParams(interactive);
376  if (payload_state->GetUsingP2PForDownloading() ||
377      payload_state->GetUsingP2PForSharing()) {
378    // OK, p2p is to be used - start it and perform housekeeping.
379    if (!StartP2PAndPerformHousekeeping()) {
380      // If this fails, disable p2p for this attempt
381      LOG(INFO) << "Forcibly disabling use of p2p since starting p2p or "
382                << "performing housekeeping failed.";
383      payload_state->SetUsingP2PForDownloading(false);
384      payload_state->SetUsingP2PForSharing(false);
385    }
386  }
387
388  if (!omaha_request_params_->Init(app_version,
389                                   omaha_url,
390                                   interactive)) {
391    LOG(ERROR) << "Unable to initialize Omaha request params.";
392    return false;
393  }
394
395  // Set the target channel, if one was provided.
396  if (target_channel.empty()) {
397    LOG(INFO) << "No target channel mandated by policy.";
398  } else {
399    LOG(INFO) << "Setting target channel as mandated: " << target_channel;
400    // Pass in false for powerwash_allowed until we add it to the policy
401    // protobuf.
402    string error_message;
403    if (!omaha_request_params_->SetTargetChannel(target_channel, false,
404                                                 &error_message)) {
405      LOG(ERROR) << "Setting the channel failed: " << error_message;
406    }
407
408    // Since this is the beginning of a new attempt, update the download
409    // channel. The download channel won't be updated until the next attempt,
410    // even if target channel changes meanwhile, so that how we'll know if we
411    // should cancel the current download attempt if there's such a change in
412    // target channel.
413    omaha_request_params_->UpdateDownloadChannel();
414  }
415
416  LOG(INFO) << "target_version_prefix = "
417            << omaha_request_params_->target_version_prefix()
418            << ", scatter_factor_in_seconds = "
419            << utils::FormatSecs(scatter_factor_.InSeconds());
420
421  LOG(INFO) << "Wall Clock Based Wait Enabled = "
422            << omaha_request_params_->wall_clock_based_wait_enabled()
423            << ", Update Check Count Wait Enabled = "
424            << omaha_request_params_->update_check_count_wait_enabled()
425            << ", Waiting Period = " << utils::FormatSecs(
426               omaha_request_params_->waiting_period().InSeconds());
427
428  LOG(INFO) << "Use p2p For Downloading = "
429            << payload_state->GetUsingP2PForDownloading()
430            << ", Use p2p For Sharing = "
431            << payload_state->GetUsingP2PForSharing();
432
433  obeying_proxies_ = true;
434  if (obey_proxies || proxy_manual_checks_ == 0) {
435    LOG(INFO) << "forced to obey proxies";
436    // If forced to obey proxies, every 20th request will not use proxies
437    proxy_manual_checks_++;
438    LOG(INFO) << "proxy manual checks: " << proxy_manual_checks_;
439    if (proxy_manual_checks_ >= kMaxConsecutiveObeyProxyRequests) {
440      proxy_manual_checks_ = 0;
441      obeying_proxies_ = false;
442    }
443  } else if (base::RandInt(0, 4) == 0) {
444    obeying_proxies_ = false;
445  }
446  LOG_IF(INFO, !obeying_proxies_) << "To help ensure updates work, this update "
447      "check we are ignoring the proxy settings and using "
448      "direct connections.";
449
450  DisableDeltaUpdateIfNeeded();
451  return true;
452}
453
454void UpdateAttempter::CalculateScatteringParams(bool interactive) {
455  // Take a copy of the old scatter value before we update it, as
456  // we need to update the waiting period if this value changes.
457  TimeDelta old_scatter_factor = scatter_factor_;
458  const policy::DevicePolicy* device_policy = system_state_->device_policy();
459  if (device_policy) {
460    int64_t new_scatter_factor_in_secs = 0;
461    device_policy->GetScatterFactorInSeconds(&new_scatter_factor_in_secs);
462    if (new_scatter_factor_in_secs < 0)  // sanitize input, just in case.
463      new_scatter_factor_in_secs  = 0;
464    scatter_factor_ = TimeDelta::FromSeconds(new_scatter_factor_in_secs);
465  }
466
467  bool is_scatter_enabled = false;
468  if (scatter_factor_.InSeconds() == 0) {
469    LOG(INFO) << "Scattering disabled since scatter factor is set to 0";
470  } else if (interactive) {
471    LOG(INFO) << "Scattering disabled as this is an interactive update check";
472  } else if (!system_state_->hardware()->IsOOBEComplete(nullptr)) {
473    LOG(INFO) << "Scattering disabled since OOBE is not complete yet";
474  } else {
475    is_scatter_enabled = true;
476    LOG(INFO) << "Scattering is enabled";
477  }
478
479  if (is_scatter_enabled) {
480    // This means the scattering policy is turned on.
481    // Now check if we need to update the waiting period. The two cases
482    // in which we'd need to update the waiting period are:
483    // 1. First time in process or a scheduled check after a user-initiated one.
484    //    (omaha_request_params_->waiting_period will be zero in this case).
485    // 2. Admin has changed the scattering policy value.
486    //    (new scattering value will be different from old one in this case).
487    int64_t wait_period_in_secs = 0;
488    if (omaha_request_params_->waiting_period().InSeconds() == 0) {
489      // First case. Check if we have a suitable value to set for
490      // the waiting period.
491      if (prefs_->GetInt64(kPrefsWallClockWaitPeriod, &wait_period_in_secs) &&
492          wait_period_in_secs > 0 &&
493          wait_period_in_secs <= scatter_factor_.InSeconds()) {
494        // This means:
495        // 1. There's a persisted value for the waiting period available.
496        // 2. And that persisted value is still valid.
497        // So, in this case, we should reuse the persisted value instead of
498        // generating a new random value to improve the chances of a good
499        // distribution for scattering.
500        omaha_request_params_->set_waiting_period(
501          TimeDelta::FromSeconds(wait_period_in_secs));
502        LOG(INFO) << "Using persisted wall-clock waiting period: " <<
503            utils::FormatSecs(
504                omaha_request_params_->waiting_period().InSeconds());
505      } else {
506        // This means there's no persisted value for the waiting period
507        // available or its value is invalid given the new scatter_factor value.
508        // So, we should go ahead and regenerate a new value for the
509        // waiting period.
510        LOG(INFO) << "Persisted value not present or not valid ("
511                  << utils::FormatSecs(wait_period_in_secs)
512                  << ") for wall-clock waiting period.";
513        GenerateNewWaitingPeriod();
514      }
515    } else if (scatter_factor_ != old_scatter_factor) {
516      // This means there's already a waiting period value, but we detected
517      // a change in the scattering policy value. So, we should regenerate the
518      // waiting period to make sure it's within the bounds of the new scatter
519      // factor value.
520      GenerateNewWaitingPeriod();
521    } else {
522      // Neither the first time scattering is enabled nor the scattering value
523      // changed. Nothing to do.
524      LOG(INFO) << "Keeping current wall-clock waiting period: " <<
525          utils::FormatSecs(
526              omaha_request_params_->waiting_period().InSeconds());
527    }
528
529    // The invariant at this point is that omaha_request_params_->waiting_period
530    // is non-zero no matter which path we took above.
531    LOG_IF(ERROR, omaha_request_params_->waiting_period().InSeconds() == 0)
532        << "Waiting Period should NOT be zero at this point!!!";
533
534    // Since scattering is enabled, wall clock based wait will always be
535    // enabled.
536    omaha_request_params_->set_wall_clock_based_wait_enabled(true);
537
538    // If we don't have any issues in accessing the file system to update
539    // the update check count value, we'll turn that on as well.
540    bool decrement_succeeded = DecrementUpdateCheckCount();
541    omaha_request_params_->set_update_check_count_wait_enabled(
542      decrement_succeeded);
543  } else {
544    // This means the scattering feature is turned off or disabled for
545    // this particular update check. Make sure to disable
546    // all the knobs and artifacts so that we don't invoke any scattering
547    // related code.
548    omaha_request_params_->set_wall_clock_based_wait_enabled(false);
549    omaha_request_params_->set_update_check_count_wait_enabled(false);
550    omaha_request_params_->set_waiting_period(TimeDelta::FromSeconds(0));
551    prefs_->Delete(kPrefsWallClockWaitPeriod);
552    prefs_->Delete(kPrefsUpdateCheckCount);
553    // Don't delete the UpdateFirstSeenAt file as we don't want manual checks
554    // that result in no-updates (e.g. due to server side throttling) to
555    // cause update starvation by having the client generate a new
556    // UpdateFirstSeenAt for each scheduled check that follows a manual check.
557  }
558}
559
560void UpdateAttempter::GenerateNewWaitingPeriod() {
561  omaha_request_params_->set_waiting_period(TimeDelta::FromSeconds(
562      base::RandInt(1, scatter_factor_.InSeconds())));
563
564  LOG(INFO) << "Generated new wall-clock waiting period: " << utils::FormatSecs(
565                omaha_request_params_->waiting_period().InSeconds());
566
567  // Do a best-effort to persist this in all cases. Even if the persistence
568  // fails, we'll still be able to scatter based on our in-memory value.
569  // The persistence only helps in ensuring a good overall distribution
570  // across multiple devices if they tend to reboot too often.
571  system_state_->payload_state()->SetScatteringWaitPeriod(
572      omaha_request_params_->waiting_period());
573}
574
575void UpdateAttempter::BuildPostInstallActions(
576    InstallPlanAction* previous_action) {
577  shared_ptr<PostinstallRunnerAction> postinstall_runner_action(
578      new PostinstallRunnerAction(system_state_->boot_control()));
579  actions_.push_back(shared_ptr<AbstractAction>(postinstall_runner_action));
580  BondActions(previous_action,
581              postinstall_runner_action.get());
582}
583
584void UpdateAttempter::BuildUpdateActions(bool interactive) {
585  CHECK(!processor_->IsRunning());
586  processor_->set_delegate(this);
587
588  // Actions:
589  std::unique_ptr<LibcurlHttpFetcher> update_check_fetcher(
590      new LibcurlHttpFetcher(GetProxyResolver(), system_state_->hardware()));
591  update_check_fetcher->set_server_to_check(ServerToCheck::kUpdate);
592  // Try harder to connect to the network, esp when not interactive.
593  // See comment in libcurl_http_fetcher.cc.
594  update_check_fetcher->set_no_network_max_retries(interactive ? 1 : 3);
595  shared_ptr<OmahaRequestAction> update_check_action(
596      new OmahaRequestAction(system_state_,
597                             nullptr,
598                             std::move(update_check_fetcher),
599                             false));
600  shared_ptr<OmahaResponseHandlerAction> response_handler_action(
601      new OmahaResponseHandlerAction(system_state_));
602  shared_ptr<FilesystemVerifierAction> src_filesystem_verifier_action(
603      new FilesystemVerifierAction(system_state_->boot_control(),
604                                   VerifierMode::kComputeSourceHash));
605
606  shared_ptr<OmahaRequestAction> download_started_action(
607      new OmahaRequestAction(system_state_,
608                             new OmahaEvent(
609                                 OmahaEvent::kTypeUpdateDownloadStarted),
610                             brillo::make_unique_ptr(new LibcurlHttpFetcher(
611                                 GetProxyResolver(),
612                                 system_state_->hardware())),
613                             false));
614
615  LibcurlHttpFetcher* download_fetcher =
616      new LibcurlHttpFetcher(GetProxyResolver(), system_state_->hardware());
617  download_fetcher->set_server_to_check(ServerToCheck::kDownload);
618  shared_ptr<DownloadAction> download_action(
619      new DownloadAction(prefs_,
620                         system_state_,
621                         new MultiRangeHttpFetcher(
622                             download_fetcher)));  // passes ownership
623  shared_ptr<OmahaRequestAction> download_finished_action(
624      new OmahaRequestAction(
625          system_state_,
626          new OmahaEvent(OmahaEvent::kTypeUpdateDownloadFinished),
627          brillo::make_unique_ptr(
628              new LibcurlHttpFetcher(GetProxyResolver(),
629                                     system_state_->hardware())),
630          false));
631  shared_ptr<FilesystemVerifierAction> dst_filesystem_verifier_action(
632      new FilesystemVerifierAction(system_state_->boot_control(),
633                                   VerifierMode::kVerifyTargetHash));
634  shared_ptr<OmahaRequestAction> update_complete_action(
635      new OmahaRequestAction(
636          system_state_,
637          new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
638          brillo::make_unique_ptr(
639              new LibcurlHttpFetcher(GetProxyResolver(),
640                                     system_state_->hardware())),
641          false));
642
643  download_action->set_delegate(this);
644  response_handler_action_ = response_handler_action;
645  download_action_ = download_action;
646
647  actions_.push_back(shared_ptr<AbstractAction>(update_check_action));
648  actions_.push_back(shared_ptr<AbstractAction>(response_handler_action));
649  actions_.push_back(shared_ptr<AbstractAction>(
650      src_filesystem_verifier_action));
651  actions_.push_back(shared_ptr<AbstractAction>(download_started_action));
652  actions_.push_back(shared_ptr<AbstractAction>(download_action));
653  actions_.push_back(shared_ptr<AbstractAction>(download_finished_action));
654  actions_.push_back(shared_ptr<AbstractAction>(
655      dst_filesystem_verifier_action));
656
657  // Bond them together. We have to use the leaf-types when calling
658  // BondActions().
659  BondActions(update_check_action.get(),
660              response_handler_action.get());
661  BondActions(response_handler_action.get(),
662              src_filesystem_verifier_action.get());
663  BondActions(src_filesystem_verifier_action.get(),
664              download_action.get());
665  BondActions(download_action.get(),
666              dst_filesystem_verifier_action.get());
667  BuildPostInstallActions(dst_filesystem_verifier_action.get());
668
669  actions_.push_back(shared_ptr<AbstractAction>(update_complete_action));
670
671  // Enqueue the actions
672  for (const shared_ptr<AbstractAction>& action : actions_) {
673    processor_->EnqueueAction(action.get());
674  }
675}
676
677bool UpdateAttempter::Rollback(bool powerwash) {
678  if (!CanRollback()) {
679    return false;
680  }
681
682  // Extra check for enterprise-enrolled devices since they don't support
683  // powerwash.
684  if (powerwash) {
685    // Enterprise-enrolled devices have an empty owner in their device policy.
686    string owner;
687    RefreshDevicePolicy();
688    const policy::DevicePolicy* device_policy = system_state_->device_policy();
689    if (device_policy && (!device_policy->GetOwner(&owner) || owner.empty())) {
690      LOG(ERROR) << "Enterprise device detected. "
691                 << "Cannot perform a powerwash for enterprise devices.";
692      return false;
693    }
694  }
695
696  processor_->set_delegate(this);
697
698  // Initialize the default request params.
699  if (!omaha_request_params_->Init("", "", true)) {
700    LOG(ERROR) << "Unable to initialize Omaha request params.";
701    return false;
702  }
703
704  LOG(INFO) << "Setting rollback options.";
705  InstallPlan install_plan;
706
707  install_plan.target_slot = GetRollbackSlot();
708  install_plan.source_slot = system_state_->boot_control()->GetCurrentSlot();
709
710  TEST_AND_RETURN_FALSE(
711      install_plan.LoadPartitionsFromSlots(system_state_->boot_control()));
712  install_plan.powerwash_required = powerwash;
713
714  LOG(INFO) << "Using this install plan:";
715  install_plan.Dump();
716
717  shared_ptr<InstallPlanAction> install_plan_action(
718      new InstallPlanAction(install_plan));
719  actions_.push_back(shared_ptr<AbstractAction>(install_plan_action));
720
721  BuildPostInstallActions(install_plan_action.get());
722
723  // Enqueue the actions
724  for (const shared_ptr<AbstractAction>& action : actions_) {
725    processor_->EnqueueAction(action.get());
726  }
727
728  // Update the payload state for Rollback.
729  system_state_->payload_state()->Rollback();
730
731  SetStatusAndNotify(UpdateStatus::ATTEMPTING_ROLLBACK);
732
733  // Just in case we didn't update boot flags yet, make sure they're updated
734  // before any update processing starts. This also schedules the start of the
735  // actions we just posted.
736  start_action_processor_ = true;
737  UpdateBootFlags();
738  return true;
739}
740
741bool UpdateAttempter::CanRollback() const {
742  // We can only rollback if the update_engine isn't busy and we have a valid
743  // rollback partition.
744  return (status_ == UpdateStatus::IDLE &&
745          GetRollbackSlot() != BootControlInterface::kInvalidSlot);
746}
747
748BootControlInterface::Slot UpdateAttempter::GetRollbackSlot() const {
749  LOG(INFO) << "UpdateAttempter::GetRollbackSlot";
750  const unsigned int num_slots = system_state_->boot_control()->GetNumSlots();
751  const BootControlInterface::Slot current_slot =
752      system_state_->boot_control()->GetCurrentSlot();
753
754  LOG(INFO) << "  Installed slots: " << num_slots;
755  LOG(INFO) << "  Booted from slot: "
756            << BootControlInterface::SlotName(current_slot);
757
758  if (current_slot == BootControlInterface::kInvalidSlot || num_slots < 2) {
759    LOG(INFO) << "Device is not updateable.";
760    return BootControlInterface::kInvalidSlot;
761  }
762
763  vector<BootControlInterface::Slot> bootable_slots;
764  for(BootControlInterface::Slot slot = 0; slot < num_slots; slot++) {
765    if (slot != current_slot &&
766        system_state_->boot_control()->IsSlotBootable(slot)) {
767      LOG(INFO) << "Found bootable slot "
768                << BootControlInterface::SlotName(slot);
769      return slot;
770    }
771  }
772  LOG(INFO) << "No other bootable slot found.";
773  return BootControlInterface::kInvalidSlot;
774}
775
776void UpdateAttempter::CheckForUpdate(const string& app_version,
777                                     const string& omaha_url,
778                                     bool interactive) {
779  LOG(INFO) << "Forced update check requested.";
780  forced_app_version_.clear();
781  forced_omaha_url_.clear();
782
783  // Certain conditions must be met to allow setting custom version and update
784  // server URLs. However, kScheduledAUTestURLRequest and kAUTestURLRequest are
785  // always allowed regardless of device state.
786  if (IsAnyUpdateSourceAllowed()) {
787    forced_app_version_ = app_version;
788    forced_omaha_url_ = omaha_url;
789  }
790  if (omaha_url == kScheduledAUTestURLRequest) {
791    forced_omaha_url_ = constants::kOmahaDefaultAUTestURL;
792    // Pretend that it's not user-initiated even though it is,
793    // so as to test scattering logic, etc. which get kicked off
794    // only in scheduled update checks.
795    interactive = false;
796  } else if (omaha_url == kAUTestURLRequest) {
797    forced_omaha_url_ = constants::kOmahaDefaultAUTestURL;
798  }
799
800  if (forced_update_pending_callback_.get()) {
801    // Make sure that a scheduling request is made prior to calling the forced
802    // update pending callback.
803    ScheduleUpdates();
804    forced_update_pending_callback_->Run(true, interactive);
805  }
806}
807
808bool UpdateAttempter::RebootIfNeeded() {
809  if (status_ != UpdateStatus::UPDATED_NEED_REBOOT) {
810    LOG(INFO) << "Reboot requested, but status is "
811              << UpdateStatusToString(status_) << ", so not rebooting.";
812    return false;
813  }
814
815  if (USE_POWER_MANAGEMENT && RequestPowerManagerReboot())
816    return true;
817
818  return RebootDirectly();
819}
820
821void UpdateAttempter::WriteUpdateCompletedMarker() {
822  string boot_id;
823  if (!utils::GetBootId(&boot_id))
824    return;
825  prefs_->SetString(kPrefsUpdateCompletedOnBootId, boot_id);
826
827  int64_t value = system_state_->clock()->GetBootTime().ToInternalValue();
828  prefs_->SetInt64(kPrefsUpdateCompletedBootTime, value);
829}
830
831bool UpdateAttempter::RequestPowerManagerReboot() {
832  org::chromium::PowerManagerProxyInterface* power_manager_proxy =
833      system_state_->power_manager_proxy();
834  if (!power_manager_proxy) {
835    LOG(WARNING) << "No PowerManager proxy defined, skipping reboot.";
836    return false;
837  }
838  LOG(INFO) << "Calling " << power_manager::kPowerManagerInterface << "."
839            << power_manager::kRequestRestartMethod;
840  brillo::ErrorPtr error;
841  return power_manager_proxy->RequestRestart(
842      power_manager::REQUEST_RESTART_FOR_UPDATE, &error);
843}
844
845bool UpdateAttempter::RebootDirectly() {
846  vector<string> command;
847  command.push_back("/sbin/shutdown");
848  command.push_back("-r");
849  command.push_back("now");
850  LOG(INFO) << "Running \"" << JoinString(command, ' ') << "\"";
851  int rc = 0;
852  Subprocess::SynchronousExec(command, &rc, nullptr);
853  return rc == 0;
854}
855
856void UpdateAttempter::OnUpdateScheduled(EvalStatus status,
857                                        const UpdateCheckParams& params) {
858  waiting_for_scheduled_check_ = false;
859
860  if (status == EvalStatus::kSucceeded) {
861    if (!params.updates_enabled) {
862      LOG(WARNING) << "Updates permanently disabled.";
863      // Signal disabled status, then switch right back to idle. This is
864      // necessary for ensuring that observers waiting for a signal change will
865      // actually notice one on subsequent calls. Note that we don't need to
866      // re-schedule a check in this case as updates are permanently disabled;
867      // further (forced) checks may still initiate a scheduling call.
868      SetStatusAndNotify(UpdateStatus::DISABLED);
869      SetStatusAndNotify(UpdateStatus::IDLE);
870      return;
871    }
872
873    LOG(INFO) << "Running "
874              << (params.is_interactive ? "interactive" : "periodic")
875              << " update.";
876
877    string app_version, omaha_url;
878    if (params.is_interactive) {
879      app_version = forced_app_version_;
880      omaha_url = forced_omaha_url_;
881    }
882
883    Update(app_version, omaha_url, params.target_channel,
884           params.target_version_prefix, false, params.is_interactive);
885  } else {
886    LOG(WARNING)
887        << "Update check scheduling failed (possibly timed out); retrying.";
888    ScheduleUpdates();
889  }
890
891  // This check ensures that future update checks will be or are already
892  // scheduled. The check should never fail. A check failure means that there's
893  // a bug that will most likely prevent further automatic update checks. It
894  // seems better to crash in such cases and restart the update_engine daemon
895  // into, hopefully, a known good state.
896  CHECK(IsUpdateRunningOrScheduled());
897}
898
899void UpdateAttempter::UpdateLastCheckedTime() {
900  last_checked_time_ = system_state_->clock()->GetWallclockTime().ToTimeT();
901}
902
903// Delegate methods:
904void UpdateAttempter::ProcessingDone(const ActionProcessor* processor,
905                                     ErrorCode code) {
906  LOG(INFO) << "Processing Done.";
907  actions_.clear();
908
909  // Reset cpu shares back to normal.
910  CleanupCpuSharesManagement();
911
912  if (status_ == UpdateStatus::REPORTING_ERROR_EVENT) {
913    LOG(INFO) << "Error event sent.";
914
915    // Inform scheduler of new status;
916    SetStatusAndNotify(UpdateStatus::IDLE);
917    ScheduleUpdates();
918
919    if (!fake_update_success_) {
920      return;
921    }
922    LOG(INFO) << "Booted from FW B and tried to install new firmware, "
923        "so requesting reboot from user.";
924  }
925
926  if (code == ErrorCode::kSuccess) {
927    WriteUpdateCompletedMarker();
928    prefs_->SetInt64(kPrefsDeltaUpdateFailures, 0);
929    prefs_->SetString(kPrefsPreviousVersion,
930                      omaha_request_params_->app_version());
931    DeltaPerformer::ResetUpdateProgress(prefs_, false);
932
933    system_state_->payload_state()->UpdateSucceeded();
934
935    // Since we're done with scattering fully at this point, this is the
936    // safest point delete the state files, as we're sure that the status is
937    // set to reboot (which means no more updates will be applied until reboot)
938    // This deletion is required for correctness as we want the next update
939    // check to re-create a new random number for the update check count.
940    // Similarly, we also delete the wall-clock-wait period that was persisted
941    // so that we start with a new random value for the next update check
942    // after reboot so that the same device is not favored or punished in any
943    // way.
944    prefs_->Delete(kPrefsUpdateCheckCount);
945    system_state_->payload_state()->SetScatteringWaitPeriod(TimeDelta());
946    prefs_->Delete(kPrefsUpdateFirstSeenAt);
947
948    SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
949    ScheduleUpdates();
950    LOG(INFO) << "Update successfully applied, waiting to reboot.";
951
952    // This pointer is null during rollback operations, and the stats
953    // don't make much sense then anyway.
954    if (response_handler_action_) {
955      const InstallPlan& install_plan =
956          response_handler_action_->install_plan();
957
958      // Generate an unique payload identifier.
959      const string target_version_uid =
960          install_plan.payload_hash + ":" + install_plan.metadata_signature;
961
962      // Expect to reboot into the new version to send the proper metric during
963      // next boot.
964      system_state_->payload_state()->ExpectRebootInNewVersion(
965          target_version_uid);
966    } else {
967      // If we just finished a rollback, then we expect to have no Omaha
968      // response. Otherwise, it's an error.
969      if (system_state_->payload_state()->GetRollbackVersion().empty()) {
970        LOG(ERROR) << "Can't send metrics because expected "
971            "response_handler_action_ missing.";
972      }
973    }
974    return;
975  }
976
977  if (ScheduleErrorEventAction()) {
978    return;
979  }
980  LOG(INFO) << "No update.";
981  SetStatusAndNotify(UpdateStatus::IDLE);
982  ScheduleUpdates();
983}
984
985void UpdateAttempter::ProcessingStopped(const ActionProcessor* processor) {
986  // Reset cpu shares back to normal.
987  CleanupCpuSharesManagement();
988  download_progress_ = 0.0;
989  SetStatusAndNotify(UpdateStatus::IDLE);
990  ScheduleUpdates();
991  actions_.clear();
992  error_event_.reset(nullptr);
993}
994
995// Called whenever an action has finished processing, either successfully
996// or otherwise.
997void UpdateAttempter::ActionCompleted(ActionProcessor* processor,
998                                      AbstractAction* action,
999                                      ErrorCode code) {
1000  // Reset download progress regardless of whether or not the download
1001  // action succeeded. Also, get the response code from HTTP request
1002  // actions (update download as well as the initial update check
1003  // actions).
1004  const string type = action->Type();
1005  if (type == DownloadAction::StaticType()) {
1006    download_progress_ = 0.0;
1007    DownloadAction* download_action = static_cast<DownloadAction*>(action);
1008    http_response_code_ = download_action->GetHTTPResponseCode();
1009  } else if (type == OmahaRequestAction::StaticType()) {
1010    OmahaRequestAction* omaha_request_action =
1011        static_cast<OmahaRequestAction*>(action);
1012    // If the request is not an event, then it's the update-check.
1013    if (!omaha_request_action->IsEvent()) {
1014      http_response_code_ = omaha_request_action->GetHTTPResponseCode();
1015
1016      // Record the number of consecutive failed update checks.
1017      if (http_response_code_ == kHttpResponseInternalServerError ||
1018          http_response_code_ == kHttpResponseServiceUnavailable) {
1019        consecutive_failed_update_checks_++;
1020      } else {
1021        consecutive_failed_update_checks_ = 0;
1022      }
1023
1024      // Store the server-dictated poll interval, if any.
1025      server_dictated_poll_interval_ =
1026          std::max(0, omaha_request_action->GetOutputObject().poll_interval);
1027    }
1028  }
1029  if (code != ErrorCode::kSuccess) {
1030    // If the current state is at or past the download phase, count the failure
1031    // in case a switch to full update becomes necessary. Ignore network
1032    // transfer timeouts and failures.
1033    if (status_ >= UpdateStatus::DOWNLOADING &&
1034        code != ErrorCode::kDownloadTransferError) {
1035      MarkDeltaUpdateFailure();
1036    }
1037    // On failure, schedule an error event to be sent to Omaha.
1038    CreatePendingErrorEvent(action, code);
1039    return;
1040  }
1041  // Find out which action completed.
1042  if (type == OmahaResponseHandlerAction::StaticType()) {
1043    // Note that the status will be updated to DOWNLOADING when some bytes get
1044    // actually downloaded from the server and the BytesReceived callback is
1045    // invoked. This avoids notifying the user that a download has started in
1046    // cases when the server and the client are unable to initiate the download.
1047    CHECK(action == response_handler_action_.get());
1048    const InstallPlan& plan = response_handler_action_->install_plan();
1049    UpdateLastCheckedTime();
1050    new_version_ = plan.version;
1051    new_payload_size_ = plan.payload_size;
1052    SetupDownload();
1053    SetupCpuSharesManagement();
1054    SetStatusAndNotify(UpdateStatus::UPDATE_AVAILABLE);
1055  } else if (type == DownloadAction::StaticType()) {
1056    SetStatusAndNotify(UpdateStatus::FINALIZING);
1057  }
1058}
1059
1060void UpdateAttempter::BytesReceived(uint64_t bytes_received, uint64_t total) {
1061  double progress = static_cast<double>(bytes_received) /
1062      static_cast<double>(total);
1063  // Self throttle based on progress. Also send notifications if
1064  // progress is too slow.
1065  const double kDeltaPercent = 0.01;  // 1%
1066  if (status_ != UpdateStatus::DOWNLOADING ||
1067      bytes_received == total ||
1068      progress - download_progress_ >= kDeltaPercent ||
1069      TimeTicks::Now() - last_notify_time_ >= TimeDelta::FromSeconds(10)) {
1070    download_progress_ = progress;
1071    SetStatusAndNotify(UpdateStatus::DOWNLOADING);
1072  }
1073}
1074
1075bool UpdateAttempter::ResetStatus() {
1076  LOG(INFO) << "Attempting to reset state from "
1077            << UpdateStatusToString(status_) << " to UpdateStatus::IDLE";
1078
1079  switch (status_) {
1080    case UpdateStatus::IDLE:
1081      // no-op.
1082      return true;
1083
1084    case UpdateStatus::UPDATED_NEED_REBOOT:  {
1085      bool ret_value = true;
1086      status_ = UpdateStatus::IDLE;
1087
1088      // Remove the reboot marker so that if the machine is rebooted
1089      // after resetting to idle state, it doesn't go back to
1090      // UpdateStatus::UPDATED_NEED_REBOOT state.
1091      ret_value = prefs_->Delete(kPrefsUpdateCompletedOnBootId) && ret_value;
1092      ret_value = prefs_->Delete(kPrefsUpdateCompletedBootTime) && ret_value;
1093
1094      // Update the boot flags so the current slot has higher priority.
1095      BootControlInterface* boot_control = system_state_->boot_control();
1096      if (!boot_control->SetActiveBootSlot(boot_control->GetCurrentSlot()))
1097        ret_value = false;
1098
1099      // Notify the PayloadState that the successful payload was canceled.
1100      system_state_->payload_state()->ResetUpdateStatus();
1101
1102      // The previous version is used to report back to omaha after reboot that
1103      // we actually rebooted into the new version from this "prev-version". We
1104      // need to clear out this value now to prevent it being sent on the next
1105      // updatecheck request.
1106      ret_value = prefs_->SetString(kPrefsPreviousVersion, "") && ret_value;
1107
1108      LOG(INFO) << "Reset status " << (ret_value ? "successful" : "failed");
1109      return ret_value;
1110    }
1111
1112    default:
1113      LOG(ERROR) << "Reset not allowed in this state.";
1114      return false;
1115  }
1116}
1117
1118bool UpdateAttempter::GetStatus(int64_t* last_checked_time,
1119                                double* progress,
1120                                string* current_operation,
1121                                string* new_version,
1122                                int64_t* new_payload_size) {
1123  *last_checked_time = last_checked_time_;
1124  *progress = download_progress_;
1125  *current_operation = UpdateStatusToString(status_);
1126  *new_version = new_version_;
1127  *new_payload_size = new_payload_size_;
1128  return true;
1129}
1130
1131void UpdateAttempter::UpdateBootFlags() {
1132  if (update_boot_flags_running_) {
1133    LOG(INFO) << "Update boot flags running, nothing to do.";
1134    return;
1135  }
1136  if (updated_boot_flags_) {
1137    LOG(INFO) << "Already updated boot flags. Skipping.";
1138    if (start_action_processor_) {
1139      ScheduleProcessingStart();
1140    }
1141    return;
1142  }
1143  // This is purely best effort. Failures should be logged by Subprocess. Run
1144  // the script asynchronously to avoid blocking the event loop regardless of
1145  // the script runtime.
1146  update_boot_flags_running_ = true;
1147  LOG(INFO) << "Marking booted slot as good.";
1148  if (!system_state_->boot_control()->MarkBootSuccessfulAsync(Bind(
1149          &UpdateAttempter::CompleteUpdateBootFlags, base::Unretained(this)))) {
1150    LOG(ERROR) << "Failed to mark current boot as successful.";
1151    CompleteUpdateBootFlags(false);
1152  }
1153}
1154
1155void UpdateAttempter::CompleteUpdateBootFlags(bool successful) {
1156  update_boot_flags_running_ = false;
1157  updated_boot_flags_ = true;
1158  if (start_action_processor_) {
1159    ScheduleProcessingStart();
1160  }
1161}
1162
1163void UpdateAttempter::BroadcastStatus() {
1164  if (!dbus_adaptor_)
1165    return;
1166  last_notify_time_ = TimeTicks::Now();
1167  dbus_adaptor_->SendStatusUpdateSignal(
1168      last_checked_time_,
1169      download_progress_,
1170      UpdateStatusToString(status_),
1171      new_version_.c_str(),
1172      new_payload_size_);
1173}
1174
1175uint32_t UpdateAttempter::GetErrorCodeFlags()  {
1176  uint32_t flags = 0;
1177
1178  if (!system_state_->hardware()->IsNormalBootMode())
1179    flags |= static_cast<uint32_t>(ErrorCode::kDevModeFlag);
1180
1181  if (response_handler_action_.get() &&
1182      response_handler_action_->install_plan().is_resume)
1183    flags |= static_cast<uint32_t>(ErrorCode::kResumedFlag);
1184
1185  if (!system_state_->hardware()->IsOfficialBuild())
1186    flags |= static_cast<uint32_t>(ErrorCode::kTestImageFlag);
1187
1188  if (omaha_request_params_->update_url() !=
1189      constants::kOmahaDefaultProductionURL) {
1190    flags |= static_cast<uint32_t>(ErrorCode::kTestOmahaUrlFlag);
1191  }
1192
1193  return flags;
1194}
1195
1196bool UpdateAttempter::ShouldCancel(ErrorCode* cancel_reason) {
1197  // Check if the channel we're attempting to update to is the same as the
1198  // target channel currently chosen by the user.
1199  OmahaRequestParams* params = system_state_->request_params();
1200  if (params->download_channel() != params->target_channel()) {
1201    LOG(ERROR) << "Aborting download as target channel: "
1202               << params->target_channel()
1203               << " is different from the download channel: "
1204               << params->download_channel();
1205    *cancel_reason = ErrorCode::kUpdateCanceledByChannelChange;
1206    return true;
1207  }
1208
1209  return false;
1210}
1211
1212void UpdateAttempter::SetStatusAndNotify(UpdateStatus status) {
1213  status_ = status;
1214  BroadcastStatus();
1215}
1216
1217void UpdateAttempter::CreatePendingErrorEvent(AbstractAction* action,
1218                                              ErrorCode code) {
1219  if (error_event_.get()) {
1220    // This shouldn't really happen.
1221    LOG(WARNING) << "There's already an existing pending error event.";
1222    return;
1223  }
1224
1225  // For now assume that a generic Omaha response action failure means that
1226  // there's no update so don't send an event. Also, double check that the
1227  // failure has not occurred while sending an error event -- in which case
1228  // don't schedule another. This shouldn't really happen but just in case...
1229  if ((action->Type() == OmahaResponseHandlerAction::StaticType() &&
1230       code == ErrorCode::kError) ||
1231      status_ == UpdateStatus::REPORTING_ERROR_EVENT) {
1232    return;
1233  }
1234
1235  // Classify the code to generate the appropriate result so that
1236  // the Borgmon charts show up the results correctly.
1237  // Do this before calling GetErrorCodeForAction which could potentially
1238  // augment the bit representation of code and thus cause no matches for
1239  // the switch cases below.
1240  OmahaEvent::Result event_result;
1241  switch (code) {
1242    case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1243    case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1244    case ErrorCode::kOmahaUpdateDeferredForBackoff:
1245      event_result = OmahaEvent::kResultUpdateDeferred;
1246      break;
1247    default:
1248      event_result = OmahaEvent::kResultError;
1249      break;
1250  }
1251
1252  code = GetErrorCodeForAction(action, code);
1253  fake_update_success_ = code == ErrorCode::kPostinstallBootedFromFirmwareB;
1254
1255  // Compute the final error code with all the bit flags to be sent to Omaha.
1256  code = static_cast<ErrorCode>(
1257      static_cast<uint32_t>(code) | GetErrorCodeFlags());
1258  error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
1259                                    event_result,
1260                                    code));
1261}
1262
1263bool UpdateAttempter::ScheduleErrorEventAction() {
1264  if (error_event_.get() == nullptr)
1265    return false;
1266
1267  LOG(ERROR) << "Update failed.";
1268  system_state_->payload_state()->UpdateFailed(error_event_->error_code);
1269
1270  // Send it to Omaha.
1271  LOG(INFO) << "Reporting the error event";
1272  shared_ptr<OmahaRequestAction> error_event_action(
1273      new OmahaRequestAction(system_state_,
1274                             error_event_.release(),  // Pass ownership.
1275                             brillo::make_unique_ptr(new LibcurlHttpFetcher(
1276                                 GetProxyResolver(),
1277                                 system_state_->hardware())),
1278                             false));
1279  actions_.push_back(shared_ptr<AbstractAction>(error_event_action));
1280  processor_->EnqueueAction(error_event_action.get());
1281  SetStatusAndNotify(UpdateStatus::REPORTING_ERROR_EVENT);
1282  processor_->StartProcessing();
1283  return true;
1284}
1285
1286void UpdateAttempter::SetCpuShares(utils::CpuShares shares) {
1287  if (shares_ == shares) {
1288    return;
1289  }
1290  if (utils::SetCpuShares(shares)) {
1291    shares_ = shares;
1292    LOG(INFO) << "CPU shares = " << shares_;
1293  }
1294}
1295
1296void UpdateAttempter::SetupCpuSharesManagement() {
1297  if (manage_shares_id_ != MessageLoop::kTaskIdNull) {
1298    LOG(ERROR) << "Cpu shares timeout source hasn't been destroyed.";
1299    CleanupCpuSharesManagement();
1300  }
1301  const int kCpuSharesTimeout = 2 * 60 * 60;  // 2 hours
1302  manage_shares_id_ = MessageLoop::current()->PostDelayedTask(
1303      FROM_HERE,
1304      Bind(&UpdateAttempter::ManageCpuSharesCallback, base::Unretained(this)),
1305      TimeDelta::FromSeconds(kCpuSharesTimeout));
1306  SetCpuShares(utils::kCpuSharesLow);
1307}
1308
1309void UpdateAttempter::CleanupCpuSharesManagement() {
1310  if (manage_shares_id_ != MessageLoop::kTaskIdNull) {
1311    // The UpdateAttempter is instantiated by default by the FakeSystemState,
1312    // even when it is not used. We check the manage_shares_id_ before calling
1313    // the MessageLoop::current() since the unit test using a FakeSystemState
1314    // may have not define a MessageLoop for the current thread.
1315    MessageLoop::current()->CancelTask(manage_shares_id_);
1316    manage_shares_id_ = MessageLoop::kTaskIdNull;
1317  }
1318  SetCpuShares(utils::kCpuSharesNormal);
1319}
1320
1321void UpdateAttempter::ScheduleProcessingStart() {
1322  LOG(INFO) << "Scheduling an action processor start.";
1323  start_action_processor_ = false;
1324  MessageLoop::current()->PostTask(
1325      FROM_HERE,
1326      Bind([this] { this->processor_->StartProcessing(); }));
1327}
1328
1329void UpdateAttempter::ManageCpuSharesCallback() {
1330  SetCpuShares(utils::kCpuSharesNormal);
1331  manage_shares_id_ = MessageLoop::kTaskIdNull;
1332}
1333
1334void UpdateAttempter::DisableDeltaUpdateIfNeeded() {
1335  int64_t delta_failures;
1336  if (omaha_request_params_->delta_okay() &&
1337      prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) &&
1338      delta_failures >= kMaxDeltaUpdateFailures) {
1339    LOG(WARNING) << "Too many delta update failures, forcing full update.";
1340    omaha_request_params_->set_delta_okay(false);
1341  }
1342}
1343
1344void UpdateAttempter::MarkDeltaUpdateFailure() {
1345  // Don't try to resume a failed delta update.
1346  DeltaPerformer::ResetUpdateProgress(prefs_, false);
1347  int64_t delta_failures;
1348  if (!prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) ||
1349      delta_failures < 0) {
1350    delta_failures = 0;
1351  }
1352  prefs_->SetInt64(kPrefsDeltaUpdateFailures, ++delta_failures);
1353}
1354
1355void UpdateAttempter::SetupDownload() {
1356  MultiRangeHttpFetcher* fetcher =
1357      static_cast<MultiRangeHttpFetcher*>(download_action_->http_fetcher());
1358  fetcher->ClearRanges();
1359  if (response_handler_action_->install_plan().is_resume) {
1360    // Resuming an update so fetch the update manifest metadata first.
1361    int64_t manifest_metadata_size = 0;
1362    prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size);
1363    fetcher->AddRange(0, manifest_metadata_size);
1364    // If there're remaining unprocessed data blobs, fetch them. Be careful not
1365    // to request data beyond the end of the payload to avoid 416 HTTP response
1366    // error codes.
1367    int64_t next_data_offset = 0;
1368    prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset);
1369    uint64_t resume_offset = manifest_metadata_size + next_data_offset;
1370    if (resume_offset < response_handler_action_->install_plan().payload_size) {
1371      fetcher->AddRange(resume_offset);
1372    }
1373  } else {
1374    fetcher->AddRange(0);
1375  }
1376}
1377
1378void UpdateAttempter::PingOmaha() {
1379  if (!processor_->IsRunning()) {
1380    shared_ptr<OmahaRequestAction> ping_action(new OmahaRequestAction(
1381        system_state_,
1382        nullptr,
1383        brillo::make_unique_ptr(new LibcurlHttpFetcher(
1384            GetProxyResolver(),
1385            system_state_->hardware())),
1386        true));
1387    actions_.push_back(shared_ptr<OmahaRequestAction>(ping_action));
1388    processor_->set_delegate(nullptr);
1389    processor_->EnqueueAction(ping_action.get());
1390    // Call StartProcessing() synchronously here to avoid any race conditions
1391    // caused by multiple outstanding ping Omaha requests.  If we call
1392    // StartProcessing() asynchronously, the device can be suspended before we
1393    // get a chance to callback to StartProcessing().  When the device resumes
1394    // (assuming the device sleeps longer than the next update check period),
1395    // StartProcessing() is called back and at the same time, the next update
1396    // check is fired which eventually invokes StartProcessing().  A crash
1397    // can occur because StartProcessing() checks to make sure that the
1398    // processor is idle which it isn't due to the two concurrent ping Omaha
1399    // requests.
1400    processor_->StartProcessing();
1401  } else {
1402    LOG(WARNING) << "Action processor running, Omaha ping suppressed.";
1403  }
1404
1405  // Update the last check time here; it may be re-updated when an Omaha
1406  // response is received, but this will prevent us from repeatedly scheduling
1407  // checks in the case where a response is not received.
1408  UpdateLastCheckedTime();
1409
1410  // Update the status which will schedule the next update check
1411  SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
1412  ScheduleUpdates();
1413}
1414
1415
1416bool UpdateAttempter::DecrementUpdateCheckCount() {
1417  int64_t update_check_count_value;
1418
1419  if (!prefs_->Exists(kPrefsUpdateCheckCount)) {
1420    // This file does not exist. This means we haven't started our update
1421    // check count down yet, so nothing more to do. This file will be created
1422    // later when we first satisfy the wall-clock-based-wait period.
1423    LOG(INFO) << "No existing update check count. That's normal.";
1424    return true;
1425  }
1426
1427  if (prefs_->GetInt64(kPrefsUpdateCheckCount, &update_check_count_value)) {
1428    // Only if we're able to read a proper integer value, then go ahead
1429    // and decrement and write back the result in the same file, if needed.
1430    LOG(INFO) << "Update check count = " << update_check_count_value;
1431
1432    if (update_check_count_value == 0) {
1433      // It could be 0, if, for some reason, the file didn't get deleted
1434      // when we set our status to waiting for reboot. so we just leave it
1435      // as is so that we can prevent another update_check wait for this client.
1436      LOG(INFO) << "Not decrementing update check count as it's already 0.";
1437      return true;
1438    }
1439
1440    if (update_check_count_value > 0)
1441      update_check_count_value--;
1442    else
1443      update_check_count_value = 0;
1444
1445    // Write out the new value of update_check_count_value.
1446    if (prefs_->SetInt64(kPrefsUpdateCheckCount, update_check_count_value)) {
1447      // We successfully wrote out te new value, so enable the
1448      // update check based wait.
1449      LOG(INFO) << "New update check count = " << update_check_count_value;
1450      return true;
1451    }
1452  }
1453
1454  LOG(INFO) << "Deleting update check count state due to read/write errors.";
1455
1456  // We cannot read/write to the file, so disable the update check based wait
1457  // so that we don't get stuck in this OS version by any chance (which could
1458  // happen if there's some bug that causes to read/write incorrectly).
1459  // Also attempt to delete the file to do our best effort to cleanup.
1460  prefs_->Delete(kPrefsUpdateCheckCount);
1461  return false;
1462}
1463
1464
1465void UpdateAttempter::UpdateEngineStarted() {
1466  // If we just booted into a new update, keep the previous OS version
1467  // in case we rebooted because of a crash of the old version, so we
1468  // can do a proper crash report with correct information.
1469  // This must be done before calling
1470  // system_state_->payload_state()->UpdateEngineStarted() since it will
1471  // delete SystemUpdated marker file.
1472  if (system_state_->system_rebooted() &&
1473      prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1474    if (!prefs_->GetString(kPrefsPreviousVersion, &prev_version_)) {
1475      // If we fail to get the version string, make sure it stays empty.
1476      prev_version_.clear();
1477    }
1478  }
1479
1480  system_state_->payload_state()->UpdateEngineStarted();
1481  StartP2PAtStartup();
1482}
1483
1484bool UpdateAttempter::StartP2PAtStartup() {
1485  if (system_state_ == nullptr ||
1486      !system_state_->p2p_manager()->IsP2PEnabled()) {
1487    LOG(INFO) << "Not starting p2p at startup since it's not enabled.";
1488    return false;
1489  }
1490
1491  if (system_state_->p2p_manager()->CountSharedFiles() < 1) {
1492    LOG(INFO) << "Not starting p2p at startup since our application "
1493              << "is not sharing any files.";
1494    return false;
1495  }
1496
1497  return StartP2PAndPerformHousekeeping();
1498}
1499
1500bool UpdateAttempter::StartP2PAndPerformHousekeeping() {
1501  if (system_state_ == nullptr)
1502    return false;
1503
1504  if (!system_state_->p2p_manager()->IsP2PEnabled()) {
1505    LOG(INFO) << "Not starting p2p since it's not enabled.";
1506    return false;
1507  }
1508
1509  LOG(INFO) << "Ensuring that p2p is running.";
1510  if (!system_state_->p2p_manager()->EnsureP2PRunning()) {
1511    LOG(ERROR) << "Error starting p2p.";
1512    return false;
1513  }
1514
1515  LOG(INFO) << "Performing p2p housekeeping.";
1516  if (!system_state_->p2p_manager()->PerformHousekeeping()) {
1517    LOG(ERROR) << "Error performing housekeeping for p2p.";
1518    return false;
1519  }
1520
1521  LOG(INFO) << "Done performing p2p housekeeping.";
1522  return true;
1523}
1524
1525bool UpdateAttempter::GetBootTimeAtUpdate(Time *out_boot_time) {
1526  // In case of an update_engine restart without a reboot, we stored the boot_id
1527  // when the update was completed by setting a pref, so we can check whether
1528  // the last update was on this boot or a previous one.
1529  string boot_id;
1530  TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
1531
1532  string update_completed_on_boot_id;
1533  if (!prefs_->Exists(kPrefsUpdateCompletedOnBootId) ||
1534      !prefs_->GetString(kPrefsUpdateCompletedOnBootId,
1535                         &update_completed_on_boot_id) ||
1536      update_completed_on_boot_id != boot_id)
1537    return false;
1538
1539  // Short-circuit avoiding the read in case out_boot_time is nullptr.
1540  if (out_boot_time) {
1541    int64_t boot_time = 0;
1542    // Since the kPrefsUpdateCompletedOnBootId was correctly set, this pref
1543    // should not fail.
1544    TEST_AND_RETURN_FALSE(
1545        prefs_->GetInt64(kPrefsUpdateCompletedBootTime, &boot_time));
1546    *out_boot_time = Time::FromInternalValue(boot_time);
1547  }
1548  return true;
1549}
1550
1551bool UpdateAttempter::IsUpdateRunningOrScheduled() {
1552  return ((status_ != UpdateStatus::IDLE &&
1553           status_ != UpdateStatus::UPDATED_NEED_REBOOT) ||
1554          waiting_for_scheduled_check_);
1555}
1556
1557bool UpdateAttempter::IsAnyUpdateSourceAllowed() {
1558  // We allow updates from any source if either of these are true:
1559  //  * The device is running an unofficial (dev/test) image.
1560  //  * The debugd dev features are accessible (i.e. in devmode with no owner).
1561  // This protects users running a base image, while still allowing a specific
1562  // window (gated by the debug dev features) where `cros flash` is usable.
1563  if (!system_state_->hardware()->IsOfficialBuild()) {
1564    LOG(INFO) << "Non-official build; allowing any update source.";
1565    return true;
1566  }
1567
1568  // Even though the debugd tools are also gated on devmode, checking here can
1569  // save us a D-Bus call so it's worth doing explicitly.
1570  if (system_state_->hardware()->IsNormalBootMode()) {
1571    LOG(INFO) << "Not in devmode; disallowing custom update sources.";
1572    return false;
1573  }
1574
1575  // Official images in devmode are allowed a custom update source iff the
1576  // debugd dev tools are enabled.
1577  if (!debugd_proxy_)
1578    return false;
1579  int32_t dev_features = debugd::DEV_FEATURES_DISABLED;
1580  brillo::ErrorPtr error;
1581  bool success = debugd_proxy_->QueryDevFeatures(&dev_features, &error);
1582
1583  // Some boards may not include debugd so it's expected that this may fail,
1584  // in which case we default to disallowing custom update sources.
1585  if (success && !(dev_features & debugd::DEV_FEATURES_DISABLED)) {
1586    LOG(INFO) << "Debugd dev tools enabled; allowing any update source.";
1587    return true;
1588  }
1589  LOG(INFO) << "Debugd dev tools disabled; disallowing custom update sources.";
1590  return false;
1591}
1592
1593}  // namespace chromeos_update_engine
1594