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/cros/common_service.h"
18 
19 #include <string>
20 
21 #include <base/bind.h>
22 #include <base/location.h>
23 #include <base/logging.h>
24 #include <base/strings/stringprintf.h>
25 #include <brillo/message_loops/message_loop.h>
26 #include <brillo/strings/string_utils.h>
27 #include <policy/device_policy.h>
28 
29 #include "update_engine/common/hardware_interface.h"
30 #include "update_engine/common/prefs.h"
31 #include "update_engine/common/system_state.h"
32 #include "update_engine/common/utils.h"
33 #include "update_engine/cros/connection_manager_interface.h"
34 #include "update_engine/cros/omaha_request_params.h"
35 #include "update_engine/cros/omaha_utils.h"
36 #include "update_engine/cros/p2p_manager.h"
37 #include "update_engine/cros/payload_state_interface.h"
38 #include "update_engine/cros/update_attempter.h"
39 
40 using base::StringPrintf;
41 using brillo::ErrorPtr;
42 using brillo::string_utils::ToString;
43 using std::string;
44 using std::vector;
45 using update_engine::UpdateAttemptFlags;
46 using update_engine::UpdateEngineStatus;
47 
48 namespace chromeos_update_engine {
49 
50 namespace {
51 // Log and set the error on the passed ErrorPtr.
LogAndSetError(ErrorPtr * error,const base::Location & location,const string & reason)52 void LogAndSetError(ErrorPtr* error,
53                     const base::Location& location,
54                     const string& reason) {
55   brillo::Error::AddTo(error,
56                        location,
57                        UpdateEngineService::kErrorDomain,
58                        UpdateEngineService::kErrorFailed,
59                        reason);
60   LOG(ERROR) << "Sending Update Engine Failure: " << location.ToString() << ": "
61              << reason;
62 }
63 }  // namespace
64 
65 const char* const UpdateEngineService::kErrorDomain = "update_engine";
66 const char* const UpdateEngineService::kErrorFailed =
67     "org.chromium.UpdateEngine.Error.Failed";
68 
69 UpdateEngineService::UpdateEngineService() = default;
70 
71 // org::chromium::UpdateEngineInterfaceInterface methods implementation.
72 
SetUpdateAttemptFlags(ErrorPtr *,int32_t in_flags_as_int)73 bool UpdateEngineService::SetUpdateAttemptFlags(ErrorPtr* /* error */,
74                                                 int32_t in_flags_as_int) {
75   auto flags = static_cast<UpdateAttemptFlags>(in_flags_as_int);
76   LOG(INFO) << "Setting Update Attempt Flags: "
77             << "flags=0x" << std::hex << flags << " "
78             << "RestrictDownload="
79             << ((flags & UpdateAttemptFlags::kFlagRestrictDownload) ? "yes"
80                                                                     : "no");
81   SystemState::Get()->update_attempter()->SetUpdateAttemptFlags(flags);
82   return true;
83 }
84 
AttemptUpdate(ErrorPtr *,const string & in_app_version,const string & in_omaha_url,int32_t in_flags_as_int,bool * out_result)85 bool UpdateEngineService::AttemptUpdate(ErrorPtr* /* error */,
86                                         const string& in_app_version,
87                                         const string& in_omaha_url,
88                                         int32_t in_flags_as_int,
89                                         bool* out_result) {
90   auto flags = static_cast<UpdateAttemptFlags>(in_flags_as_int);
91   bool interactive = !(flags & UpdateAttemptFlags::kFlagNonInteractive);
92   bool restrict_downloads = (flags & UpdateAttemptFlags::kFlagRestrictDownload);
93 
94   LOG(INFO) << "Attempt update: app_version=\"" << in_app_version << "\" "
95             << "omaha_url=\"" << in_omaha_url << "\" "
96             << "flags=0x" << std::hex << flags << " "
97             << "interactive=" << (interactive ? "yes " : "no ")
98             << "RestrictDownload=" << (restrict_downloads ? "yes " : "no ");
99 
100   *out_result = SystemState::Get()->update_attempter()->CheckForUpdate(
101       in_app_version, in_omaha_url, flags);
102   return true;
103 }
104 
AttemptInstall(brillo::ErrorPtr * error,const string & omaha_url,const vector<string> & dlc_ids)105 bool UpdateEngineService::AttemptInstall(brillo::ErrorPtr* error,
106                                          const string& omaha_url,
107                                          const vector<string>& dlc_ids) {
108   if (!SystemState::Get()->update_attempter()->CheckForInstall(dlc_ids,
109                                                                omaha_url)) {
110     // TODO(xiaochu): support more detailed error messages.
111     LogAndSetError(error, FROM_HERE, "Could not schedule install operation.");
112     return false;
113   }
114   return true;
115 }
116 
AttemptRollback(ErrorPtr * error,bool in_powerwash)117 bool UpdateEngineService::AttemptRollback(ErrorPtr* error, bool in_powerwash) {
118   LOG(INFO) << "Attempting rollback to non-active partitions.";
119 
120   if (!SystemState::Get()->update_attempter()->Rollback(in_powerwash)) {
121     // TODO(dgarrett): Give a more specific error code/reason.
122     LogAndSetError(error, FROM_HERE, "Rollback attempt failed.");
123     return false;
124   }
125   return true;
126 }
127 
CanRollback(ErrorPtr *,bool * out_can_rollback)128 bool UpdateEngineService::CanRollback(ErrorPtr* /* error */,
129                                       bool* out_can_rollback) {
130   bool can_rollback = SystemState::Get()->update_attempter()->CanRollback();
131   LOG(INFO) << "Checking to see if we can rollback . Result: " << can_rollback;
132   *out_can_rollback = can_rollback;
133   return true;
134 }
135 
ResetStatus(ErrorPtr * error)136 bool UpdateEngineService::ResetStatus(ErrorPtr* error) {
137   if (!SystemState::Get()->update_attempter()->ResetStatus()) {
138     // TODO(dgarrett): Give a more specific error code/reason.
139     LogAndSetError(error, FROM_HERE, "ResetStatus failed.");
140     return false;
141   }
142   return true;
143 }
144 
SetDlcActiveValue(brillo::ErrorPtr * error,bool is_active,const string & dlc_id)145 bool UpdateEngineService::SetDlcActiveValue(brillo::ErrorPtr* error,
146                                             bool is_active,
147                                             const string& dlc_id) {
148   if (!SystemState::Get()->update_attempter()->SetDlcActiveValue(is_active,
149                                                                  dlc_id)) {
150     LogAndSetError(error, FROM_HERE, "SetDlcActiveValue failed.");
151     return false;
152   }
153   return true;
154 }
155 
GetStatus(ErrorPtr * error,UpdateEngineStatus * out_status)156 bool UpdateEngineService::GetStatus(ErrorPtr* error,
157                                     UpdateEngineStatus* out_status) {
158   if (!SystemState::Get()->update_attempter()->GetStatus(out_status)) {
159     LogAndSetError(error, FROM_HERE, "GetStatus failed.");
160     return false;
161   }
162   return true;
163 }
164 
RebootIfNeeded(ErrorPtr * error)165 bool UpdateEngineService::RebootIfNeeded(ErrorPtr* error) {
166   if (!SystemState::Get()->update_attempter()->RebootIfNeeded()) {
167     // TODO(dgarrett): Give a more specific error code/reason.
168     LogAndSetError(error, FROM_HERE, "Reboot not needed, or attempt failed.");
169     return false;
170   }
171   return true;
172 }
173 
SetChannel(ErrorPtr * error,const string & in_target_channel,bool in_is_powerwash_allowed)174 bool UpdateEngineService::SetChannel(ErrorPtr* error,
175                                      const string& in_target_channel,
176                                      bool in_is_powerwash_allowed) {
177   const policy::DevicePolicy* device_policy =
178       SystemState::Get()->device_policy();
179 
180   // The device_policy is loaded in a lazy way before an update check. Load it
181   // now from the libbrillo cache if it wasn't already loaded.
182   if (!device_policy) {
183     UpdateAttempter* update_attempter = SystemState::Get()->update_attempter();
184     if (update_attempter) {
185       update_attempter->RefreshDevicePolicy();
186       device_policy = SystemState::Get()->device_policy();
187     }
188   }
189 
190   bool delegated = false;
191   if (device_policy && device_policy->GetReleaseChannelDelegated(&delegated) &&
192       !delegated) {
193     LogAndSetError(error,
194                    FROM_HERE,
195                    "Cannot set target channel explicitly when channel "
196                    "policy/settings is not delegated");
197     return false;
198   }
199 
200   LOG(INFO) << "Setting destination channel to: " << in_target_channel;
201   string error_message;
202   if (!SystemState::Get()->request_params()->SetTargetChannel(
203           in_target_channel, in_is_powerwash_allowed, &error_message)) {
204     LogAndSetError(error, FROM_HERE, error_message);
205     return false;
206   }
207   return true;
208 }
209 
GetChannel(ErrorPtr *,bool in_get_current_channel,string * out_channel)210 bool UpdateEngineService::GetChannel(ErrorPtr* /* error */,
211                                      bool in_get_current_channel,
212                                      string* out_channel) {
213   OmahaRequestParams* rp = SystemState::Get()->request_params();
214   *out_channel =
215       (in_get_current_channel ? rp->current_channel() : rp->target_channel());
216   return true;
217 }
218 
SetCohortHint(ErrorPtr * error,const string & in_cohort_hint)219 bool UpdateEngineService::SetCohortHint(ErrorPtr* error,
220                                         const string& in_cohort_hint) {
221   // It is ok to override the cohort hint with an invalid value since it is
222   // stored in stateful partition. The code reading it should sanitize it
223   // anyway.
224   if (!SystemState::Get()->prefs()->SetString(kPrefsOmahaCohortHint,
225                                               in_cohort_hint)) {
226     LogAndSetError(
227         error,
228         FROM_HERE,
229         StringPrintf("Error setting the cohort hint value to \"%s\".",
230                      in_cohort_hint.c_str()));
231     return false;
232   }
233   return true;
234 }
235 
GetCohortHint(ErrorPtr * error,string * out_cohort_hint)236 bool UpdateEngineService::GetCohortHint(ErrorPtr* error,
237                                         string* out_cohort_hint) {
238   const auto* prefs = SystemState::Get()->prefs();
239   *out_cohort_hint = "";
240   if (prefs->Exists(kPrefsOmahaCohortHint) &&
241       !prefs->GetString(kPrefsOmahaCohortHint, out_cohort_hint)) {
242     LogAndSetError(error, FROM_HERE, "Error getting the cohort hint.");
243     return false;
244   }
245   return true;
246 }
247 
SetP2PUpdatePermission(ErrorPtr * error,bool in_enabled)248 bool UpdateEngineService::SetP2PUpdatePermission(ErrorPtr* error,
249                                                  bool in_enabled) {
250   if (!SystemState::Get()->prefs()->SetBoolean(kPrefsP2PEnabled, in_enabled)) {
251     LogAndSetError(
252         error,
253         FROM_HERE,
254         StringPrintf("Error setting the update via p2p permission to %s.",
255                      ToString(in_enabled).c_str()));
256     return false;
257   }
258   return true;
259 }
260 
GetP2PUpdatePermission(ErrorPtr * error,bool * out_enabled)261 bool UpdateEngineService::GetP2PUpdatePermission(ErrorPtr* error,
262                                                  bool* out_enabled) {
263   const auto* prefs = SystemState::Get()->prefs();
264   bool p2p_pref = false;  // Default if no setting is present.
265   if (prefs->Exists(kPrefsP2PEnabled) &&
266       !prefs->GetBoolean(kPrefsP2PEnabled, &p2p_pref)) {
267     LogAndSetError(error, FROM_HERE, "Error getting the P2PEnabled setting.");
268     return false;
269   }
270 
271   *out_enabled = p2p_pref;
272   return true;
273 }
274 
SetUpdateOverCellularPermission(ErrorPtr * error,bool in_allowed)275 bool UpdateEngineService::SetUpdateOverCellularPermission(ErrorPtr* error,
276                                                           bool in_allowed) {
277   ConnectionManagerInterface* connection_manager =
278       SystemState::Get()->connection_manager();
279 
280   // Check if this setting is allowed by the device policy.
281   if (connection_manager->IsAllowedConnectionTypesForUpdateSet()) {
282     LogAndSetError(error,
283                    FROM_HERE,
284                    "Ignoring the update over cellular setting since there's "
285                    "a device policy enforcing this setting.");
286     return false;
287   }
288 
289   // If the policy wasn't loaded yet, then it is still OK to change the local
290   // setting because the policy will be checked again during the update check.
291   if (!SystemState::Get()->prefs()->SetBoolean(
292           kPrefsUpdateOverCellularPermission, in_allowed)) {
293     LogAndSetError(error,
294                    FROM_HERE,
295                    string("Error setting the update over cellular to ") +
296                        (in_allowed ? "true" : "false"));
297     return false;
298   }
299   return true;
300 }
301 
SetUpdateOverCellularTarget(brillo::ErrorPtr * error,const std::string & target_version,int64_t target_size)302 bool UpdateEngineService::SetUpdateOverCellularTarget(
303     brillo::ErrorPtr* error,
304     const std::string& target_version,
305     int64_t target_size) {
306   ConnectionManagerInterface* connection_manager =
307       SystemState::Get()->connection_manager();
308 
309   // Check if this setting is allowed by the device policy.
310   if (connection_manager->IsAllowedConnectionTypesForUpdateSet()) {
311     LogAndSetError(error,
312                    FROM_HERE,
313                    "Ignoring the update over cellular setting since there's "
314                    "a device policy enforcing this setting.");
315     return false;
316   }
317 
318   // If the policy wasn't loaded yet, then it is still OK to change the local
319   // setting because the policy will be checked again during the update check.
320 
321   auto* prefs = SystemState::Get()->prefs();
322   if (!prefs->SetString(kPrefsUpdateOverCellularTargetVersion,
323                         target_version) ||
324       !prefs->SetInt64(kPrefsUpdateOverCellularTargetSize, target_size)) {
325     LogAndSetError(
326         error, FROM_HERE, "Error setting the target for update over cellular.");
327     return false;
328   }
329   return true;
330 }
331 
GetUpdateOverCellularPermission(ErrorPtr * error,bool * out_allowed)332 bool UpdateEngineService::GetUpdateOverCellularPermission(ErrorPtr* error,
333                                                           bool* out_allowed) {
334   ConnectionManagerInterface* connection_manager =
335       SystemState::Get()->connection_manager();
336 
337   if (connection_manager->IsAllowedConnectionTypesForUpdateSet()) {
338     // We have device policy, so ignore the user preferences.
339     *out_allowed = connection_manager->IsUpdateAllowedOver(
340         ConnectionType::kCellular, ConnectionTethering::kUnknown);
341   } else {
342     const auto* prefs = SystemState::Get()->prefs();
343     if (!prefs->Exists(kPrefsUpdateOverCellularPermission)) {
344       // Update is not allowed as user preference is not set or not available.
345       *out_allowed = false;
346       return true;
347     }
348 
349     bool is_allowed;
350 
351     if (!prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed)) {
352       LogAndSetError(error,
353                      FROM_HERE,
354                      "Error getting the update over cellular preference.");
355       return false;
356     }
357     *out_allowed = is_allowed;
358   }
359   return true;
360 }
361 
GetDurationSinceUpdate(ErrorPtr * error,int64_t * out_usec_wallclock)362 bool UpdateEngineService::GetDurationSinceUpdate(ErrorPtr* error,
363                                                  int64_t* out_usec_wallclock) {
364   base::Time time;
365   if (!SystemState::Get()->update_attempter()->GetBootTimeAtUpdate(&time)) {
366     LogAndSetError(error, FROM_HERE, "No pending update.");
367     return false;
368   }
369 
370   const auto* clock = SystemState::Get()->clock();
371   *out_usec_wallclock = (clock->GetBootTime() - time).InMicroseconds();
372   return true;
373 }
374 
GetPrevVersion(ErrorPtr *,string * out_prev_version)375 bool UpdateEngineService::GetPrevVersion(ErrorPtr* /* error */,
376                                          string* out_prev_version) {
377   *out_prev_version = SystemState::Get()->update_attempter()->GetPrevVersion();
378   return true;
379 }
380 
GetRollbackPartition(ErrorPtr *,string * out_rollback_partition_name)381 bool UpdateEngineService::GetRollbackPartition(
382     ErrorPtr* /* error */, string* out_rollback_partition_name) {
383   BootControlInterface::Slot rollback_slot =
384       SystemState::Get()->update_attempter()->GetRollbackSlot();
385 
386   if (rollback_slot == BootControlInterface::kInvalidSlot) {
387     out_rollback_partition_name->clear();
388     return true;
389   }
390 
391   string name;
392   if (!SystemState::Get()->boot_control()->GetPartitionDevice(
393           "KERNEL", rollback_slot, &name)) {
394     LOG(ERROR) << "Invalid rollback device";
395     return false;
396   }
397 
398   LOG(INFO) << "Getting rollback partition name. Result: " << name;
399   *out_rollback_partition_name = name;
400   return true;
401 }
402 
GetLastAttemptError(ErrorPtr *,int32_t * out_last_attempt_error)403 bool UpdateEngineService::GetLastAttemptError(ErrorPtr* /* error */,
404                                               int32_t* out_last_attempt_error) {
405   ErrorCode error_code =
406       SystemState::Get()->update_attempter()->GetAttemptErrorCode();
407   *out_last_attempt_error = static_cast<int>(error_code);
408   return true;
409 }
410 
411 }  // namespace chromeos_update_engine
412