blob: fd1ca1a255f3829e8d3741c6ce13c3ceed87673f [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.
Alessandro Astone4e1e8662020-03-17 22:26:22 +010093static auto AdbInstallPackageHandler(Device* device, int* result) {
Tom Marshall03354052018-06-21 00:57:24 +020094 RecoveryUI* ui = device->GetUI();
95
xunchang95d67322019-04-05 16:16:07 -070096 // How long (in seconds) we wait for the package path to be ready. It doesn't need to be too long
97 // because the minadbd service has already issued an install command. FUSE_SIDELOAD_HOST_PATHNAME
98 // will start to exist once the host connects and starts serving a package. Poll for its
99 // appearance. (Note that inotify doesn't work with FUSE.)
100 constexpr int ADB_INSTALL_TIMEOUT = 15;
Tao Bao7b9b7db2019-04-19 15:22:15 -0700101 bool should_continue = true;
xunchang95d67322019-04-05 16:16:07 -0700102 *result = INSTALL_ERROR;
103 for (int i = 0; i < ADB_INSTALL_TIMEOUT; ++i) {
104 struct stat st;
105 if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &st) != 0) {
106 if (errno == ENOENT && i < ADB_INSTALL_TIMEOUT - 1) {
107 sleep(1);
108 continue;
109 } else {
Tao Bao7b9b7db2019-04-19 15:22:15 -0700110 should_continue = false;
xunchang95d67322019-04-05 16:16:07 -0700111 ui->Print("\nTimed out waiting for fuse to be ready.\n\n");
112 break;
113 }
114 }
Tom Marshalla9ac9552018-12-17 15:57:44 -0800115 ui->CancelWaitKey();
Tom Marshall03354052018-06-21 00:57:24 +0200116
117 *result = install_package(FUSE_SIDELOAD_HOST_PATHNAME, false, false, 0, true /* verify */, ui);
Alessandro Astone4e1e8662020-03-17 22:26:22 +0100118 if (*result == INSTALL_UNVERIFIED &&
119 ui->IsTextVisible() && ask_to_continue_unverified(device)) {
Tom Marshall03354052018-06-21 00:57:24 +0200120 *result =
121 install_package(FUSE_SIDELOAD_HOST_PATHNAME, false, false, 0, false /* verify */, ui);
122 }
xunchang95d67322019-04-05 16:16:07 -0700123 break;
124 }
125
126 // Calling stat() on this magic filename signals the FUSE to exit.
127 struct stat st;
128 stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &st);
Tao Bao7b9b7db2019-04-19 15:22:15 -0700129 return std::make_pair(*result == INSTALL_SUCCESS, should_continue);
xunchang95d67322019-04-05 16:16:07 -0700130}
131
Tao Bao7b9b7db2019-04-19 15:22:15 -0700132static auto AdbRebootHandler(MinadbdCommand command, int* result,
133 Device::BuiltinAction* reboot_action) {
Tao Bao75321ad2019-04-23 11:46:25 -0700134 // Use Device::REBOOT_{FASTBOOT,RECOVERY,RESCUE}, instead of the ones with ENTER_. This allows
135 // rebooting back into fastboot/recovery/rescue mode through bootloader, which may use a newly
136 // installed bootloader/recovery image.
Tao Bao7b9b7db2019-04-19 15:22:15 -0700137 switch (command) {
138 case MinadbdCommand::kRebootBootloader:
139 *reboot_action = Device::REBOOT_BOOTLOADER;
140 break;
141 case MinadbdCommand::kRebootFastboot:
Tao Bao75321ad2019-04-23 11:46:25 -0700142 *reboot_action = Device::REBOOT_FASTBOOT;
Tao Bao7b9b7db2019-04-19 15:22:15 -0700143 break;
144 case MinadbdCommand::kRebootRecovery:
Tao Bao75321ad2019-04-23 11:46:25 -0700145 *reboot_action = Device::REBOOT_RECOVERY;
Tao Bao7b9b7db2019-04-19 15:22:15 -0700146 break;
147 case MinadbdCommand::kRebootRescue:
Tao Bao7b9b7db2019-04-19 15:22:15 -0700148 *reboot_action = Device::REBOOT_RESCUE;
149 break;
150 case MinadbdCommand::kRebootAndroid:
151 default:
152 *reboot_action = Device::REBOOT;
153 break;
154 }
155 *result = INSTALL_REBOOT;
156 return std::make_pair(true, false);
157}
158
159// Parses and executes the command from minadbd. Returns whether the caller should keep waiting for
160// next command.
161static bool HandleMessageFromMinadbd(int socket_fd,
162 const std::map<MinadbdCommand, CommandFunction>& command_map) {
xunchang95d67322019-04-05 16:16:07 -0700163 char buffer[kMinadbdMessageSize];
164 if (!android::base::ReadFully(socket_fd, buffer, kMinadbdMessageSize)) {
165 PLOG(ERROR) << "Failed to read message from minadbd";
166 return false;
167 }
168
169 std::string message(buffer, buffer + kMinadbdMessageSize);
Tao Bao7b9b7db2019-04-19 15:22:15 -0700170 auto command_type = ParseMinadbdCommand(message);
171 if (command_type == MinadbdCommand::kError) {
xunchang95d67322019-04-05 16:16:07 -0700172 return false;
173 }
174 if (command_map.find(command_type) == command_map.end()) {
175 LOG(ERROR) << "Unsupported command: "
176 << android::base::get_unaligned<unsigned int>(
177 message.substr(strlen(kMinadbdCommandPrefix)).c_str());
178 return false;
179 }
180
181 // We have received a valid command, execute the corresponding function.
182 const auto& command_func = command_map.at(command_type);
Tao Bao7b9b7db2019-04-19 15:22:15 -0700183 const auto [result, should_continue] = command_func();
184 LOG(INFO) << "Command " << static_cast<uint32_t>(command_type) << " finished with " << result;
185 if (!WriteStatusToFd(result ? MinadbdCommandStatus::kSuccess : MinadbdCommandStatus::kFailure,
186 socket_fd)) {
187 return false;
xunchang95d67322019-04-05 16:16:07 -0700188 }
Tao Bao7b9b7db2019-04-19 15:22:15 -0700189 return should_continue;
xunchang95d67322019-04-05 16:16:07 -0700190}
191
192// TODO(xunchang) add a wrapper function and kill the minadbd service there.
193static void ListenAndExecuteMinadbdCommands(
Tao Bao75321ad2019-04-23 11:46:25 -0700194 RecoveryUI* ui, pid_t minadbd_pid, android::base::unique_fd&& socket_fd,
Tao Bao7b9b7db2019-04-19 15:22:15 -0700195 const std::map<MinadbdCommand, CommandFunction>& command_map) {
xunchang95d67322019-04-05 16:16:07 -0700196 android::base::unique_fd epoll_fd(epoll_create1(O_CLOEXEC));
197 if (epoll_fd == -1) {
198 PLOG(ERROR) << "Failed to create epoll";
199 kill(minadbd_pid, SIGKILL);
200 return;
201 }
202
203 constexpr int EPOLL_MAX_EVENTS = 10;
204 struct epoll_event ev = {};
205 ev.events = EPOLLIN | EPOLLHUP;
206 ev.data.fd = socket_fd.get();
207 struct epoll_event events[EPOLL_MAX_EVENTS];
208 if (epoll_ctl(epoll_fd.get(), EPOLL_CTL_ADD, socket_fd.get(), &ev) == -1) {
209 PLOG(ERROR) << "Failed to add socket fd to epoll";
210 kill(minadbd_pid, SIGKILL);
211 return;
212 }
213
214 // Set the timeout to be 300s when waiting for minadbd commands.
215 constexpr int TIMEOUT_MILLIS = 300 * 1000;
216 while (true) {
Tao Bao75321ad2019-04-23 11:46:25 -0700217 // Reset the progress bar and the background image before each command.
218 ui->SetProgressType(RecoveryUI::EMPTY);
219 ui->SetBackground(RecoveryUI::NO_COMMAND);
220
xunchang95d67322019-04-05 16:16:07 -0700221 // Poll for the status change of the socket_fd, and handle the message if the fd is ready to
222 // read.
223 int event_count =
224 TEMP_FAILURE_RETRY(epoll_wait(epoll_fd.get(), events, EPOLL_MAX_EVENTS, TIMEOUT_MILLIS));
225 if (event_count == -1) {
226 PLOG(ERROR) << "Failed to wait for epoll events";
227 kill(minadbd_pid, SIGKILL);
228 return;
229 }
230 if (event_count == 0) {
231 LOG(ERROR) << "Timeout waiting for messages from minadbd";
232 kill(minadbd_pid, SIGKILL);
233 return;
234 }
235
236 for (int n = 0; n < event_count; n++) {
237 if (events[n].events & EPOLLHUP) {
238 LOG(INFO) << "Socket has been closed";
239 kill(minadbd_pid, SIGKILL);
240 return;
241 }
242 if (!HandleMessageFromMinadbd(socket_fd.get(), command_map)) {
243 kill(minadbd_pid, SIGKILL);
244 return;
245 }
246 }
247 }
248}
249
250// Recovery starts minadbd service as a child process, and spawns another thread to listen for the
251// message from minadbd through a socket pair. Here is an example to execute one command from adb
252// host.
253// a. recovery b. listener thread c. minadbd service
254//
255// a1. create socket pair
256// a2. fork minadbd service
257// c3. wait for the adb commands
258// from host
259// c4. after receiving host commands:
260// 1) set up pre-condition (i.e.
261// start fuse for adb sideload)
262// 2) issue command through
263// socket.
264// 3) wait for result
265// a5. start listener thread
266// b6. listen for message from
267// minadbd in a loop.
268// b7. After receiving a minadbd
269// command from socket
270// 1) execute the command function
271// 2) send the result back to
272// minadbd
273// ......
274// c8. exit upon receiving the
275// result
276// a9. wait for listener thread
277// to exit.
278//
279// a10. wait for minadbd to
280// exit
281// b11. exit the listening loop
282//
283static void CreateMinadbdServiceAndExecuteCommands(
Tom Marshalla9ac9552018-12-17 15:57:44 -0800284 Device* device, const std::map<MinadbdCommand, CommandFunction>& command_map,
Tao Bao75321ad2019-04-23 11:46:25 -0700285 bool rescue_mode) {
xunchang95d67322019-04-05 16:16:07 -0700286 signal(SIGPIPE, SIG_IGN);
287
288 android::base::unique_fd recovery_socket;
289 android::base::unique_fd minadbd_socket;
290 if (!android::base::Socketpair(AF_UNIX, SOCK_STREAM, 0, &recovery_socket, &minadbd_socket)) {
291 PLOG(ERROR) << "Failed to create socket";
292 return;
293 }
294
295 pid_t child = fork();
296 if (child == -1) {
297 PLOG(ERROR) << "Failed to fork child process";
298 return;
299 }
300 if (child == 0) {
301 recovery_socket.reset();
Tao Bao378bfbf2019-04-16 14:22:25 -0700302 std::vector<std::string> minadbd_commands = {
303 "/system/bin/minadbd",
304 "--socket_fd",
305 std::to_string(minadbd_socket.release()),
306 };
307 if (rescue_mode) {
308 minadbd_commands.push_back("--rescue");
309 }
310 auto exec_args = StringVectorToNullTerminatedArray(minadbd_commands);
311 execv(exec_args[0], exec_args.data());
xunchang95d67322019-04-05 16:16:07 -0700312 _exit(EXIT_FAILURE);
313 }
314
315 minadbd_socket.reset();
316
317 // We need to call SetUsbConfig() after forking minadbd service. Because the function waits for
318 // the usb state to be updated, which depends on sys.usb.ffs.ready=1 set in the adb daemon.
319 if (!SetUsbConfig("sideload")) {
320 LOG(ERROR) << "Failed to set usb config to sideload";
321 return;
322 }
323
Tom Marshalla9ac9552018-12-17 15:57:44 -0800324 RecoveryUI* ui = device->GetUI();
Tao Bao75321ad2019-04-23 11:46:25 -0700325 std::thread listener_thread(ListenAndExecuteMinadbdCommands, ui, child,
326 std::move(recovery_socket), std::ref(command_map));
Tom Marshalla9ac9552018-12-17 15:57:44 -0800327
328 if (ui->IsTextVisible()) {
329 std::vector<std::string> headers{ rescue_mode ? "Rescue mode" : "ADB Sideload" };
330 std::vector<std::string> entries{ "Cancel" };
331 size_t chosen_item = ui->ShowMenu(
332 headers, entries, 0, true,
333 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
334
335 if (chosen_item != Device::kRefresh) {
336 // Kill minadbd if 'cancel' was selected, to abort sideload.
337 kill(child, SIGKILL);
338 }
339 }
340
xunchang95d67322019-04-05 16:16:07 -0700341 if (listener_thread.joinable()) {
342 listener_thread.join();
343 }
344
345 int status;
346 waitpid(child, &status, 0);
347 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
348 if (WEXITSTATUS(status) == MinadbdErrorCode::kMinadbdAdbVersionError) {
349 LOG(ERROR) << "\nYou need adb 1.0.32 or newer to sideload\nto this device.\n";
350 } else if (!WIFSIGNALED(status)) {
351 LOG(ERROR) << "\n(adbd status " << WEXITSTATUS(status) << ")";
352 }
353 }
354
355 signal(SIGPIPE, SIG_DFL);
356}
357
Alessandro Astone4e1e8662020-03-17 22:26:22 +0100358int ApplyFromAdb(Device* device, bool rescue_mode, Device::BuiltinAction* reboot_action) {
Hridya Valsarajue4ef4532018-08-31 11:57:51 -0700359 // Save the usb state to restore after the sideload operation.
360 std::string usb_state = android::base::GetProperty("sys.usb.state", "none");
361 // Clean up state and stop adbd.
362 if (usb_state != "none" && !SetUsbConfig("none")) {
363 LOG(ERROR) << "Failed to clear USB config";
364 return INSTALL_ERROR;
365 }
Tao Bao682c34b2015-04-07 17:16:35 -0700366
xunchang95d67322019-04-05 16:16:07 -0700367 int install_result = INSTALL_ERROR;
Tao Bao7b9b7db2019-04-19 15:22:15 -0700368 std::map<MinadbdCommand, CommandFunction> command_map{
Alessandro Astone4e1e8662020-03-17 22:26:22 +0100369 { MinadbdCommand::kInstall, std::bind(&AdbInstallPackageHandler, device, &install_result) },
Tao Bao7b9b7db2019-04-19 15:22:15 -0700370 { MinadbdCommand::kRebootAndroid, std::bind(&AdbRebootHandler, MinadbdCommand::kRebootAndroid,
371 &install_result, reboot_action) },
372 { MinadbdCommand::kRebootBootloader,
373 std::bind(&AdbRebootHandler, MinadbdCommand::kRebootBootloader, &install_result,
374 reboot_action) },
375 { MinadbdCommand::kRebootFastboot, std::bind(&AdbRebootHandler, MinadbdCommand::kRebootFastboot,
376 &install_result, reboot_action) },
377 { MinadbdCommand::kRebootRecovery, std::bind(&AdbRebootHandler, MinadbdCommand::kRebootRecovery,
378 &install_result, reboot_action) },
379 { MinadbdCommand::kRebootRescue,
380 std::bind(&AdbRebootHandler, MinadbdCommand::kRebootRescue, &install_result, reboot_action) },
xunchang95d67322019-04-05 16:16:07 -0700381 };
Doug Zongker9270a202012-01-09 15:16:13 -0800382
Tom Marshall03354052018-06-21 00:57:24 +0200383 RecoveryUI* ui = device->GetUI();
384
xunchang5a1916b2019-04-22 12:18:14 -0700385 if (!rescue_mode) {
386 ui->Print(
387 "\n\nNow send the package you want to apply\n"
388 "to the device with \"adb sideload <filename>\"...\n");
389 } else {
xunchang5a1916b2019-04-22 12:18:14 -0700390 command_map.emplace(MinadbdCommand::kWipeData, [&device]() {
391 bool result = WipeData(device, false);
392 return std::make_pair(result, true);
393 });
Tao Bao0bbb2ed2019-07-08 18:07:22 -0700394 command_map.emplace(MinadbdCommand::kNoOp, []() { return std::make_pair(true, true); });
395
396 ui->Print("\n\nWaiting for rescue commands...\n");
xunchang5a1916b2019-04-22 12:18:14 -0700397 }
398
Tom Marshalla9ac9552018-12-17 15:57:44 -0800399 CreateMinadbdServiceAndExecuteCommands(device, command_map, rescue_mode);
Doug Zongker075ad802014-06-26 15:35:51 -0700400
Hridya Valsarajue4ef4532018-08-31 11:57:51 -0700401 // Clean up before switching to the older state, for example setting the state
402 // to none sets sys/class/android_usb/android0/enable to 0.
403 if (!SetUsbConfig("none")) {
404 LOG(ERROR) << "Failed to clear USB config";
405 }
406
407 if (usb_state != "none") {
408 if (!SetUsbConfig(usb_state)) {
409 LOG(ERROR) << "Failed to set USB config to " << usb_state;
410 }
411 }
Doug Zongker9270a202012-01-09 15:16:13 -0800412
xunchang95d67322019-04-05 16:16:07 -0700413 return install_result;
Doug Zongker9270a202012-01-09 15:16:13 -0800414}