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