blob: 84711d3273f31d3b6e77c8047fc90a47c83269b6 [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.
93static auto AdbInstallPackageHandler(RecoveryUI* ui, int* result) {
xunchang95d67322019-04-05 16:16:07 -070094 // How long (in seconds) we wait for the package path to be ready. It doesn't need to be too long
95 // because the minadbd service has already issued an install command. FUSE_SIDELOAD_HOST_PATHNAME
96 // will start to exist once the host connects and starts serving a package. Poll for its
97 // appearance. (Note that inotify doesn't work with FUSE.)
98 constexpr int ADB_INSTALL_TIMEOUT = 15;
Tao Bao7b9b7db2019-04-19 15:22:15 -070099 bool should_continue = true;
xunchang95d67322019-04-05 16:16:07 -0700100 *result = INSTALL_ERROR;
101 for (int i = 0; i < ADB_INSTALL_TIMEOUT; ++i) {
102 struct stat st;
103 if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &st) != 0) {
104 if (errno == ENOENT && i < ADB_INSTALL_TIMEOUT - 1) {
105 sleep(1);
106 continue;
107 } else {
Tao Bao7b9b7db2019-04-19 15:22:15 -0700108 should_continue = false;
xunchang95d67322019-04-05 16:16:07 -0700109 ui->Print("\nTimed out waiting for fuse to be ready.\n\n");
110 break;
111 }
112 }
Tom Marshalla9ac9552018-12-17 15:57:44 -0800113 ui->CancelWaitKey();
xunchang388d2532019-04-12 16:22:15 -0700114 *result = install_package(FUSE_SIDELOAD_HOST_PATHNAME, false, false, 0, ui);
xunchang95d67322019-04-05 16:16:07 -0700115 break;
116 }
117
118 // Calling stat() on this magic filename signals the FUSE to exit.
119 struct stat st;
120 stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &st);
Tao Bao7b9b7db2019-04-19 15:22:15 -0700121 return std::make_pair(*result == INSTALL_SUCCESS, should_continue);
xunchang95d67322019-04-05 16:16:07 -0700122}
123
Tao Bao7b9b7db2019-04-19 15:22:15 -0700124static auto AdbRebootHandler(MinadbdCommand command, int* result,
125 Device::BuiltinAction* reboot_action) {
Tao Bao75321ad2019-04-23 11:46:25 -0700126 // Use Device::REBOOT_{FASTBOOT,RECOVERY,RESCUE}, instead of the ones with ENTER_. This allows
127 // rebooting back into fastboot/recovery/rescue mode through bootloader, which may use a newly
128 // installed bootloader/recovery image.
Tao Bao7b9b7db2019-04-19 15:22:15 -0700129 switch (command) {
130 case MinadbdCommand::kRebootBootloader:
131 *reboot_action = Device::REBOOT_BOOTLOADER;
132 break;
133 case MinadbdCommand::kRebootFastboot:
Tao Bao75321ad2019-04-23 11:46:25 -0700134 *reboot_action = Device::REBOOT_FASTBOOT;
Tao Bao7b9b7db2019-04-19 15:22:15 -0700135 break;
136 case MinadbdCommand::kRebootRecovery:
Tao Bao75321ad2019-04-23 11:46:25 -0700137 *reboot_action = Device::REBOOT_RECOVERY;
Tao Bao7b9b7db2019-04-19 15:22:15 -0700138 break;
139 case MinadbdCommand::kRebootRescue:
Tao Bao7b9b7db2019-04-19 15:22:15 -0700140 *reboot_action = Device::REBOOT_RESCUE;
141 break;
142 case MinadbdCommand::kRebootAndroid:
143 default:
144 *reboot_action = Device::REBOOT;
145 break;
146 }
147 *result = INSTALL_REBOOT;
148 return std::make_pair(true, false);
149}
150
151// Parses and executes the command from minadbd. Returns whether the caller should keep waiting for
152// next command.
153static bool HandleMessageFromMinadbd(int socket_fd,
154 const std::map<MinadbdCommand, CommandFunction>& command_map) {
xunchang95d67322019-04-05 16:16:07 -0700155 char buffer[kMinadbdMessageSize];
156 if (!android::base::ReadFully(socket_fd, buffer, kMinadbdMessageSize)) {
157 PLOG(ERROR) << "Failed to read message from minadbd";
158 return false;
159 }
160
161 std::string message(buffer, buffer + kMinadbdMessageSize);
Tao Bao7b9b7db2019-04-19 15:22:15 -0700162 auto command_type = ParseMinadbdCommand(message);
163 if (command_type == MinadbdCommand::kError) {
xunchang95d67322019-04-05 16:16:07 -0700164 return false;
165 }
166 if (command_map.find(command_type) == command_map.end()) {
167 LOG(ERROR) << "Unsupported command: "
168 << android::base::get_unaligned<unsigned int>(
169 message.substr(strlen(kMinadbdCommandPrefix)).c_str());
170 return false;
171 }
172
173 // We have received a valid command, execute the corresponding function.
174 const auto& command_func = command_map.at(command_type);
Tao Bao7b9b7db2019-04-19 15:22:15 -0700175 const auto [result, should_continue] = command_func();
176 LOG(INFO) << "Command " << static_cast<uint32_t>(command_type) << " finished with " << result;
177 if (!WriteStatusToFd(result ? MinadbdCommandStatus::kSuccess : MinadbdCommandStatus::kFailure,
178 socket_fd)) {
179 return false;
xunchang95d67322019-04-05 16:16:07 -0700180 }
Tao Bao7b9b7db2019-04-19 15:22:15 -0700181 return should_continue;
xunchang95d67322019-04-05 16:16:07 -0700182}
183
184// TODO(xunchang) add a wrapper function and kill the minadbd service there.
185static void ListenAndExecuteMinadbdCommands(
Tao Bao75321ad2019-04-23 11:46:25 -0700186 RecoveryUI* ui, pid_t minadbd_pid, android::base::unique_fd&& socket_fd,
Tao Bao7b9b7db2019-04-19 15:22:15 -0700187 const std::map<MinadbdCommand, CommandFunction>& command_map) {
xunchang95d67322019-04-05 16:16:07 -0700188 android::base::unique_fd epoll_fd(epoll_create1(O_CLOEXEC));
189 if (epoll_fd == -1) {
190 PLOG(ERROR) << "Failed to create epoll";
191 kill(minadbd_pid, SIGKILL);
192 return;
193 }
194
195 constexpr int EPOLL_MAX_EVENTS = 10;
196 struct epoll_event ev = {};
197 ev.events = EPOLLIN | EPOLLHUP;
198 ev.data.fd = socket_fd.get();
199 struct epoll_event events[EPOLL_MAX_EVENTS];
200 if (epoll_ctl(epoll_fd.get(), EPOLL_CTL_ADD, socket_fd.get(), &ev) == -1) {
201 PLOG(ERROR) << "Failed to add socket fd to epoll";
202 kill(minadbd_pid, SIGKILL);
203 return;
204 }
205
206 // Set the timeout to be 300s when waiting for minadbd commands.
207 constexpr int TIMEOUT_MILLIS = 300 * 1000;
208 while (true) {
Tao Bao75321ad2019-04-23 11:46:25 -0700209 // Reset the progress bar and the background image before each command.
210 ui->SetProgressType(RecoveryUI::EMPTY);
211 ui->SetBackground(RecoveryUI::NO_COMMAND);
212
xunchang95d67322019-04-05 16:16:07 -0700213 // Poll for the status change of the socket_fd, and handle the message if the fd is ready to
214 // read.
215 int event_count =
216 TEMP_FAILURE_RETRY(epoll_wait(epoll_fd.get(), events, EPOLL_MAX_EVENTS, TIMEOUT_MILLIS));
217 if (event_count == -1) {
218 PLOG(ERROR) << "Failed to wait for epoll events";
219 kill(minadbd_pid, SIGKILL);
220 return;
221 }
222 if (event_count == 0) {
223 LOG(ERROR) << "Timeout waiting for messages from minadbd";
224 kill(minadbd_pid, SIGKILL);
225 return;
226 }
227
228 for (int n = 0; n < event_count; n++) {
229 if (events[n].events & EPOLLHUP) {
230 LOG(INFO) << "Socket has been closed";
231 kill(minadbd_pid, SIGKILL);
232 return;
233 }
234 if (!HandleMessageFromMinadbd(socket_fd.get(), command_map)) {
235 kill(minadbd_pid, SIGKILL);
236 return;
237 }
238 }
239 }
240}
241
242// Recovery starts minadbd service as a child process, and spawns another thread to listen for the
243// message from minadbd through a socket pair. Here is an example to execute one command from adb
244// host.
245// a. recovery b. listener thread c. minadbd service
246//
247// a1. create socket pair
248// a2. fork minadbd service
249// c3. wait for the adb commands
250// from host
251// c4. after receiving host commands:
252// 1) set up pre-condition (i.e.
253// start fuse for adb sideload)
254// 2) issue command through
255// socket.
256// 3) wait for result
257// a5. start listener thread
258// b6. listen for message from
259// minadbd in a loop.
260// b7. After receiving a minadbd
261// command from socket
262// 1) execute the command function
263// 2) send the result back to
264// minadbd
265// ......
266// c8. exit upon receiving the
267// result
268// a9. wait for listener thread
269// to exit.
270//
271// a10. wait for minadbd to
272// exit
273// b11. exit the listening loop
274//
275static void CreateMinadbdServiceAndExecuteCommands(
Tom Marshalla9ac9552018-12-17 15:57:44 -0800276 Device* device, const std::map<MinadbdCommand, CommandFunction>& command_map,
Tao Bao75321ad2019-04-23 11:46:25 -0700277 bool rescue_mode) {
xunchang95d67322019-04-05 16:16:07 -0700278 signal(SIGPIPE, SIG_IGN);
279
280 android::base::unique_fd recovery_socket;
281 android::base::unique_fd minadbd_socket;
282 if (!android::base::Socketpair(AF_UNIX, SOCK_STREAM, 0, &recovery_socket, &minadbd_socket)) {
283 PLOG(ERROR) << "Failed to create socket";
284 return;
285 }
286
287 pid_t child = fork();
288 if (child == -1) {
289 PLOG(ERROR) << "Failed to fork child process";
290 return;
291 }
292 if (child == 0) {
293 recovery_socket.reset();
Tao Bao378bfbf2019-04-16 14:22:25 -0700294 std::vector<std::string> minadbd_commands = {
295 "/system/bin/minadbd",
296 "--socket_fd",
297 std::to_string(minadbd_socket.release()),
298 };
299 if (rescue_mode) {
300 minadbd_commands.push_back("--rescue");
301 }
302 auto exec_args = StringVectorToNullTerminatedArray(minadbd_commands);
303 execv(exec_args[0], exec_args.data());
xunchang95d67322019-04-05 16:16:07 -0700304 _exit(EXIT_FAILURE);
305 }
306
307 minadbd_socket.reset();
308
309 // We need to call SetUsbConfig() after forking minadbd service. Because the function waits for
310 // the usb state to be updated, which depends on sys.usb.ffs.ready=1 set in the adb daemon.
311 if (!SetUsbConfig("sideload")) {
312 LOG(ERROR) << "Failed to set usb config to sideload";
313 return;
314 }
315
Tom Marshalla9ac9552018-12-17 15:57:44 -0800316 RecoveryUI* ui = device->GetUI();
Tao Bao75321ad2019-04-23 11:46:25 -0700317 std::thread listener_thread(ListenAndExecuteMinadbdCommands, ui, child,
318 std::move(recovery_socket), std::ref(command_map));
Tom Marshalla9ac9552018-12-17 15:57:44 -0800319
320 if (ui->IsTextVisible()) {
321 std::vector<std::string> headers{ rescue_mode ? "Rescue mode" : "ADB Sideload" };
322 std::vector<std::string> entries{ "Cancel" };
323 size_t chosen_item = ui->ShowMenu(
324 headers, entries, 0, true,
325 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
326
327 if (chosen_item != Device::kRefresh) {
328 // Kill minadbd if 'cancel' was selected, to abort sideload.
329 kill(child, SIGKILL);
330 }
331 }
332
xunchang95d67322019-04-05 16:16:07 -0700333 if (listener_thread.joinable()) {
334 listener_thread.join();
335 }
336
337 int status;
338 waitpid(child, &status, 0);
339 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
340 if (WEXITSTATUS(status) == MinadbdErrorCode::kMinadbdAdbVersionError) {
341 LOG(ERROR) << "\nYou need adb 1.0.32 or newer to sideload\nto this device.\n";
342 } else if (!WIFSIGNALED(status)) {
343 LOG(ERROR) << "\n(adbd status " << WEXITSTATUS(status) << ")";
344 }
345 }
346
347 signal(SIGPIPE, SIG_DFL);
348}
349
xunchang5a1916b2019-04-22 12:18:14 -0700350int ApplyFromAdb(Device* device, bool rescue_mode, Device::BuiltinAction* reboot_action) {
Hridya Valsarajue4ef4532018-08-31 11:57:51 -0700351 // Save the usb state to restore after the sideload operation.
352 std::string usb_state = android::base::GetProperty("sys.usb.state", "none");
353 // Clean up state and stop adbd.
354 if (usb_state != "none" && !SetUsbConfig("none")) {
355 LOG(ERROR) << "Failed to clear USB config";
356 return INSTALL_ERROR;
357 }
Tao Bao682c34b2015-04-07 17:16:35 -0700358
xunchang5a1916b2019-04-22 12:18:14 -0700359 RecoveryUI* ui = device->GetUI();
Doug Zongker9270a202012-01-09 15:16:13 -0800360
xunchang95d67322019-04-05 16:16:07 -0700361 int install_result = INSTALL_ERROR;
Tao Bao7b9b7db2019-04-19 15:22:15 -0700362 std::map<MinadbdCommand, CommandFunction> command_map{
363 { MinadbdCommand::kInstall, std::bind(&AdbInstallPackageHandler, ui, &install_result) },
364 { MinadbdCommand::kRebootAndroid, std::bind(&AdbRebootHandler, MinadbdCommand::kRebootAndroid,
365 &install_result, reboot_action) },
366 { MinadbdCommand::kRebootBootloader,
367 std::bind(&AdbRebootHandler, MinadbdCommand::kRebootBootloader, &install_result,
368 reboot_action) },
369 { MinadbdCommand::kRebootFastboot, std::bind(&AdbRebootHandler, MinadbdCommand::kRebootFastboot,
370 &install_result, reboot_action) },
371 { MinadbdCommand::kRebootRecovery, std::bind(&AdbRebootHandler, MinadbdCommand::kRebootRecovery,
372 &install_result, reboot_action) },
373 { MinadbdCommand::kRebootRescue,
374 std::bind(&AdbRebootHandler, MinadbdCommand::kRebootRescue, &install_result, reboot_action) },
xunchang95d67322019-04-05 16:16:07 -0700375 };
Doug Zongker9270a202012-01-09 15:16:13 -0800376
xunchang5a1916b2019-04-22 12:18:14 -0700377 if (!rescue_mode) {
378 ui->Print(
379 "\n\nNow send the package you want to apply\n"
380 "to the device with \"adb sideload <filename>\"...\n");
381 } else {
xunchang5a1916b2019-04-22 12:18:14 -0700382 command_map.emplace(MinadbdCommand::kWipeData, [&device]() {
383 bool result = WipeData(device, false);
384 return std::make_pair(result, true);
385 });
Tao Bao0bbb2ed2019-07-08 18:07:22 -0700386 command_map.emplace(MinadbdCommand::kNoOp, []() { return std::make_pair(true, true); });
387
388 ui->Print("\n\nWaiting for rescue commands...\n");
xunchang5a1916b2019-04-22 12:18:14 -0700389 }
390
Tom Marshalla9ac9552018-12-17 15:57:44 -0800391 CreateMinadbdServiceAndExecuteCommands(device, command_map, rescue_mode);
Doug Zongker075ad802014-06-26 15:35:51 -0700392
Hridya Valsarajue4ef4532018-08-31 11:57:51 -0700393 // Clean up before switching to the older state, for example setting the state
394 // to none sets sys/class/android_usb/android0/enable to 0.
395 if (!SetUsbConfig("none")) {
396 LOG(ERROR) << "Failed to clear USB config";
397 }
398
399 if (usb_state != "none") {
400 if (!SetUsbConfig(usb_state)) {
401 LOG(ERROR) << "Failed to set USB config to " << usb_state;
402 }
403 }
Doug Zongker9270a202012-01-09 15:16:13 -0800404
xunchang95d67322019-04-05 16:16:07 -0700405 return install_result;
Doug Zongker9270a202012-01-09 15:16:13 -0800406}