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