1 //
2 // Copyright (C) 2016 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 <sysexits.h>
18 #include <unistd.h>
19
20 #include <string>
21 #include <vector>
22
23 #include <base/bind.h>
24 #include <base/callback.h>
25 #include <base/command_line.h>
26 #include <base/logging.h>
27 #include <base/strings/string_split.h>
28 #include <binder/IServiceManager.h>
29 #include <binderwrapper/binder_wrapper.h>
30 #include <brillo/binder_watcher.h>
31 #include <brillo/daemons/daemon.h>
32 #include <brillo/flag_helper.h>
33 #include <brillo/message_loops/message_loop.h>
34 #include <brillo/syslog_logging.h>
35 #include <utils/String16.h>
36 #include <utils/StrongPointer.h>
37
38 #include "android/os/BnUpdateEngineCallback.h"
39 #include "android/os/IUpdateEngine.h"
40 #include "update_engine/client_library/include/update_engine/update_status.h"
41 #include "update_engine/common/error_code.h"
42 #include "update_engine/common/error_code_utils.h"
43 #include "update_engine/update_status_utils.h"
44 #include "utils/String8.h"
45
46 using android::binder::Status;
47
48 namespace chromeos_update_engine {
49 namespace internal {
50
51 class UpdateEngineClientAndroid : public brillo::Daemon {
52 public:
UpdateEngineClientAndroid(int argc,char ** argv)53 UpdateEngineClientAndroid(int argc, char** argv) : argc_(argc), argv_(argv) {}
54
55 int ExitWhenIdle(const Status& status);
56 int ExitWhenIdle(int return_code);
57
58 private:
59 class UECallback : public android::os::BnUpdateEngineCallback {
60 public:
UECallback(UpdateEngineClientAndroid * client)61 explicit UECallback(UpdateEngineClientAndroid* client) : client_(client) {}
62
63 // android::os::BnUpdateEngineCallback overrides.
64 Status onStatusUpdate(int status_code, float progress) override;
65 Status onPayloadApplicationComplete(int error_code) override;
66
67 private:
68 UpdateEngineClientAndroid* client_;
69 };
70
71 int OnInit() override;
72
73 // Called whenever the UpdateEngine daemon dies.
74 void UpdateEngineServiceDied();
75 // Register callback to watch for death notification from update_engine.
76 void RegisterDeathNotification();
77
78 static std::vector<android::String16> ParseHeaders(const std::string& arg);
79
80 // Copy of argc and argv passed to main().
81 int argc_;
82 char** argv_;
83
84 android::sp<android::os::IUpdateEngine> service_;
85 android::sp<android::os::BnUpdateEngineCallback> callback_;
86 android::sp<android::os::BnUpdateEngineCallback> cleanup_callback_;
87
88 brillo::BinderWatcher binder_watcher_;
89 };
90
onStatusUpdate(int status_code,float progress)91 Status UpdateEngineClientAndroid::UECallback::onStatusUpdate(int status_code,
92 float progress) {
93 update_engine::UpdateStatus status =
94 static_cast<update_engine::UpdateStatus>(status_code);
95 LOG(INFO) << "onStatusUpdate(" << UpdateStatusToString(status) << " ("
96 << status_code << "), " << progress << ")";
97 return Status::ok();
98 }
99
onPayloadApplicationComplete(int error_code)100 Status UpdateEngineClientAndroid::UECallback::onPayloadApplicationComplete(
101 int error_code) {
102 ErrorCode code = static_cast<ErrorCode>(error_code);
103 LOG(INFO) << "onPayloadApplicationComplete(" << utils::ErrorCodeToString(code)
104 << " (" << error_code << "))";
105 client_->ExitWhenIdle(
106 (code == ErrorCode::kSuccess || code == ErrorCode::kUpdatedButNotActive)
107 ? EX_OK
108 : 1);
109 return Status::ok();
110 }
111
112 constexpr auto&& UNSPECIFIED_FLAG = "unspecified";
113
RegisterDeathNotification()114 void UpdateEngineClientAndroid::RegisterDeathNotification() {
115 // When following updates status changes, exit if the update_engine daemon
116 // dies.
117 android::BinderWrapper::Create();
118 android::BinderWrapper::Get()->RegisterForDeathNotifications(
119 android::os::IUpdateEngine::asBinder(service_),
120 base::Bind(&UpdateEngineClientAndroid::UpdateEngineServiceDied,
121 base::Unretained(this)));
122 }
123
OnInit()124 int UpdateEngineClientAndroid::OnInit() {
125 int ret = Daemon::OnInit();
126 if (ret != EX_OK)
127 return ret;
128
129 DEFINE_bool(update, false, "Start a new update, if no update in progress.");
130 DEFINE_string(payload,
131 "http://127.0.0.1:8080/payload",
132 "The URI to the update payload to use.");
133 DEFINE_int64(offset,
134 0,
135 "The offset in the payload where the CrAU update starts. "
136 "Used when --update is passed.");
137 DEFINE_int64(size,
138 0,
139 "The size of the CrAU part of the payload. If 0 is passed, it "
140 "will be autodetected. Used when --update is passed.");
141 DEFINE_string(headers,
142 "",
143 "A list of key-value pairs, one element of the list per line. "
144 "Used when --update or --allocate is passed.");
145
146 DEFINE_bool(verify,
147 false,
148 "Given payload metadata, verify if the payload is applicable.");
149 DEFINE_bool(allocate, false, "Given payload metadata, allocate space.");
150 DEFINE_string(metadata,
151 "/data/ota_package/metadata",
152 "The path to the update payload metadata. "
153 "Used when --verify or --allocate is passed.");
154
155 DEFINE_string(switch_slot,
156 UNSPECIFIED_FLAG,
157 "Perform just the slow switching part of OTA. "
158 "Used to revert a slot switch or re-do slot switch. Valid "
159 "values are 'true' and 'false'");
160 DEFINE_bool(suspend, false, "Suspend an ongoing update and exit.");
161 DEFINE_bool(resume, false, "Resume a suspended update.");
162 DEFINE_bool(cancel, false, "Cancel the ongoing update and exit.");
163 DEFINE_bool(reset_status, false, "Reset an already applied update and exit.");
164 DEFINE_bool(follow,
165 false,
166 "Follow status update changes until a final state is reached. "
167 "Exit status is 0 if the update succeeded, and 1 otherwise.");
168 DEFINE_bool(merge,
169 false,
170 "Wait for previous update to merge. "
171 "Only available after rebooting to new slot.");
172 // Boilerplate init commands.
173 base::CommandLine::Init(argc_, argv_);
174 brillo::FlagHelper::Init(argc_, argv_, "Android Update Engine Client");
175 if (argc_ == 1) {
176 LOG(ERROR) << "Nothing to do. Run with --help for help.";
177 return 1;
178 }
179
180 // Ensure there are no positional arguments.
181 const std::vector<std::string> positional_args =
182 base::CommandLine::ForCurrentProcess()->GetArgs();
183 if (!positional_args.empty()) {
184 LOG(ERROR) << "Found a positional argument '" << positional_args.front()
185 << "'. If you want to pass a value to a flag, pass it as "
186 "--flag=value.";
187 return 1;
188 }
189
190 bool keep_running = false;
191 brillo::InitLog(brillo::kLogToStderr);
192
193 // Initialize a binder watcher early in the process before any interaction
194 // with the binder driver.
195 binder_watcher_.Init();
196
197 android::status_t status = android::getService(
198 android::String16("android.os.UpdateEngineService"), &service_);
199 if (status != android::OK) {
200 LOG(ERROR) << "Failed to get IUpdateEngine binder from service manager: "
201 << Status::fromStatusT(status).toString8();
202 return ExitWhenIdle(1);
203 }
204
205 // Other commands, such as |setShouldSwitchSlotOnReboot|, might rely on the
206 // follow behavior, so created callback before running these commands.
207 if (FLAGS_follow) {
208 // Register a callback object with the service.
209 callback_ = new UECallback(this);
210 bool bound;
211 if (!service_->bind(callback_, &bound).isOk() || !bound) {
212 LOG(ERROR) << "Failed to bind() the UpdateEngine daemon.";
213 return 1;
214 }
215 keep_running = true;
216 }
217
218 if (FLAGS_suspend) {
219 return ExitWhenIdle(service_->suspend());
220 }
221
222 if (FLAGS_resume) {
223 return ExitWhenIdle(service_->resume());
224 }
225
226 if (FLAGS_cancel) {
227 return ExitWhenIdle(service_->cancel());
228 }
229
230 if (FLAGS_reset_status) {
231 return ExitWhenIdle(service_->resetStatus());
232 }
233
234 if (FLAGS_switch_slot != UNSPECIFIED_FLAG) {
235 if (FLAGS_switch_slot != "true" && FLAGS_switch_slot != "false") {
236 LOG(ERROR) << "--switch_slot should be either true or false, got "
237 << FLAGS_switch_slot;
238 return 1;
239 }
240 const bool should_switch = FLAGS_switch_slot == "true";
241 ::android::binder::Status status;
242 if (should_switch) {
243 status = service_->setShouldSwitchSlotOnReboot(
244 android::String16(FLAGS_metadata.c_str(), FLAGS_metadata.size()));
245 if (!FLAGS_follow) {
246 return ExitWhenIdle(status);
247 }
248 } else {
249 // resetShouldSwitchSlotOnReboot() is a synchronous call, no need to
250 // follow
251 status = service_->resetShouldSwitchSlotOnReboot();
252 return ExitWhenIdle(status);
253 }
254 }
255
256 if (FLAGS_verify) {
257 bool applicable = false;
258 Status status = service_->verifyPayloadApplicable(
259 android::String16{FLAGS_metadata.data(), FLAGS_metadata.size()},
260 &applicable);
261 LOG(INFO) << "Payload is " << (applicable ? "" : "not ") << "applicable.";
262 return ExitWhenIdle(status);
263 }
264
265 if (FLAGS_allocate) {
266 auto headers = ParseHeaders(FLAGS_headers);
267 int64_t ret = 0;
268 Status status = service_->allocateSpaceForPayload(
269 android::String16{FLAGS_metadata.data(), FLAGS_metadata.size()},
270 headers,
271 &ret);
272 if (status.isOk()) {
273 if (ret == 0) {
274 LOG(INFO) << "Successfully allocated space for payload.";
275 } else {
276 LOG(INFO) << "Insufficient space; required " << ret << " bytes.";
277 }
278 } else {
279 LOG(INFO) << "Allocation failed.";
280 }
281 return ExitWhenIdle(status);
282 }
283
284 if (FLAGS_merge) {
285 // Register a callback object with the service.
286 cleanup_callback_ = new UECallback(this);
287 Status status = service_->cleanupSuccessfulUpdate(cleanup_callback_);
288 if (!status.isOk()) {
289 LOG(ERROR) << "Failed to call cleanupSuccessfulUpdate.";
290 return ExitWhenIdle(status);
291 }
292 keep_running = true;
293 }
294
295 if (FLAGS_update) {
296 auto and_headers = ParseHeaders(FLAGS_headers);
297 Status status = service_->applyPayload(
298 android::String16{FLAGS_payload.data(), FLAGS_payload.size()},
299 FLAGS_offset,
300 FLAGS_size,
301 and_headers);
302 if (!status.isOk())
303 return ExitWhenIdle(status);
304 }
305
306 if (!keep_running)
307 return ExitWhenIdle(EX_OK);
308
309 RegisterDeathNotification();
310 return EX_OK;
311 }
312
ExitWhenIdle(const Status & status)313 int UpdateEngineClientAndroid::ExitWhenIdle(const Status& status) {
314 if (status.isOk())
315 return ExitWhenIdle(EX_OK);
316 LOG(ERROR) << status.toString8();
317 return ExitWhenIdle(status.exceptionCode());
318 }
319
ExitWhenIdle(int return_code)320 int UpdateEngineClientAndroid::ExitWhenIdle(int return_code) {
321 auto delayed_exit = base::Bind(
322 &Daemon::QuitWithExitCode, base::Unretained(this), return_code);
323 if (!brillo::MessageLoop::current()->PostTask(delayed_exit))
324 return 1;
325 return EX_OK;
326 }
327
UpdateEngineServiceDied()328 void UpdateEngineClientAndroid::UpdateEngineServiceDied() {
329 LOG(ERROR) << "UpdateEngineService died.";
330 QuitWithExitCode(1);
331 }
332
ParseHeaders(const std::string & arg)333 std::vector<android::String16> UpdateEngineClientAndroid::ParseHeaders(
334 const std::string& arg) {
335 std::vector<std::string> headers = base::SplitString(
336 arg, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
337 std::vector<android::String16> and_headers;
338 for (const auto& header : headers) {
339 and_headers.push_back(android::String16{header.data(), header.size()});
340 }
341 return and_headers;
342 }
343
344 } // namespace internal
345 } // namespace chromeos_update_engine
346
main(int argc,char ** argv)347 int main(int argc, char** argv) {
348 chromeos_update_engine::internal::UpdateEngineClientAndroid client(argc,
349 argv);
350 return client.Run();
351 }
352