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 #ifndef UPDATE_ENGINE_UPDATE_ATTEMPTER_H_
18 #define UPDATE_ENGINE_UPDATE_ATTEMPTER_H_
19 
20 #include <time.h>
21 
22 #include <memory>
23 #include <set>
24 #include <string>
25 #include <utility>
26 #include <vector>
27 
28 #include <base/bind.h>
29 #include <base/time/time.h>
30 #include <gtest/gtest_prod.h>  // for FRIEND_TEST
31 
32 #include "debugd/dbus-proxies.h"
33 #include "update_engine/chrome_browser_proxy_resolver.h"
34 #include "update_engine/client_library/include/update_engine/update_status.h"
35 #include "update_engine/common/action_processor.h"
36 #include "update_engine/common/certificate_checker.h"
37 #include "update_engine/common/cpu_limiter.h"
38 #include "update_engine/libcros_proxy.h"
39 #include "update_engine/omaha_request_params.h"
40 #include "update_engine/omaha_response_handler_action.h"
41 #include "update_engine/payload_consumer/download_action.h"
42 #include "update_engine/payload_consumer/postinstall_runner_action.h"
43 #include "update_engine/proxy_resolver.h"
44 #include "update_engine/service_observer_interface.h"
45 #include "update_engine/system_state.h"
46 #include "update_engine/update_manager/policy.h"
47 #include "update_engine/update_manager/update_manager.h"
48 #include "update_engine/weave_service_interface.h"
49 
50 class MetricsLibraryInterface;
51 
52 namespace policy {
53 class PolicyProvider;
54 }
55 
56 namespace chromeos_update_engine {
57 
58 class UpdateEngineAdaptor;
59 
60 class UpdateAttempter : public ActionProcessorDelegate,
61                         public DownloadActionDelegate,
62                         public CertificateChecker::Observer,
63                         public WeaveServiceInterface::DelegateInterface,
64                         public PostinstallRunnerAction::DelegateInterface {
65  public:
66   using UpdateStatus = update_engine::UpdateStatus;
67   static const int kMaxDeltaUpdateFailures;
68 
69   UpdateAttempter(SystemState* system_state,
70                   CertificateChecker* cert_checker,
71                   LibCrosProxy* libcros_proxy,
72                   org::chromium::debugdProxyInterface* debugd_proxy);
73   ~UpdateAttempter() override;
74 
75   // Further initialization to be done post construction.
76   void Init();
77 
78   // Initiates scheduling of update checks.
79   virtual void ScheduleUpdates();
80 
81   // Checks for update and, if a newer version is available, attempts to update
82   // the system. Non-empty |in_app_version| or |in_update_url| prevents
83   // automatic detection of the parameter.  |target_channel| denotes a
84   // policy-mandated channel we are updating to, if not empty. If |obey_proxies|
85   // is true, the update will likely respect Chrome's proxy setting. For
86   // security reasons, we may still not honor them. |interactive| should be true
87   // if this was called from the user (ie dbus).
88   virtual void Update(const std::string& app_version,
89                       const std::string& omaha_url,
90                       const std::string& target_channel,
91                       const std::string& target_version_prefix,
92                       bool obey_proxies,
93                       bool interactive);
94 
95   // ActionProcessorDelegate methods:
96   void ProcessingDone(const ActionProcessor* processor,
97                       ErrorCode code) override;
98   void ProcessingStopped(const ActionProcessor* processor) override;
99   void ActionCompleted(ActionProcessor* processor,
100                        AbstractAction* action,
101                        ErrorCode code) override;
102 
103   // WeaveServiceInterface::DelegateInterface overrides.
104   bool OnCheckForUpdates(brillo::ErrorPtr* error) override;
105   bool OnTrackChannel(const std::string& channel,
106                       brillo::ErrorPtr* error) override;
107   bool GetWeaveState(int64_t* last_checked_time,
108                      double* progress,
109                      UpdateStatus* update_status,
110                      std::string* current_channel,
111                      std::string* tracking_channel) override;
112 
113   // PostinstallRunnerAction::DelegateInterface
114   void ProgressUpdate(double progress) override;
115 
116   // Resets the current state to UPDATE_STATUS_IDLE.
117   // Used by update_engine_client for restarting a new update without
118   // having to reboot once the previous update has reached
119   // UPDATE_STATUS_UPDATED_NEED_REBOOT state. This is used only
120   // for testing purposes.
121   virtual bool ResetStatus();
122 
123   // Returns the current status in the out params. Returns true on success.
124   virtual bool GetStatus(int64_t* last_checked_time,
125                          double* progress,
126                          std::string* current_operation,
127                          std::string* new_version,
128                          int64_t* new_size);
129 
130   // Runs chromeos-setgoodkernel, whose responsibility it is to mark the
131   // currently booted partition has high priority/permanent/etc. The execution
132   // is asynchronous. On completion, the action processor may be started
133   // depending on the |start_action_processor_| field. Note that every update
134   // attempt goes through this method.
135   void UpdateBootFlags();
136 
137   // Called when the boot flags have been updated.
138   void CompleteUpdateBootFlags(bool success);
139 
status()140   UpdateStatus status() const { return status_; }
141 
http_response_code()142   int http_response_code() const { return http_response_code_; }
set_http_response_code(int code)143   void set_http_response_code(int code) { http_response_code_ = code; }
144 
145   // This is the internal entry point for going through an
146   // update. If the current status is idle invokes Update.
147   // This is called by the DBus implementation.
148   virtual void CheckForUpdate(const std::string& app_version,
149                               const std::string& omaha_url,
150                               bool is_interactive);
151 
152   // This is the internal entry point for going through a rollback. This will
153   // attempt to run the postinstall on the non-active partition and set it as
154   // the partition to boot from. If |powerwash| is True, perform a powerwash
155   // as part of rollback. Returns True on success.
156   bool Rollback(bool powerwash);
157 
158   // This is the internal entry point for checking if we can rollback.
159   bool CanRollback() const;
160 
161   // This is the internal entry point for getting a rollback partition name,
162   // if one exists. It returns the bootable rollback kernel device partition
163   // name or empty string if none is available.
164   BootControlInterface::Slot GetRollbackSlot() const;
165 
166   // Initiates a reboot if the current state is
167   // UPDATED_NEED_REBOOT. Returns true on sucess, false otherwise.
168   bool RebootIfNeeded();
169 
170   // DownloadActionDelegate methods:
171   void BytesReceived(uint64_t bytes_progressed,
172                      uint64_t bytes_received,
173                      uint64_t total) override;
174 
175   // Returns that the update should be canceled when the download channel was
176   // changed.
177   bool ShouldCancel(ErrorCode* cancel_reason) override;
178 
179   void DownloadComplete() override;
180 
181   // Broadcasts the current status to all observers.
182   void BroadcastStatus();
183 
184   // Broadcasts the current tracking channel to all observers.
185   void BroadcastChannel();
186 
187   // Returns the special flags to be added to ErrorCode values based on the
188   // parameters used in the current update attempt.
189   uint32_t GetErrorCodeFlags();
190 
191   // Called at update_engine startup to do various house-keeping.
192   void UpdateEngineStarted();
193 
194   // Reloads the device policy from libbrillo. Note: This method doesn't
195   // cause a real-time policy fetch from the policy server. It just reloads the
196   // latest value that libbrillo has cached. libbrillo fetches the policies
197   // from the server asynchronously at its own frequency.
198   virtual void RefreshDevicePolicy();
199 
200   // Stores in |out_boot_time| the boottime (CLOCK_BOOTTIME) recorded at the
201   // time of the last successful update in the current boot. Returns false if
202   // there wasn't a successful update in the current boot.
203   virtual bool GetBootTimeAtUpdate(base::Time *out_boot_time);
204 
205   // Returns a version OS version that was being used before the last reboot,
206   // and if that reboot happended to be into an update (current version).
207   // This will return an empty string otherwise.
GetPrevVersion()208   std::string const& GetPrevVersion() const { return prev_version_; }
209 
210   // Returns the number of consecutive failed update checks.
consecutive_failed_update_checks()211   virtual unsigned int consecutive_failed_update_checks() const {
212     return consecutive_failed_update_checks_;
213   }
214 
215   // Returns the poll interval dictated by Omaha, if provided; zero otherwise.
server_dictated_poll_interval()216   virtual unsigned int server_dictated_poll_interval() const {
217     return server_dictated_poll_interval_;
218   }
219 
220   // Sets a callback to be used when either a forced update request is received
221   // (first argument set to true) or cleared by an update attempt (first
222   // argument set to false). The callback further encodes whether the forced
223   // check is an interactive one (second argument set to true). Takes ownership
224   // of the callback object. A null value disables callback on these events.
225   // Note that only one callback can be set, so effectively at most one client
226   // can be notified.
set_forced_update_pending_callback(base::Callback<void (bool,bool)> * callback)227   virtual void set_forced_update_pending_callback(
228       base::Callback<void(bool, bool)>*  // NOLINT(readability/function)
229       callback) {
230     forced_update_pending_callback_.reset(callback);
231   }
232 
233   // Returns true if we should allow updates from any source. In official builds
234   // we want to restrict updates to known safe sources, but under certain
235   // conditions it's useful to allow updating from anywhere (e.g. to allow
236   // 'cros flash' to function properly).
237   virtual bool IsAnyUpdateSourceAllowed();
238 
239   // Add and remove a service observer.
AddObserver(ServiceObserverInterface * observer)240   void AddObserver(ServiceObserverInterface* observer) {
241     service_observers_.insert(observer);
242   }
RemoveObserver(ServiceObserverInterface * observer)243   void RemoveObserver(ServiceObserverInterface* observer) {
244     service_observers_.erase(observer);
245   }
246 
247   // Remove all the observers.
ClearObservers()248   void ClearObservers() { service_observers_.clear(); }
249 
250  private:
251   // Update server URL for automated lab test.
252   static const char* const kTestUpdateUrl;
253 
254   // Friend declarations for testing purposes.
255   friend class UpdateAttempterUnderTest;
256   friend class UpdateAttempterTest;
257   FRIEND_TEST(UpdateAttempterTest, ActionCompletedDownloadTest);
258   FRIEND_TEST(UpdateAttempterTest, ActionCompletedErrorTest);
259   FRIEND_TEST(UpdateAttempterTest, ActionCompletedOmahaRequestTest);
260   FRIEND_TEST(UpdateAttempterTest, CreatePendingErrorEventTest);
261   FRIEND_TEST(UpdateAttempterTest, CreatePendingErrorEventResumedTest);
262   FRIEND_TEST(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest);
263   FRIEND_TEST(UpdateAttempterTest, MarkDeltaUpdateFailureTest);
264   FRIEND_TEST(UpdateAttempterTest, PingOmahaTest);
265   FRIEND_TEST(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest);
266   FRIEND_TEST(UpdateAttempterTest, ScheduleErrorEventActionTest);
267   FRIEND_TEST(UpdateAttempterTest, UpdateTest);
268   FRIEND_TEST(UpdateAttempterTest, ReportDailyMetrics);
269   FRIEND_TEST(UpdateAttempterTest, BootTimeInUpdateMarkerFile);
270 
271   // CertificateChecker::Observer method.
272   // Report metrics about the certificate being checked.
273   void CertificateChecked(ServerToCheck server_to_check,
274                           CertificateCheckResult result) override;
275 
276   // Checks if it's more than 24 hours since daily metrics were last
277   // reported and, if so, reports daily metrics. Returns |true| if
278   // metrics were reported, |false| otherwise.
279   bool CheckAndReportDailyMetrics();
280 
281   // Calculates and reports the age of the currently running OS. This
282   // is defined as the age of the /etc/lsb-release file.
283   void ReportOSAge();
284 
285   // Sets the status to the given status and notifies a status update over dbus.
286   void SetStatusAndNotify(UpdateStatus status);
287 
288   // Sets up the download parameters after receiving the update check response.
289   void SetupDownload();
290 
291   // Creates an error event object in |error_event_| to be included in an
292   // OmahaRequestAction once the current action processor is done.
293   void CreatePendingErrorEvent(AbstractAction* action, ErrorCode code);
294 
295   // If there's a pending error event allocated in |error_event_|, schedules an
296   // OmahaRequestAction with that event in the current processor, clears the
297   // pending event, updates the status and returns true. Returns false
298   // otherwise.
299   bool ScheduleErrorEventAction();
300 
301   // Schedules an event loop callback to start the action processor. This is
302   // scheduled asynchronously to unblock the event loop.
303   void ScheduleProcessingStart();
304 
305   // Checks if a full update is needed and forces it by updating the Omaha
306   // request params.
307   void DisableDeltaUpdateIfNeeded();
308 
309   // If this was a delta update attempt that failed, count it so that a full
310   // update can be tried when needed.
311   void MarkDeltaUpdateFailure();
312 
GetProxyResolver()313   ProxyResolver* GetProxyResolver() {
314 #if USE_LIBCROS
315     return obeying_proxies_ ?
316         reinterpret_cast<ProxyResolver*>(&chrome_proxy_resolver_) :
317         reinterpret_cast<ProxyResolver*>(&direct_proxy_resolver_);
318 #else
319     return &direct_proxy_resolver_;
320 #endif  // USE_LIBCROS
321   }
322 
323   // Sends a ping to Omaha.
324   // This is used after an update has been applied and we're waiting for the
325   // user to reboot.  This ping helps keep the number of actives count
326   // accurate in case a user takes a long time to reboot the device after an
327   // update has been applied.
328   void PingOmaha();
329 
330   // Helper method of Update() to calculate the update-related parameters
331   // from various sources and set the appropriate state. Please refer to
332   // Update() method for the meaning of the parametes.
333   bool CalculateUpdateParams(const std::string& app_version,
334                              const std::string& omaha_url,
335                              const std::string& target_channel,
336                              const std::string& target_version_prefix,
337                              bool obey_proxies,
338                              bool interactive);
339 
340   // Calculates all the scattering related parameters (such as waiting period,
341   // which type of scattering is enabled, etc.) and also updates/deletes
342   // the corresponding prefs file used in scattering. Should be called
343   // only after the device policy has been loaded and set in the system_state_.
344   void CalculateScatteringParams(bool is_interactive);
345 
346   // Sets a random value for the waiting period to wait for before downloading
347   // an update, if one available. This value will be upperbounded by the
348   // scatter factor value specified from policy.
349   void GenerateNewWaitingPeriod();
350 
351   // Helper method of Update() and Rollback() to construct the sequence of
352   // actions to be performed for the postinstall.
353   // |previous_action| is the previous action to get
354   // bonded with the install_plan that gets passed to postinstall.
355   void BuildPostInstallActions(InstallPlanAction* previous_action);
356 
357   // Helper method of Update() to construct the sequence of actions to
358   // be performed for an update check. Please refer to
359   // Update() method for the meaning of the parameters.
360   void BuildUpdateActions(bool interactive);
361 
362   // Decrements the count in the kUpdateCheckCountFilePath.
363   // Returns True if successfully decremented, false otherwise.
364   bool DecrementUpdateCheckCount();
365 
366   // Starts p2p and performs housekeeping. Returns true only if p2p is
367   // running and housekeeping was done.
368   bool StartP2PAndPerformHousekeeping();
369 
370   // Calculates whether peer-to-peer should be used. Sets the
371   // |use_p2p_to_download_| and |use_p2p_to_share_| parameters
372   // on the |omaha_request_params_| object.
373   void CalculateP2PParams(bool interactive);
374 
375   // Starts P2P if it's enabled and there are files to actually share.
376   // Called only at program startup. Returns true only if p2p was
377   // started and housekeeping was performed.
378   bool StartP2PAtStartup();
379 
380   // Writes to the processing completed marker. Does nothing if
381   // |update_completed_marker_| is empty.
382   void WriteUpdateCompletedMarker();
383 
384   // Sends a D-Bus message to the Chrome OS power manager asking it to reboot
385   // the system. Returns true on success.
386   bool RequestPowerManagerReboot();
387 
388   // Reboots the system directly by calling /sbin/shutdown. Returns true on
389   // success.
390   bool RebootDirectly();
391 
392   // Callback for the async UpdateCheckAllowed policy request. If |status| is
393   // |EvalStatus::kSucceeded|, either runs or suppresses periodic update checks,
394   // based on the content of |params|. Otherwise, retries the policy request.
395   void OnUpdateScheduled(
396       chromeos_update_manager::EvalStatus status,
397       const chromeos_update_manager::UpdateCheckParams& params);
398 
399   // Updates the time an update was last attempted to the current time.
400   void UpdateLastCheckedTime();
401 
402   // Returns whether an update is currently running or scheduled.
403   bool IsUpdateRunningOrScheduled();
404 
405   // Last status notification timestamp used for throttling. Use monotonic
406   // TimeTicks to ensure that notifications are sent even if the system clock is
407   // set back in the middle of an update.
408   base::TimeTicks last_notify_time_;
409 
410   std::vector<std::shared_ptr<AbstractAction>> actions_;
411   std::unique_ptr<ActionProcessor> processor_;
412 
413   // External state of the system outside the update_engine process
414   // carved out separately to mock out easily in unit tests.
415   SystemState* system_state_;
416 
417   // Pointer to the certificate checker instance to use.
418   CertificateChecker* cert_checker_;
419 
420   // The list of services observing changes in the updater.
421   std::set<ServiceObserverInterface*> service_observers_;
422 
423   // Pointer to the OmahaResponseHandlerAction in the actions_ vector.
424   std::shared_ptr<OmahaResponseHandlerAction> response_handler_action_;
425 
426   // Pointer to the DownloadAction in the actions_ vector.
427   std::shared_ptr<DownloadAction> download_action_;
428 
429   // Pointer to the preferences store interface. This is just a cached
430   // copy of system_state->prefs() because it's used in many methods and
431   // is convenient this way.
432   PrefsInterface* prefs_ = nullptr;
433 
434   // Pending error event, if any.
435   std::unique_ptr<OmahaEvent> error_event_;
436 
437   // If we should request a reboot even tho we failed the update
438   bool fake_update_success_ = false;
439 
440   // HTTP server response code from the last HTTP request action.
441   int http_response_code_ = 0;
442 
443   // CPU limiter during the update.
444   CPULimiter cpu_limiter_;
445 
446   // For status:
447   UpdateStatus status_{UpdateStatus::IDLE};
448   double download_progress_ = 0.0;
449   int64_t last_checked_time_ = 0;
450   std::string prev_version_;
451   std::string new_version_ = "0.0.0.0";
452   int64_t new_payload_size_ = 0;
453 
454   // Common parameters for all Omaha requests.
455   OmahaRequestParams* omaha_request_params_ = nullptr;
456 
457   // Number of consecutive manual update checks we've had where we obeyed
458   // Chrome's proxy settings.
459   int proxy_manual_checks_ = 0;
460 
461   // If true, this update cycle we are obeying proxies
462   bool obeying_proxies_ = true;
463 
464   // Our two proxy resolvers
465   DirectProxyResolver direct_proxy_resolver_;
466 #if USE_LIBCROS
467   ChromeBrowserProxyResolver chrome_proxy_resolver_;
468 #endif  // USE_LIBCROS
469 
470   // Originally, both of these flags are false. Once UpdateBootFlags is called,
471   // |update_boot_flags_running_| is set to true. As soon as UpdateBootFlags
472   // completes its asynchronous run, |update_boot_flags_running_| is reset to
473   // false and |updated_boot_flags_| is set to true. From that point on there
474   // will be no more changes to these flags.
475   //
476   // True if UpdateBootFlags has completed.
477   bool updated_boot_flags_ = false;
478   // True if UpdateBootFlags is running.
479   bool update_boot_flags_running_ = false;
480 
481   // True if the action processor needs to be started by the boot flag updater.
482   bool start_action_processor_ = false;
483 
484   // Used for fetching information about the device policy.
485   std::unique_ptr<policy::PolicyProvider> policy_provider_;
486 
487   // The current scatter factor as found in the policy setting.
488   base::TimeDelta scatter_factor_;
489 
490   // The number of consecutive failed update checks. Needed for calculating the
491   // next update check interval.
492   unsigned int consecutive_failed_update_checks_ = 0;
493 
494   // The poll interval (in seconds) that was dictated by Omaha, if any; zero
495   // otherwise. This is needed for calculating the update check interval.
496   unsigned int server_dictated_poll_interval_ = 0;
497 
498   // Tracks whether we have scheduled update checks.
499   bool waiting_for_scheduled_check_ = false;
500 
501   // A callback to use when a forced update request is either received (true) or
502   // cleared by an update attempt (false). The second argument indicates whether
503   // this is an interactive update, and its value is significant iff the first
504   // argument is true.
505   std::unique_ptr<base::Callback<void(bool, bool)>>
506       forced_update_pending_callback_;
507 
508   // The |app_version| and |omaha_url| parameters received during the latest
509   // forced update request. They are retrieved for use once the update is
510   // actually scheduled.
511   std::string forced_app_version_;
512   std::string forced_omaha_url_;
513 
514   org::chromium::debugdProxyInterface* debugd_proxy_;
515 
516   DISALLOW_COPY_AND_ASSIGN(UpdateAttempter);
517 };
518 
519 }  // namespace chromeos_update_engine
520 
521 #endif  // UPDATE_ENGINE_UPDATE_ATTEMPTER_H_
522