blob: ad4be382e1fffc64546cd176cf87c8dedeb2e86f [file] [log] [blame]
Doug Zongker9270a202012-01-09 15:16:13 -08001/*
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
xunchang24788852019-03-22 16:08:52 -070017#include "install/adb_install.h"
Tao Bao0150d012017-05-01 11:31:28 -070018
Doug Zongker9270a202012-01-09 15:16:13 -080019#include <errno.h>
Tao Bao0150d012017-05-01 11:31:28 -070020#include <fcntl.h>
21#include <signal.h>
Doug Zongker9270a202012-01-09 15:16:13 -080022#include <stdlib.h>
23#include <string.h>
xunchang95d67322019-04-05 16:16:07 -070024#include <sys/epoll.h>
25#include <sys/socket.h>
Tao Bao0150d012017-05-01 11:31:28 -070026#include <sys/stat.h>
Doug Zongker9270a202012-01-09 15:16:13 -080027#include <sys/types.h>
28#include <sys/wait.h>
Tao Bao0150d012017-05-01 11:31:28 -070029#include <unistd.h>
Doug Zongker9270a202012-01-09 15:16:13 -080030
xunchang95d67322019-04-05 16:16:07 -070031#include <atomic>
32#include <functional>
33#include <map>
Tao Bao7b9b7db2019-04-19 15:22:15 -070034#include <utility>
Tao Bao378bfbf2019-04-16 14:22:25 -070035#include <vector>
xunchang95d67322019-04-05 16:16:07 -070036
37#include <android-base/file.h>
Tao Bao0167d4c2017-05-11 14:44:15 -070038#include <android-base/logging.h>
xunchang95d67322019-04-05 16:16:07 -070039#include <android-base/memory.h>
Elliott Hughescb220402016-09-23 15:30:55 -070040#include <android-base/properties.h>
xunchang95d67322019-04-05 16:16:07 -070041#include <android-base/strings.h>
42#include <android-base/unique_fd.h>
Elliott Hughescb220402016-09-23 15:30:55 -070043
Tao Bao0150d012017-05-01 11:31:28 -070044#include "fuse_sideload.h"
xunchang24788852019-03-22 16:08:52 -070045#include "install/install.h"
xunchang5a1916b2019-04-22 12:18:14 -070046#include "install/wipe_data.h"
xunchang95d67322019-04-05 16:16:07 -070047#include "minadbd_types.h"
Tao Bao378bfbf2019-04-16 14:22:25 -070048#include "otautil/sysutil.h"
Tao Bao7b9b7db2019-04-19 15:22:15 -070049#include "recovery_ui/device.h"
Tianjie Xu8f397302018-08-20 13:40:47 -070050#include "recovery_ui/ui.h"
Tao Bao0150d012017-05-01 11:31:28 -070051
Tao Bao7b9b7db2019-04-19 15:22:15 -070052// A CommandFunction returns a pair of (result, should_continue), which indicates the command
53// execution result and whether it should proceed to the next iteration. The execution result will
54// always be sent to the minadbd side.
55using CommandFunction = std::function<std::pair<bool, bool>()>;
xunchang95d67322019-04-05 16:16:07 -070056
xunchang24788852019-03-22 16:08:52 -070057static bool SetUsbConfig(const std::string& state) {
58 android::base::SetProperty("sys.usb.config", state);
59 return android::base::WaitForProperty("sys.usb.state", state);
60}
61
Tao Bao7b9b7db2019-04-19 15:22:15 -070062// Parses the minadbd command in |message|; returns MinadbdCommand::kError upon errors.
63static MinadbdCommand ParseMinadbdCommand(const std::string& message) {
xunchang95d67322019-04-05 16:16:07 -070064 if (!android::base::StartsWith(message, kMinadbdCommandPrefix)) {
65 LOG(ERROR) << "Failed to parse command in message " << message;
Tao Bao7b9b7db2019-04-19 15:22:15 -070066 return MinadbdCommand::kError;
xunchang95d67322019-04-05 16:16:07 -070067 }
68
69 auto cmd_code_string = message.substr(strlen(kMinadbdCommandPrefix));
70 auto cmd_code = android::base::get_unaligned<uint32_t>(cmd_code_string.c_str());
Tao Bao7b9b7db2019-04-19 15:22:15 -070071 if (cmd_code >= static_cast<uint32_t>(MinadbdCommand::kError)) {
xunchang95d67322019-04-05 16:16:07 -070072 LOG(ERROR) << "Unsupported command code: " << cmd_code;
Tao Bao7b9b7db2019-04-19 15:22:15 -070073 return MinadbdCommand::kError;
xunchang95d67322019-04-05 16:16:07 -070074 }
75
Tao Bao7b9b7db2019-04-19 15:22:15 -070076 return static_cast<MinadbdCommand>(cmd_code);
xunchang95d67322019-04-05 16:16:07 -070077}
78
79static bool WriteStatusToFd(MinadbdCommandStatus status, int fd) {
80 char message[kMinadbdMessageSize];
81 memcpy(message, kMinadbdStatusPrefix, strlen(kMinadbdStatusPrefix));
82 android::base::put_unaligned(message + strlen(kMinadbdStatusPrefix), status);
83
84 if (!android::base::WriteFully(fd, message, kMinadbdMessageSize)) {
85 PLOG(ERROR) << "Failed to write message " << message;
86 return false;
87 }
88 return true;
89}
90
Tao Bao7b9b7db2019-04-19 15:22:15 -070091// Installs the package from FUSE. Returns the installation result and whether it should continue
92// waiting for new commands.
Tom Marshall03354052018-06-21 00:57:24 +020093static auto AdbInstallPackageHandler(
94 Device* device, int* result,
95 const std::function<bool(Device*)>& ask_to_continue_unverified_fn) {
96 RecoveryUI* ui = device->GetUI();
97
xunchang95d67322019-04-05 16:16:07 -070098 // How long (in seconds) we wait for the package path to be ready. It doesn't need to be too long
99 // because the minadbd service has already issued an install command. FUSE_SIDELOAD_HOST_PATHNAME
100 // will start to exist once the host connects and starts serving a package. Poll for its
101 // appearance. (Note that inotify doesn't work with FUSE.)
102 constexpr int ADB_INSTALL_TIMEOUT = 15;
Tao Bao7b9b7db2019-04-19 15:22:15 -0700103 bool should_continue = true;
xunchang95d67322019-04-05 16:16:07 -0700104 *result = INSTALL_ERROR;
105 for (int i = 0; i < ADB_INSTALL_TIMEOUT; ++i) {
106 struct stat st;
107 if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &st) != 0) {
108 if (errno == ENOENT && i < ADB_INSTALL_TIMEOUT - 1) {
109 sleep(1);
110 continue;
111 } else {
Tao Bao7b9b7db2019-04-19 15:22:15 -0700112 should_continue = false;
xunchang95d67322019-04-05 16:16:07 -0700113 ui->Print("\nTimed out waiting for fuse to be ready.\n\n");
114 break;
115 }
116 }
Tom Marshalla9ac9552018-12-17 15:57:44 -0800117 ui->CancelWaitKey();
Tom Marshall03354052018-06-21 00:57:24 +0200118
119 *result = install_package(FUSE_SIDELOAD_HOST_PATHNAME, false, false, 0, true /* verify */, ui);
120 if (*result == INSTALL_UNVERIFIED && ask_to_continue_unverified_fn &&
121 ask_to_continue_unverified_fn(device)) {
122 *result =
123 install_package(FUSE_SIDELOAD_HOST_PATHNAME, false, false, 0, false /* verify */, ui);
124 }
xunchang95d67322019-04-05 16:16:07 -0700125 break;
126 }
127
128 // Calling stat() on this magic filename signals the FUSE to exit.
129 struct stat st;
130 stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &st);
Tao Bao7b9b7db2019-04-19 15:22:15 -0700131 return std::make_pair(*result == INSTALL_SUCCESS, should_continue);
xunchang95d67322019-04-05 16:16:07 -0700132}
133
Tao Bao7b9b7db2019-04-19 15:22:15 -0700134static auto AdbRebootHandler(MinadbdCommand command, int* result,
135 Device::BuiltinAction* reboot_action) {
Tao Bao75321ad2019-04-23 11:46:25 -0700136 // Use Device::REBOOT_{FASTBOOT,RECOVERY,RESCUE}, instead of the ones with ENTER_. This allows
137 // rebooting back into fastboot/recovery/rescue mode through bootloader, which may use a newly
138 // installed bootloader/recovery image.
Tao Bao7b9b7db2019-04-19 15:22:15 -0700139 switch (command) {
140 case MinadbdCommand::kRebootBootloader:
141 *reboot_action = Device::REBOOT_BOOTLOADER;
142 break;
143 case MinadbdCommand::kRebootFastboot:
Tao Bao75321ad2019-04-23 11:46:25 -0700144 *reboot_action = Device::REBOOT_FASTBOOT;
Tao Bao7b9b7db2019-04-19 15:22:15 -0700145 break;
146 case MinadbdCommand::kRebootRecovery:
Tao Bao75321ad2019-04-23 11:46:25 -0700147 *reboot_action = Device::REBOOT_RECOVERY;
Tao Bao7b9b7db2019-04-19 15:22:15 -0700148 break;
149 case MinadbdCommand::kRebootRescue:
Tao Bao7b9b7db2019-04-19 15:22:15 -0700150 *reboot_action = Device::REBOOT_RESCUE;
151 break;
152 case MinadbdCommand::kRebootAndroid:
153 default:
154 *reboot_action = Device::REBOOT;
155 break;
156 }
157 *result = INSTALL_REBOOT;
158 return std::make_pair(true, false);
159}
160
161// Parses and executes the command from minadbd. Returns whether the caller should keep waiting for
162// next command.
163static bool HandleMessageFromMinadbd(int socket_fd,
164 const std::map<MinadbdCommand, CommandFunction>& command_map) {
xunchang95d67322019-04-05 16:16:07 -0700165 char buffer[kMinadbdMessageSize];
166 if (!android::base::ReadFully(socket_fd, buffer, kMinadbdMessageSize)) {
167 PLOG(ERROR) << "Failed to read message from minadbd";
168 return false;
169 }
170
171 std::string message(buffer, buffer + kMinadbdMessageSize);
Tao Bao7b9b7db2019-04-19 15:22:15 -0700172 auto command_type = ParseMinadbdCommand(message);
173 if (command_type == MinadbdCommand::kError) {
xunchang95d67322019-04-05 16:16:07 -0700174 return false;
175 }
176 if (command_map.find(command_type) == command_map.end()) {
177 LOG(ERROR) << "Unsupported command: "
178 << android::base::get_unaligned<unsigned int>(
179 message.substr(strlen(kMinadbdCommandPrefix)).c_str());
180 return false;
181 }
182
183 // We have received a valid command, execute the corresponding function.
184 const auto& command_func = command_map.at(command_type);
Tao Bao7b9b7db2019-04-19 15:22:15 -0700185 const auto [result, should_continue] = command_func();
186 LOG(INFO) << "Command " << static_cast<uint32_t>(command_type) << " finished with " << result;
187 if (!WriteStatusToFd(result ? MinadbdCommandStatus::kSuccess : MinadbdCommandStatus::kFailure,
188 socket_fd)) {
189 return false;
xunchang95d67322019-04-05 16:16:07 -0700190 }
Tao Bao7b9b7db2019-04-19 15:22:15 -0700191 return should_continue;
xunchang95d67322019-04-05 16:16:07 -0700192}
193
194// TODO(xunchang) add a wrapper function and kill the minadbd service there.
195static void ListenAndExecuteMinadbdCommands(
Tao Bao75321ad2019-04-23 11:46:25 -0700196 RecoveryUI* ui, pid_t minadbd_pid, android::base::unique_fd&& socket_fd,
Tao Bao7b9b7db2019-04-19 15:22:15 -0700197 const std::map<MinadbdCommand, CommandFunction>& command_map) {
xunchang95d67322019-04-05 16:16:07 -0700198 android::base::unique_fd epoll_fd(epoll_create1(O_CLOEXEC));
199 if (epoll_fd == -1) {
200 PLOG(ERROR) << "Failed to create epoll";
201 kill(minadbd_pid, SIGKILL);
202 return;
203 }
204
205 constexpr int EPOLL_MAX_EVENTS = 10;
206 struct epoll_event ev = {};
207 ev.events = EPOLLIN | EPOLLHUP;
208 ev.data.fd = socket_fd.get();
209 struct epoll_event events[EPOLL_MAX_EVENTS];
210 if (epoll_ctl(epoll_fd.get(), EPOLL_CTL_ADD, socket_fd.get(), &ev) == -1) {
211 PLOG(ERROR) << "Failed to add socket fd to epoll";
212 kill(minadbd_pid, SIGKILL);
213 return;
214 }
215
216 // Set the timeout to be 300s when waiting for minadbd commands.
217 constexpr int TIMEOUT_MILLIS = 300 * 1000;
218 while (true) {
Tao Bao75321ad2019-04-23 11:46:25 -0700219 // Reset the progress bar and the background image before each command.
220 ui->SetProgressType(RecoveryUI::EMPTY);
221 ui->SetBackground(RecoveryUI::NO_COMMAND);
222
xunchang95d67322019-04-05 16:16:07 -0700223 // Poll for the status change of the socket_fd, and handle the message if the fd is ready to
224 // read.
225 int event_count =
226 TEMP_FAILURE_RETRY(epoll_wait(epoll_fd.get(), events, EPOLL_MAX_EVENTS, TIMEOUT_MILLIS));
227 if (event_count == -1) {
228 PLOG(ERROR) << "Failed to wait for epoll events";
229 kill(minadbd_pid, SIGKILL);
230 return;
231 }
232 if (event_count == 0) {
233 LOG(ERROR) << "Timeout waiting for messages from minadbd";
234 kill(minadbd_pid, SIGKILL);
235 return;
236 }
237
238 for (int n = 0; n < event_count; n++) {
239 if (events[n].events & EPOLLHUP) {
240 LOG(INFO) << "Socket has been closed";
241 kill(minadbd_pid, SIGKILL);
242 return;
243 }
244 if (!HandleMessageFromMinadbd(socket_fd.get(), command_map)) {
245 kill(minadbd_pid, SIGKILL);
246 return;
247 }
248 }
249 }
250}
251
252// Recovery starts minadbd service as a child process, and spawns another thread to listen for the
253// message from minadbd through a socket pair. Here is an example to execute one command from adb
254// host.
255// a. recovery b. listener thread c. minadbd service
256//
257// a1. create socket pair
258// a2. fork minadbd service
259// c3. wait for the adb commands
260// from host
261// c4. after receiving host commands:
262// 1) set up pre-condition (i.e.
263// start fuse for adb sideload)
264// 2) issue command through
265// socket.
266// 3) wait for result
267// a5. start listener thread
268// b6. listen for message from
269// minadbd in a loop.
270// b7. After receiving a minadbd
271// command from socket
272// 1) execute the command function
273// 2) send the result back to
274// minadbd
275// ......
276// c8. exit upon receiving the
277// result
278// a9. wait for listener thread
279// to exit.
280//
281// a10. wait for minadbd to
282// exit
283// b11. exit the listening loop
284//
285static void CreateMinadbdServiceAndExecuteCommands(
Tom Marshalla9ac9552018-12-17 15:57:44 -0800286 Device* device, const std::map<MinadbdCommand, CommandFunction>& command_map,
Tao Bao75321ad2019-04-23 11:46:25 -0700287 bool rescue_mode) {
xunchang95d67322019-04-05 16:16:07 -0700288 signal(SIGPIPE, SIG_IGN);
289
290 android::base::unique_fd recovery_socket;
291 android::base::unique_fd minadbd_socket;
292 if (!android::base::Socketpair(AF_UNIX, SOCK_STREAM, 0, &recovery_socket, &minadbd_socket)) {
293 PLOG(ERROR) << "Failed to create socket";
294 return;
295 }
296
297 pid_t child = fork();
298 if (child == -1) {
299 PLOG(ERROR) << "Failed to fork child process";
300 return;
301 }
302 if (child == 0) {
303 recovery_socket.reset();
Tao Bao378bfbf2019-04-16 14:22:25 -0700304 std::vector<std::string> minadbd_commands = {
305 "/system/bin/minadbd",
306 "--socket_fd",
307 std::to_string(minadbd_socket.release()),
308 };
309 if (rescue_mode) {
310 minadbd_commands.push_back("--rescue");
311 }
312 auto exec_args = StringVectorToNullTerminatedArray(minadbd_commands);
313 execv(exec_args[0], exec_args.data());
xunchang95d67322019-04-05 16:16:07 -0700314 _exit(EXIT_FAILURE);
315 }
316
317 minadbd_socket.reset();
318
319 // We need to call SetUsbConfig() after forking minadbd service. Because the function waits for
320 // the usb state to be updated, which depends on sys.usb.ffs.ready=1 set in the adb daemon.
321 if (!SetUsbConfig("sideload")) {
322 LOG(ERROR) << "Failed to set usb config to sideload";
323 return;
324 }
325
Tom Marshalla9ac9552018-12-17 15:57:44 -0800326 RecoveryUI* ui = device->GetUI();
Tao Bao75321ad2019-04-23 11:46:25 -0700327 std::thread listener_thread(ListenAndExecuteMinadbdCommands, ui, child,
328 std::move(recovery_socket), std::ref(command_map));
Tom Marshalla9ac9552018-12-17 15:57:44 -0800329
330 if (ui->IsTextVisible()) {
331 std::vector<std::string> headers{ rescue_mode ? "Rescue mode" : "ADB Sideload" };
332 std::vector<std::string> entries{ "Cancel" };
333 size_t chosen_item = ui->ShowMenu(
334 headers, entries, 0, true,
335 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
336
337 if (chosen_item != Device::kRefresh) {
338 // Kill minadbd if 'cancel' was selected, to abort sideload.
339 kill(child, SIGKILL);
340 }
341 }
342
xunchang95d67322019-04-05 16:16:07 -0700343 if (listener_thread.joinable()) {
344 listener_thread.join();
345 }
346
347 int status;
348 waitpid(child, &status, 0);
349 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
350 if (WEXITSTATUS(status) == MinadbdErrorCode::kMinadbdAdbVersionError) {
351 LOG(ERROR) << "\nYou need adb 1.0.32 or newer to sideload\nto this device.\n";
352 } else if (!WIFSIGNALED(status)) {
353 LOG(ERROR) << "\n(adbd status " << WEXITSTATUS(status) << ")";
354 }
355 }
356
357 signal(SIGPIPE, SIG_DFL);
358}
359
Tom Marshall03354052018-06-21 00:57:24 +0200360int ApplyFromAdb(Device* device, bool rescue_mode, Device::BuiltinAction* reboot_action,
361 const std::function<bool(Device*)>& ask_to_continue_unverified_fn) {
Hridya Valsarajue4ef4532018-08-31 11:57:51 -0700362 // Save the usb state to restore after the sideload operation.
363 std::string usb_state = android::base::GetProperty("sys.usb.state", "none");
364 // Clean up state and stop adbd.
365 if (usb_state != "none" && !SetUsbConfig("none")) {
366 LOG(ERROR) << "Failed to clear USB config";
367 return INSTALL_ERROR;
368 }
Tao Bao682c34b2015-04-07 17:16:35 -0700369
xunchang95d67322019-04-05 16:16:07 -0700370 int install_result = INSTALL_ERROR;
Tao Bao7b9b7db2019-04-19 15:22:15 -0700371 std::map<MinadbdCommand, CommandFunction> command_map{
Tom Marshall03354052018-06-21 00:57:24 +0200372 { MinadbdCommand::kInstall, std::bind(&AdbInstallPackageHandler, device, &install_result,
373 ask_to_continue_unverified_fn) },
Tao Bao7b9b7db2019-04-19 15:22:15 -0700374 { MinadbdCommand::kRebootAndroid, std::bind(&AdbRebootHandler, MinadbdCommand::kRebootAndroid,
375 &install_result, reboot_action) },
376 { MinadbdCommand::kRebootBootloader,
377 std::bind(&AdbRebootHandler, MinadbdCommand::kRebootBootloader, &install_result,
378 reboot_action) },
379 { MinadbdCommand::kRebootFastboot, std::bind(&AdbRebootHandler, MinadbdCommand::kRebootFastboot,
380 &install_result, reboot_action) },
381 { MinadbdCommand::kRebootRecovery, std::bind(&AdbRebootHandler, MinadbdCommand::kRebootRecovery,
382 &install_result, reboot_action) },
383 { MinadbdCommand::kRebootRescue,
384 std::bind(&AdbRebootHandler, MinadbdCommand::kRebootRescue, &install_result, reboot_action) },
xunchang95d67322019-04-05 16:16:07 -0700385 };
Doug Zongker9270a202012-01-09 15:16:13 -0800386
Tom Marshall03354052018-06-21 00:57:24 +0200387 RecoveryUI* ui = device->GetUI();
388
xunchang5a1916b2019-04-22 12:18:14 -0700389 if (!rescue_mode) {
390 ui->Print(
391 "\n\nNow send the package you want to apply\n"
392 "to the device with \"adb sideload <filename>\"...\n");
393 } else {
xunchang5a1916b2019-04-22 12:18:14 -0700394 command_map.emplace(MinadbdCommand::kWipeData, [&device]() {
395 bool result = WipeData(device, false);
396 return std::make_pair(result, true);
397 });
Tao Bao0bbb2ed2019-07-08 18:07:22 -0700398 command_map.emplace(MinadbdCommand::kNoOp, []() { return std::make_pair(true, true); });
399
400 ui->Print("\n\nWaiting for rescue commands...\n");
xunchang5a1916b2019-04-22 12:18:14 -0700401 }
402
Tom Marshalla9ac9552018-12-17 15:57:44 -0800403 CreateMinadbdServiceAndExecuteCommands(device, command_map, rescue_mode);
Doug Zongker075ad802014-06-26 15:35:51 -0700404
Hridya Valsarajue4ef4532018-08-31 11:57:51 -0700405 // Clean up before switching to the older state, for example setting the state
406 // to none sets sys/class/android_usb/android0/enable to 0.
407 if (!SetUsbConfig("none")) {
408 LOG(ERROR) << "Failed to clear USB config";
409 }
410
411 if (usb_state != "none") {
412 if (!SetUsbConfig(usb_state)) {
413 LOG(ERROR) << "Failed to set USB config to " << usb_state;
414 }
415 }
Doug Zongker9270a202012-01-09 15:16:13 -0800416
xunchang95d67322019-04-05 16:16:07 -0700417 return install_result;
Doug Zongker9270a202012-01-09 15:16:13 -0800418}