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/certificate_checker.h"
43 #include "update_engine/common/boot_control_interface.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/multi_range_http_fetcher.h"
48 #include "update_engine/common/platform_constants.h"
49 #include "update_engine/common/prefs_interface.h"
50 #include "update_engine/common/subprocess.h"
51 #include "update_engine/common/utils.h"
52 #include "update_engine/libcurl_http_fetcher.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 
68 using base::Bind;
69 using base::Callback;
70 using base::Time;
71 using base::TimeDelta;
72 using base::TimeTicks;
73 using brillo::MessageLoop;
74 using chromeos_update_manager::EvalStatus;
75 using chromeos_update_manager::Policy;
76 using chromeos_update_manager::UpdateCheckParams;
77 using std::set;
78 using std::shared_ptr;
79 using std::string;
80 using std::vector;
81 
82 namespace chromeos_update_engine {
83 
84 const int UpdateAttempter::kMaxDeltaUpdateFailures = 3;
85 
86 namespace {
87 const int kMaxConsecutiveObeyProxyRequests = 20;
88 
89 // Minimum threshold to broadcast an status update in progress and time.
90 const double kBroadcastThresholdProgress = 0.01;  // 1%
91 const 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().
96 const char kAUTestURLRequest[] = "autest";
97 const 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.
GetErrorCodeForAction(AbstractAction * action,ErrorCode code)104 ErrorCode 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 
UpdateAttempter(SystemState * system_state,CertificateChecker * cert_checker,LibCrosProxy * libcros_proxy)122 UpdateAttempter::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 
135 UpdateAttempter::~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 
144 void 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 
166 void 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 
181 void UpdateAttempter::CertificateChecked(ServerToCheck server_to_check,
182                                          CertificateCheckResult result) {
183   metrics::ReportCertificateCheckMetrics(system_state_,
184                                          server_to_check,
185                                          result);
186 }
187 
188 bool 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 
224 void 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 
249 void 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 
310 void 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 
329 void 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 
362 bool 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 
461 void 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 
569 void 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 
584 void 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 
595 void 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 
680 bool 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 
744 bool 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 
751 BootControlInterface::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 
779 void 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 
811 bool 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 
824 void 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 
834 bool 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 
845 void 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 
886 void UpdateAttempter::UpdateLastCheckedTime() {
887   last_checked_time_ = system_state_->clock()->GetWallclockTime().ToTimeT();
888 }
889 
890 // Delegate methods:
891 void 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 
972 void 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.
984 void 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 
1047 void 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 
1065 void UpdateAttempter::DownloadComplete() {
1066   system_state_->payload_state()->DownloadComplete();
1067 }
1068 
1069 bool UpdateAttempter::OnCheckForUpdates(brillo::ErrorPtr* error) {
1070   CheckForUpdate(
1071       "" /* app_version */, "" /* omaha_url */, true /* interactive */);
1072   return true;
1073 }
1074 
1075 bool 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 
1093 bool 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 
1107 void 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 
1119 bool 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       // Mark the current slot as successful again, since marking it as active
1144       // may reset the successful bit. We ignore the result of whether marking
1145       // the current slot as successful worked.
1146       if (!boot_control->MarkBootSuccessfulAsync(Bind([](bool successful){})))
1147         ret_value = false;
1148 
1149       // Notify the PayloadState that the successful payload was canceled.
1150       system_state_->payload_state()->ResetUpdateStatus();
1151 
1152       // The previous version is used to report back to omaha after reboot that
1153       // we actually rebooted into the new version from this "prev-version". We
1154       // need to clear out this value now to prevent it being sent on the next
1155       // updatecheck request.
1156       ret_value = prefs_->SetString(kPrefsPreviousVersion, "") && ret_value;
1157 
1158       LOG(INFO) << "Reset status " << (ret_value ? "successful" : "failed");
1159       return ret_value;
1160     }
1161 
1162     default:
1163       LOG(ERROR) << "Reset not allowed in this state.";
1164       return false;
1165   }
1166 }
1167 
1168 bool UpdateAttempter::GetStatus(int64_t* last_checked_time,
1169                                 double* progress,
1170                                 string* current_operation,
1171                                 string* new_version,
1172                                 int64_t* new_payload_size) {
1173   *last_checked_time = last_checked_time_;
1174   *progress = download_progress_;
1175   *current_operation = UpdateStatusToString(status_);
1176   *new_version = new_version_;
1177   *new_payload_size = new_payload_size_;
1178   return true;
1179 }
1180 
1181 void UpdateAttempter::UpdateBootFlags() {
1182   if (update_boot_flags_running_) {
1183     LOG(INFO) << "Update boot flags running, nothing to do.";
1184     return;
1185   }
1186   if (updated_boot_flags_) {
1187     LOG(INFO) << "Already updated boot flags. Skipping.";
1188     if (start_action_processor_) {
1189       ScheduleProcessingStart();
1190     }
1191     return;
1192   }
1193   // This is purely best effort. Failures should be logged by Subprocess. Run
1194   // the script asynchronously to avoid blocking the event loop regardless of
1195   // the script runtime.
1196   update_boot_flags_running_ = true;
1197   LOG(INFO) << "Marking booted slot as good.";
1198   if (!system_state_->boot_control()->MarkBootSuccessfulAsync(Bind(
1199           &UpdateAttempter::CompleteUpdateBootFlags, base::Unretained(this)))) {
1200     LOG(ERROR) << "Failed to mark current boot as successful.";
1201     CompleteUpdateBootFlags(false);
1202   }
1203 }
1204 
1205 void UpdateAttempter::CompleteUpdateBootFlags(bool successful) {
1206   update_boot_flags_running_ = false;
1207   updated_boot_flags_ = true;
1208   if (start_action_processor_) {
1209     ScheduleProcessingStart();
1210   }
1211 }
1212 
1213 void UpdateAttempter::BroadcastStatus() {
1214   for (const auto& observer : service_observers_) {
1215     observer->SendStatusUpdate(last_checked_time_,
1216                                download_progress_,
1217                                status_,
1218                                new_version_,
1219                                new_payload_size_);
1220   }
1221   last_notify_time_ = TimeTicks::Now();
1222 }
1223 
1224 void UpdateAttempter::BroadcastChannel() {
1225   for (const auto& observer : service_observers_) {
1226     observer->SendChannelChangeUpdate(
1227         system_state_->request_params()->target_channel());
1228   }
1229 }
1230 
1231 uint32_t UpdateAttempter::GetErrorCodeFlags()  {
1232   uint32_t flags = 0;
1233 
1234   if (!system_state_->hardware()->IsNormalBootMode())
1235     flags |= static_cast<uint32_t>(ErrorCode::kDevModeFlag);
1236 
1237   if (response_handler_action_.get() &&
1238       response_handler_action_->install_plan().is_resume)
1239     flags |= static_cast<uint32_t>(ErrorCode::kResumedFlag);
1240 
1241   if (!system_state_->hardware()->IsOfficialBuild())
1242     flags |= static_cast<uint32_t>(ErrorCode::kTestImageFlag);
1243 
1244   if (omaha_request_params_->update_url() !=
1245       constants::kOmahaDefaultProductionURL) {
1246     flags |= static_cast<uint32_t>(ErrorCode::kTestOmahaUrlFlag);
1247   }
1248 
1249   return flags;
1250 }
1251 
1252 bool UpdateAttempter::ShouldCancel(ErrorCode* cancel_reason) {
1253   // Check if the channel we're attempting to update to is the same as the
1254   // target channel currently chosen by the user.
1255   OmahaRequestParams* params = system_state_->request_params();
1256   if (params->download_channel() != params->target_channel()) {
1257     LOG(ERROR) << "Aborting download as target channel: "
1258                << params->target_channel()
1259                << " is different from the download channel: "
1260                << params->download_channel();
1261     *cancel_reason = ErrorCode::kUpdateCanceledByChannelChange;
1262     return true;
1263   }
1264 
1265   return false;
1266 }
1267 
1268 void UpdateAttempter::SetStatusAndNotify(UpdateStatus status) {
1269   status_ = status;
1270   BroadcastStatus();
1271 }
1272 
1273 void UpdateAttempter::CreatePendingErrorEvent(AbstractAction* action,
1274                                               ErrorCode code) {
1275   if (error_event_.get()) {
1276     // This shouldn't really happen.
1277     LOG(WARNING) << "There's already an existing pending error event.";
1278     return;
1279   }
1280 
1281   // For now assume that a generic Omaha response action failure means that
1282   // there's no update so don't send an event. Also, double check that the
1283   // failure has not occurred while sending an error event -- in which case
1284   // don't schedule another. This shouldn't really happen but just in case...
1285   if ((action->Type() == OmahaResponseHandlerAction::StaticType() &&
1286        code == ErrorCode::kError) ||
1287       status_ == UpdateStatus::REPORTING_ERROR_EVENT) {
1288     return;
1289   }
1290 
1291   // Classify the code to generate the appropriate result so that
1292   // the Borgmon charts show up the results correctly.
1293   // Do this before calling GetErrorCodeForAction which could potentially
1294   // augment the bit representation of code and thus cause no matches for
1295   // the switch cases below.
1296   OmahaEvent::Result event_result;
1297   switch (code) {
1298     case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1299     case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1300     case ErrorCode::kOmahaUpdateDeferredForBackoff:
1301       event_result = OmahaEvent::kResultUpdateDeferred;
1302       break;
1303     default:
1304       event_result = OmahaEvent::kResultError;
1305       break;
1306   }
1307 
1308   code = GetErrorCodeForAction(action, code);
1309   fake_update_success_ = code == ErrorCode::kPostinstallBootedFromFirmwareB;
1310 
1311   // Compute the final error code with all the bit flags to be sent to Omaha.
1312   code = static_cast<ErrorCode>(
1313       static_cast<uint32_t>(code) | GetErrorCodeFlags());
1314   error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
1315                                     event_result,
1316                                     code));
1317 }
1318 
1319 bool UpdateAttempter::ScheduleErrorEventAction() {
1320   if (error_event_.get() == nullptr)
1321     return false;
1322 
1323   LOG(ERROR) << "Update failed.";
1324   system_state_->payload_state()->UpdateFailed(error_event_->error_code);
1325 
1326   // Send it to Omaha.
1327   LOG(INFO) << "Reporting the error event";
1328   shared_ptr<OmahaRequestAction> error_event_action(
1329       new OmahaRequestAction(system_state_,
1330                              error_event_.release(),  // Pass ownership.
1331                              brillo::make_unique_ptr(new LibcurlHttpFetcher(
1332                                  GetProxyResolver(),
1333                                  system_state_->hardware())),
1334                              false));
1335   actions_.push_back(shared_ptr<AbstractAction>(error_event_action));
1336   processor_->EnqueueAction(error_event_action.get());
1337   SetStatusAndNotify(UpdateStatus::REPORTING_ERROR_EVENT);
1338   processor_->StartProcessing();
1339   return true;
1340 }
1341 
1342 void UpdateAttempter::ScheduleProcessingStart() {
1343   LOG(INFO) << "Scheduling an action processor start.";
1344   start_action_processor_ = false;
1345   MessageLoop::current()->PostTask(
1346       FROM_HERE,
1347       Bind([](ActionProcessor* processor) { processor->StartProcessing(); },
1348            base::Unretained(processor_.get())));
1349 }
1350 
1351 void UpdateAttempter::DisableDeltaUpdateIfNeeded() {
1352   int64_t delta_failures;
1353   if (omaha_request_params_->delta_okay() &&
1354       prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) &&
1355       delta_failures >= kMaxDeltaUpdateFailures) {
1356     LOG(WARNING) << "Too many delta update failures, forcing full update.";
1357     omaha_request_params_->set_delta_okay(false);
1358   }
1359 }
1360 
1361 void UpdateAttempter::MarkDeltaUpdateFailure() {
1362   // Don't try to resume a failed delta update.
1363   DeltaPerformer::ResetUpdateProgress(prefs_, false);
1364   int64_t delta_failures;
1365   if (!prefs_->GetInt64(kPrefsDeltaUpdateFailures, &delta_failures) ||
1366       delta_failures < 0) {
1367     delta_failures = 0;
1368   }
1369   prefs_->SetInt64(kPrefsDeltaUpdateFailures, ++delta_failures);
1370 }
1371 
1372 void UpdateAttempter::SetupDownload() {
1373   MultiRangeHttpFetcher* fetcher =
1374       static_cast<MultiRangeHttpFetcher*>(download_action_->http_fetcher());
1375   fetcher->ClearRanges();
1376   if (response_handler_action_->install_plan().is_resume) {
1377     // Resuming an update so fetch the update manifest metadata first.
1378     int64_t manifest_metadata_size = 0;
1379     int64_t manifest_signature_size = 0;
1380     prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size);
1381     prefs_->GetInt64(kPrefsManifestSignatureSize, &manifest_signature_size);
1382     fetcher->AddRange(0, manifest_metadata_size + manifest_signature_size);
1383     // If there're remaining unprocessed data blobs, fetch them. Be careful not
1384     // to request data beyond the end of the payload to avoid 416 HTTP response
1385     // error codes.
1386     int64_t next_data_offset = 0;
1387     prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset);
1388     uint64_t resume_offset =
1389         manifest_metadata_size + manifest_signature_size + next_data_offset;
1390     if (resume_offset < response_handler_action_->install_plan().payload_size) {
1391       fetcher->AddRange(resume_offset);
1392     }
1393   } else {
1394     fetcher->AddRange(0);
1395   }
1396 }
1397 
1398 void UpdateAttempter::PingOmaha() {
1399   if (!processor_->IsRunning()) {
1400     shared_ptr<OmahaRequestAction> ping_action(new OmahaRequestAction(
1401         system_state_,
1402         nullptr,
1403         brillo::make_unique_ptr(new LibcurlHttpFetcher(
1404             GetProxyResolver(),
1405             system_state_->hardware())),
1406         true));
1407     actions_.push_back(shared_ptr<OmahaRequestAction>(ping_action));
1408     processor_->set_delegate(nullptr);
1409     processor_->EnqueueAction(ping_action.get());
1410     // Call StartProcessing() synchronously here to avoid any race conditions
1411     // caused by multiple outstanding ping Omaha requests.  If we call
1412     // StartProcessing() asynchronously, the device can be suspended before we
1413     // get a chance to callback to StartProcessing().  When the device resumes
1414     // (assuming the device sleeps longer than the next update check period),
1415     // StartProcessing() is called back and at the same time, the next update
1416     // check is fired which eventually invokes StartProcessing().  A crash
1417     // can occur because StartProcessing() checks to make sure that the
1418     // processor is idle which it isn't due to the two concurrent ping Omaha
1419     // requests.
1420     processor_->StartProcessing();
1421   } else {
1422     LOG(WARNING) << "Action processor running, Omaha ping suppressed.";
1423   }
1424 
1425   // Update the last check time here; it may be re-updated when an Omaha
1426   // response is received, but this will prevent us from repeatedly scheduling
1427   // checks in the case where a response is not received.
1428   UpdateLastCheckedTime();
1429 
1430   // Update the status which will schedule the next update check
1431   SetStatusAndNotify(UpdateStatus::UPDATED_NEED_REBOOT);
1432   ScheduleUpdates();
1433 }
1434 
1435 
1436 bool UpdateAttempter::DecrementUpdateCheckCount() {
1437   int64_t update_check_count_value;
1438 
1439   if (!prefs_->Exists(kPrefsUpdateCheckCount)) {
1440     // This file does not exist. This means we haven't started our update
1441     // check count down yet, so nothing more to do. This file will be created
1442     // later when we first satisfy the wall-clock-based-wait period.
1443     LOG(INFO) << "No existing update check count. That's normal.";
1444     return true;
1445   }
1446 
1447   if (prefs_->GetInt64(kPrefsUpdateCheckCount, &update_check_count_value)) {
1448     // Only if we're able to read a proper integer value, then go ahead
1449     // and decrement and write back the result in the same file, if needed.
1450     LOG(INFO) << "Update check count = " << update_check_count_value;
1451 
1452     if (update_check_count_value == 0) {
1453       // It could be 0, if, for some reason, the file didn't get deleted
1454       // when we set our status to waiting for reboot. so we just leave it
1455       // as is so that we can prevent another update_check wait for this client.
1456       LOG(INFO) << "Not decrementing update check count as it's already 0.";
1457       return true;
1458     }
1459 
1460     if (update_check_count_value > 0)
1461       update_check_count_value--;
1462     else
1463       update_check_count_value = 0;
1464 
1465     // Write out the new value of update_check_count_value.
1466     if (prefs_->SetInt64(kPrefsUpdateCheckCount, update_check_count_value)) {
1467       // We successfully wrote out te new value, so enable the
1468       // update check based wait.
1469       LOG(INFO) << "New update check count = " << update_check_count_value;
1470       return true;
1471     }
1472   }
1473 
1474   LOG(INFO) << "Deleting update check count state due to read/write errors.";
1475 
1476   // We cannot read/write to the file, so disable the update check based wait
1477   // so that we don't get stuck in this OS version by any chance (which could
1478   // happen if there's some bug that causes to read/write incorrectly).
1479   // Also attempt to delete the file to do our best effort to cleanup.
1480   prefs_->Delete(kPrefsUpdateCheckCount);
1481   return false;
1482 }
1483 
1484 
1485 void UpdateAttempter::UpdateEngineStarted() {
1486   // If we just booted into a new update, keep the previous OS version
1487   // in case we rebooted because of a crash of the old version, so we
1488   // can do a proper crash report with correct information.
1489   // This must be done before calling
1490   // system_state_->payload_state()->UpdateEngineStarted() since it will
1491   // delete SystemUpdated marker file.
1492   if (system_state_->system_rebooted() &&
1493       prefs_->Exists(kPrefsSystemUpdatedMarker)) {
1494     if (!prefs_->GetString(kPrefsPreviousVersion, &prev_version_)) {
1495       // If we fail to get the version string, make sure it stays empty.
1496       prev_version_.clear();
1497     }
1498   }
1499 
1500   system_state_->payload_state()->UpdateEngineStarted();
1501   StartP2PAtStartup();
1502 }
1503 
1504 bool UpdateAttempter::StartP2PAtStartup() {
1505   if (system_state_ == nullptr ||
1506       !system_state_->p2p_manager()->IsP2PEnabled()) {
1507     LOG(INFO) << "Not starting p2p at startup since it's not enabled.";
1508     return false;
1509   }
1510 
1511   if (system_state_->p2p_manager()->CountSharedFiles() < 1) {
1512     LOG(INFO) << "Not starting p2p at startup since our application "
1513               << "is not sharing any files.";
1514     return false;
1515   }
1516 
1517   return StartP2PAndPerformHousekeeping();
1518 }
1519 
1520 bool UpdateAttempter::StartP2PAndPerformHousekeeping() {
1521   if (system_state_ == nullptr)
1522     return false;
1523 
1524   if (!system_state_->p2p_manager()->IsP2PEnabled()) {
1525     LOG(INFO) << "Not starting p2p since it's not enabled.";
1526     return false;
1527   }
1528 
1529   LOG(INFO) << "Ensuring that p2p is running.";
1530   if (!system_state_->p2p_manager()->EnsureP2PRunning()) {
1531     LOG(ERROR) << "Error starting p2p.";
1532     return false;
1533   }
1534 
1535   LOG(INFO) << "Performing p2p housekeeping.";
1536   if (!system_state_->p2p_manager()->PerformHousekeeping()) {
1537     LOG(ERROR) << "Error performing housekeeping for p2p.";
1538     return false;
1539   }
1540 
1541   LOG(INFO) << "Done performing p2p housekeeping.";
1542   return true;
1543 }
1544 
1545 bool UpdateAttempter::GetBootTimeAtUpdate(Time *out_boot_time) {
1546   // In case of an update_engine restart without a reboot, we stored the boot_id
1547   // when the update was completed by setting a pref, so we can check whether
1548   // the last update was on this boot or a previous one.
1549   string boot_id;
1550   TEST_AND_RETURN_FALSE(utils::GetBootId(&boot_id));
1551 
1552   string update_completed_on_boot_id;
1553   if (!prefs_->Exists(kPrefsUpdateCompletedOnBootId) ||
1554       !prefs_->GetString(kPrefsUpdateCompletedOnBootId,
1555                          &update_completed_on_boot_id) ||
1556       update_completed_on_boot_id != boot_id)
1557     return false;
1558 
1559   // Short-circuit avoiding the read in case out_boot_time is nullptr.
1560   if (out_boot_time) {
1561     int64_t boot_time = 0;
1562     // Since the kPrefsUpdateCompletedOnBootId was correctly set, this pref
1563     // should not fail.
1564     TEST_AND_RETURN_FALSE(
1565         prefs_->GetInt64(kPrefsUpdateCompletedBootTime, &boot_time));
1566     *out_boot_time = Time::FromInternalValue(boot_time);
1567   }
1568   return true;
1569 }
1570 
1571 bool UpdateAttempter::IsUpdateRunningOrScheduled() {
1572   return ((status_ != UpdateStatus::IDLE &&
1573            status_ != UpdateStatus::UPDATED_NEED_REBOOT) ||
1574           waiting_for_scheduled_check_);
1575 }
1576 
1577 bool UpdateAttempter::IsAnyUpdateSourceAllowed() {
1578   // We allow updates from any source if either of these are true:
1579   //  * The device is running an unofficial (dev/test) image.
1580   //  * The debugd dev features are accessible (i.e. in devmode with no owner).
1581   // This protects users running a base image, while still allowing a specific
1582   // window (gated by the debug dev features) where `cros flash` is usable.
1583   if (!system_state_->hardware()->IsOfficialBuild()) {
1584     LOG(INFO) << "Non-official build; allowing any update source.";
1585     return true;
1586   }
1587 
1588   if (system_state_->hardware()->AreDevFeaturesEnabled()) {
1589     LOG(INFO) << "Developer features enabled; allowing custom update sources.";
1590     return true;
1591   }
1592 
1593   LOG(INFO)
1594       << "Developer features disabled; disallowing custom update sources.";
1595   return false;
1596 }
1597 
1598 }  // namespace chromeos_update_engine
1599