blob: 9dfe0407f8c3863f2e88ee4752840345df06ca9d [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>
xunchang34690ce2019-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
xunchang34690ce2019-04-05 16:16:07 -070031#include <atomic>
32#include <functional>
33#include <map>
Tao Bao10f441a2019-04-19 15:22:15 -070034#include <utility>
Tao Baoc6dc3252019-04-16 14:22:25 -070035#include <vector>
xunchang34690ce2019-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>
xunchang34690ce2019-04-05 16:16:07 -070039#include <android-base/memory.h>
Elliott Hughescb220402016-09-23 15:30:55 -070040#include <android-base/properties.h>
xunchang34690ce2019-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"
xunchang34690ce2019-04-05 16:16:07 -070046#include "minadbd_types.h"
Tao Baoc6dc3252019-04-16 14:22:25 -070047#include "otautil/sysutil.h"
Tao Bao10f441a2019-04-19 15:22:15 -070048#include "recovery_ui/device.h"
Tianjie Xu8f397302018-08-20 13:40:47 -070049#include "recovery_ui/ui.h"
Tao Bao0150d012017-05-01 11:31:28 -070050
Tao Bao10f441a2019-04-19 15:22:15 -070051// A CommandFunction returns a pair of (result, should_continue), which indicates the command
52// execution result and whether it should proceed to the next iteration. The execution result will
53// always be sent to the minadbd side.
54using CommandFunction = std::function<std::pair<bool, bool>()>;
xunchang34690ce2019-04-05 16:16:07 -070055
xunchang24788852019-03-22 16:08:52 -070056static bool SetUsbConfig(const std::string& state) {
57 android::base::SetProperty("sys.usb.config", state);
58 return android::base::WaitForProperty("sys.usb.state", state);
59}
60
Tao Bao10f441a2019-04-19 15:22:15 -070061// Parses the minadbd command in |message|; returns MinadbdCommand::kError upon errors.
62static MinadbdCommand ParseMinadbdCommand(const std::string& message) {
xunchang34690ce2019-04-05 16:16:07 -070063 if (!android::base::StartsWith(message, kMinadbdCommandPrefix)) {
64 LOG(ERROR) << "Failed to parse command in message " << message;
Tao Bao10f441a2019-04-19 15:22:15 -070065 return MinadbdCommand::kError;
xunchang34690ce2019-04-05 16:16:07 -070066 }
67
68 auto cmd_code_string = message.substr(strlen(kMinadbdCommandPrefix));
69 auto cmd_code = android::base::get_unaligned<uint32_t>(cmd_code_string.c_str());
Tao Bao10f441a2019-04-19 15:22:15 -070070 if (cmd_code >= static_cast<uint32_t>(MinadbdCommand::kError)) {
xunchang34690ce2019-04-05 16:16:07 -070071 LOG(ERROR) << "Unsupported command code: " << cmd_code;
Tao Bao10f441a2019-04-19 15:22:15 -070072 return MinadbdCommand::kError;
xunchang34690ce2019-04-05 16:16:07 -070073 }
74
Tao Bao10f441a2019-04-19 15:22:15 -070075 return static_cast<MinadbdCommand>(cmd_code);
xunchang34690ce2019-04-05 16:16:07 -070076}
77
78static bool WriteStatusToFd(MinadbdCommandStatus status, int fd) {
79 char message[kMinadbdMessageSize];
80 memcpy(message, kMinadbdStatusPrefix, strlen(kMinadbdStatusPrefix));
81 android::base::put_unaligned(message + strlen(kMinadbdStatusPrefix), status);
82
83 if (!android::base::WriteFully(fd, message, kMinadbdMessageSize)) {
84 PLOG(ERROR) << "Failed to write message " << message;
85 return false;
86 }
87 return true;
88}
89
Tao Bao10f441a2019-04-19 15:22:15 -070090// Installs the package from FUSE. Returns the installation result and whether it should continue
91// waiting for new commands.
92static auto AdbInstallPackageHandler(RecoveryUI* ui, int* result) {
xunchang34690ce2019-04-05 16:16:07 -070093 // How long (in seconds) we wait for the package path to be ready. It doesn't need to be too long
94 // because the minadbd service has already issued an install command. FUSE_SIDELOAD_HOST_PATHNAME
95 // will start to exist once the host connects and starts serving a package. Poll for its
96 // appearance. (Note that inotify doesn't work with FUSE.)
97 constexpr int ADB_INSTALL_TIMEOUT = 15;
Tao Bao10f441a2019-04-19 15:22:15 -070098 bool should_continue = true;
xunchang34690ce2019-04-05 16:16:07 -070099 *result = INSTALL_ERROR;
100 for (int i = 0; i < ADB_INSTALL_TIMEOUT; ++i) {
101 struct stat st;
102 if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &st) != 0) {
103 if (errno == ENOENT && i < ADB_INSTALL_TIMEOUT - 1) {
104 sleep(1);
105 continue;
106 } else {
Tao Bao10f441a2019-04-19 15:22:15 -0700107 should_continue = false;
xunchang34690ce2019-04-05 16:16:07 -0700108 ui->Print("\nTimed out waiting for fuse to be ready.\n\n");
109 break;
110 }
111 }
xunchang316e9712019-04-12 16:22:15 -0700112 *result = install_package(FUSE_SIDELOAD_HOST_PATHNAME, false, false, 0, ui);
xunchang34690ce2019-04-05 16:16:07 -0700113 break;
114 }
115
116 // Calling stat() on this magic filename signals the FUSE to exit.
117 struct stat st;
118 stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &st);
Tao Bao10f441a2019-04-19 15:22:15 -0700119 return std::make_pair(*result == INSTALL_SUCCESS, should_continue);
xunchang34690ce2019-04-05 16:16:07 -0700120}
121
Tao Bao10f441a2019-04-19 15:22:15 -0700122static auto AdbRebootHandler(MinadbdCommand command, int* result,
123 Device::BuiltinAction* reboot_action) {
Tao Baod9cb0142019-04-23 11:46:25 -0700124 // Use Device::REBOOT_{FASTBOOT,RECOVERY,RESCUE}, instead of the ones with ENTER_. This allows
125 // rebooting back into fastboot/recovery/rescue mode through bootloader, which may use a newly
126 // installed bootloader/recovery image.
Tao Bao10f441a2019-04-19 15:22:15 -0700127 switch (command) {
128 case MinadbdCommand::kRebootBootloader:
129 *reboot_action = Device::REBOOT_BOOTLOADER;
130 break;
131 case MinadbdCommand::kRebootFastboot:
Tao Baod9cb0142019-04-23 11:46:25 -0700132 *reboot_action = Device::REBOOT_FASTBOOT;
Tao Bao10f441a2019-04-19 15:22:15 -0700133 break;
134 case MinadbdCommand::kRebootRecovery:
Tao Baod9cb0142019-04-23 11:46:25 -0700135 *reboot_action = Device::REBOOT_RECOVERY;
Tao Bao10f441a2019-04-19 15:22:15 -0700136 break;
137 case MinadbdCommand::kRebootRescue:
Tao Bao10f441a2019-04-19 15:22:15 -0700138 *reboot_action = Device::REBOOT_RESCUE;
139 break;
140 case MinadbdCommand::kRebootAndroid:
141 default:
142 *reboot_action = Device::REBOOT;
143 break;
144 }
145 *result = INSTALL_REBOOT;
146 return std::make_pair(true, false);
147}
148
149// Parses and executes the command from minadbd. Returns whether the caller should keep waiting for
150// next command.
151static bool HandleMessageFromMinadbd(int socket_fd,
152 const std::map<MinadbdCommand, CommandFunction>& command_map) {
xunchang34690ce2019-04-05 16:16:07 -0700153 char buffer[kMinadbdMessageSize];
154 if (!android::base::ReadFully(socket_fd, buffer, kMinadbdMessageSize)) {
155 PLOG(ERROR) << "Failed to read message from minadbd";
156 return false;
157 }
158
159 std::string message(buffer, buffer + kMinadbdMessageSize);
Tao Bao10f441a2019-04-19 15:22:15 -0700160 auto command_type = ParseMinadbdCommand(message);
161 if (command_type == MinadbdCommand::kError) {
xunchang34690ce2019-04-05 16:16:07 -0700162 return false;
163 }
164 if (command_map.find(command_type) == command_map.end()) {
165 LOG(ERROR) << "Unsupported command: "
166 << android::base::get_unaligned<unsigned int>(
167 message.substr(strlen(kMinadbdCommandPrefix)).c_str());
168 return false;
169 }
170
171 // We have received a valid command, execute the corresponding function.
172 const auto& command_func = command_map.at(command_type);
Tao Bao10f441a2019-04-19 15:22:15 -0700173 const auto [result, should_continue] = command_func();
174 LOG(INFO) << "Command " << static_cast<uint32_t>(command_type) << " finished with " << result;
175 if (!WriteStatusToFd(result ? MinadbdCommandStatus::kSuccess : MinadbdCommandStatus::kFailure,
176 socket_fd)) {
177 return false;
xunchang34690ce2019-04-05 16:16:07 -0700178 }
Tao Bao10f441a2019-04-19 15:22:15 -0700179 return should_continue;
xunchang34690ce2019-04-05 16:16:07 -0700180}
181
182// TODO(xunchang) add a wrapper function and kill the minadbd service there.
183static void ListenAndExecuteMinadbdCommands(
Tao Baod9cb0142019-04-23 11:46:25 -0700184 RecoveryUI* ui, pid_t minadbd_pid, android::base::unique_fd&& socket_fd,
Tao Bao10f441a2019-04-19 15:22:15 -0700185 const std::map<MinadbdCommand, CommandFunction>& command_map) {
xunchang34690ce2019-04-05 16:16:07 -0700186 android::base::unique_fd epoll_fd(epoll_create1(O_CLOEXEC));
187 if (epoll_fd == -1) {
188 PLOG(ERROR) << "Failed to create epoll";
189 kill(minadbd_pid, SIGKILL);
190 return;
191 }
192
193 constexpr int EPOLL_MAX_EVENTS = 10;
194 struct epoll_event ev = {};
195 ev.events = EPOLLIN | EPOLLHUP;
196 ev.data.fd = socket_fd.get();
197 struct epoll_event events[EPOLL_MAX_EVENTS];
198 if (epoll_ctl(epoll_fd.get(), EPOLL_CTL_ADD, socket_fd.get(), &ev) == -1) {
199 PLOG(ERROR) << "Failed to add socket fd to epoll";
200 kill(minadbd_pid, SIGKILL);
201 return;
202 }
203
204 // Set the timeout to be 300s when waiting for minadbd commands.
205 constexpr int TIMEOUT_MILLIS = 300 * 1000;
206 while (true) {
Tao Baod9cb0142019-04-23 11:46:25 -0700207 // Reset the progress bar and the background image before each command.
208 ui->SetProgressType(RecoveryUI::EMPTY);
209 ui->SetBackground(RecoveryUI::NO_COMMAND);
210
xunchang34690ce2019-04-05 16:16:07 -0700211 // Poll for the status change of the socket_fd, and handle the message if the fd is ready to
212 // read.
213 int event_count =
214 TEMP_FAILURE_RETRY(epoll_wait(epoll_fd.get(), events, EPOLL_MAX_EVENTS, TIMEOUT_MILLIS));
215 if (event_count == -1) {
216 PLOG(ERROR) << "Failed to wait for epoll events";
217 kill(minadbd_pid, SIGKILL);
218 return;
219 }
220 if (event_count == 0) {
221 LOG(ERROR) << "Timeout waiting for messages from minadbd";
222 kill(minadbd_pid, SIGKILL);
223 return;
224 }
225
226 for (int n = 0; n < event_count; n++) {
227 if (events[n].events & EPOLLHUP) {
228 LOG(INFO) << "Socket has been closed";
229 kill(minadbd_pid, SIGKILL);
230 return;
231 }
232 if (!HandleMessageFromMinadbd(socket_fd.get(), command_map)) {
233 kill(minadbd_pid, SIGKILL);
234 return;
235 }
236 }
237 }
238}
239
240// Recovery starts minadbd service as a child process, and spawns another thread to listen for the
241// message from minadbd through a socket pair. Here is an example to execute one command from adb
242// host.
243// a. recovery b. listener thread c. minadbd service
244//
245// a1. create socket pair
246// a2. fork minadbd service
247// c3. wait for the adb commands
248// from host
249// c4. after receiving host commands:
250// 1) set up pre-condition (i.e.
251// start fuse for adb sideload)
252// 2) issue command through
253// socket.
254// 3) wait for result
255// a5. start listener thread
256// b6. listen for message from
257// minadbd in a loop.
258// b7. After receiving a minadbd
259// command from socket
260// 1) execute the command function
261// 2) send the result back to
262// minadbd
263// ......
264// c8. exit upon receiving the
265// result
266// a9. wait for listener thread
267// to exit.
268//
269// a10. wait for minadbd to
270// exit
271// b11. exit the listening loop
272//
273static void CreateMinadbdServiceAndExecuteCommands(
Tao Baod9cb0142019-04-23 11:46:25 -0700274 RecoveryUI* ui, const std::map<MinadbdCommand, CommandFunction>& command_map,
275 bool rescue_mode) {
xunchang34690ce2019-04-05 16:16:07 -0700276 signal(SIGPIPE, SIG_IGN);
277
278 android::base::unique_fd recovery_socket;
279 android::base::unique_fd minadbd_socket;
280 if (!android::base::Socketpair(AF_UNIX, SOCK_STREAM, 0, &recovery_socket, &minadbd_socket)) {
281 PLOG(ERROR) << "Failed to create socket";
282 return;
283 }
284
285 pid_t child = fork();
286 if (child == -1) {
287 PLOG(ERROR) << "Failed to fork child process";
288 return;
289 }
290 if (child == 0) {
291 recovery_socket.reset();
Tao Baoc6dc3252019-04-16 14:22:25 -0700292 std::vector<std::string> minadbd_commands = {
293 "/system/bin/minadbd",
294 "--socket_fd",
295 std::to_string(minadbd_socket.release()),
296 };
297 if (rescue_mode) {
298 minadbd_commands.push_back("--rescue");
299 }
300 auto exec_args = StringVectorToNullTerminatedArray(minadbd_commands);
301 execv(exec_args[0], exec_args.data());
xunchang34690ce2019-04-05 16:16:07 -0700302 _exit(EXIT_FAILURE);
303 }
304
305 minadbd_socket.reset();
306
307 // We need to call SetUsbConfig() after forking minadbd service. Because the function waits for
308 // the usb state to be updated, which depends on sys.usb.ffs.ready=1 set in the adb daemon.
309 if (!SetUsbConfig("sideload")) {
310 LOG(ERROR) << "Failed to set usb config to sideload";
311 return;
312 }
313
Tao Baod9cb0142019-04-23 11:46:25 -0700314 std::thread listener_thread(ListenAndExecuteMinadbdCommands, ui, child,
315 std::move(recovery_socket), std::ref(command_map));
xunchang34690ce2019-04-05 16:16:07 -0700316 if (listener_thread.joinable()) {
317 listener_thread.join();
318 }
319
320 int status;
321 waitpid(child, &status, 0);
322 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
323 if (WEXITSTATUS(status) == MinadbdErrorCode::kMinadbdAdbVersionError) {
324 LOG(ERROR) << "\nYou need adb 1.0.32 or newer to sideload\nto this device.\n";
325 } else if (!WIFSIGNALED(status)) {
326 LOG(ERROR) << "\n(adbd status " << WEXITSTATUS(status) << ")";
327 }
328 }
329
330 signal(SIGPIPE, SIG_DFL);
331}
332
Tao Bao10f441a2019-04-19 15:22:15 -0700333int ApplyFromAdb(RecoveryUI* ui, bool rescue_mode, Device::BuiltinAction* reboot_action) {
Hridya Valsarajue4ef4532018-08-31 11:57:51 -0700334 // Save the usb state to restore after the sideload operation.
335 std::string usb_state = android::base::GetProperty("sys.usb.state", "none");
336 // Clean up state and stop adbd.
337 if (usb_state != "none" && !SetUsbConfig("none")) {
338 LOG(ERROR) << "Failed to clear USB config";
339 return INSTALL_ERROR;
340 }
Tao Bao682c34b2015-04-07 17:16:35 -0700341
Tao Baoc6dc3252019-04-16 14:22:25 -0700342 if (!rescue_mode) {
343 ui->Print(
344 "\n\nNow send the package you want to apply\n"
345 "to the device with \"adb sideload <filename>\"...\n");
346 } else {
347 ui->Print("\n\nWaiting for rescue commands...\n");
348 }
Doug Zongker9270a202012-01-09 15:16:13 -0800349
xunchang34690ce2019-04-05 16:16:07 -0700350 int install_result = INSTALL_ERROR;
Tao Bao10f441a2019-04-19 15:22:15 -0700351 std::map<MinadbdCommand, CommandFunction> command_map{
352 { MinadbdCommand::kInstall, std::bind(&AdbInstallPackageHandler, ui, &install_result) },
353 { MinadbdCommand::kRebootAndroid, std::bind(&AdbRebootHandler, MinadbdCommand::kRebootAndroid,
354 &install_result, reboot_action) },
355 { MinadbdCommand::kRebootBootloader,
356 std::bind(&AdbRebootHandler, MinadbdCommand::kRebootBootloader, &install_result,
357 reboot_action) },
358 { MinadbdCommand::kRebootFastboot, std::bind(&AdbRebootHandler, MinadbdCommand::kRebootFastboot,
359 &install_result, reboot_action) },
360 { MinadbdCommand::kRebootRecovery, std::bind(&AdbRebootHandler, MinadbdCommand::kRebootRecovery,
361 &install_result, reboot_action) },
362 { MinadbdCommand::kRebootRescue,
363 std::bind(&AdbRebootHandler, MinadbdCommand::kRebootRescue, &install_result, reboot_action) },
xunchang34690ce2019-04-05 16:16:07 -0700364 };
Doug Zongker9270a202012-01-09 15:16:13 -0800365
Tao Baod9cb0142019-04-23 11:46:25 -0700366 CreateMinadbdServiceAndExecuteCommands(ui, command_map, rescue_mode);
Doug Zongker075ad802014-06-26 15:35:51 -0700367
Hridya Valsarajue4ef4532018-08-31 11:57:51 -0700368 // Clean up before switching to the older state, for example setting the state
369 // to none sets sys/class/android_usb/android0/enable to 0.
370 if (!SetUsbConfig("none")) {
371 LOG(ERROR) << "Failed to clear USB config";
372 }
373
374 if (usb_state != "none") {
375 if (!SetUsbConfig(usb_state)) {
376 LOG(ERROR) << "Failed to set USB config to " << usb_state;
377 }
378 }
Doug Zongker9270a202012-01-09 15:16:13 -0800379
xunchang34690ce2019-04-05 16:16:07 -0700380 return install_result;
Doug Zongker9270a202012-01-09 15:16:13 -0800381}