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