blob: 5486b7e3f92e34e5a3fea096e33f40ae8535c81f [file] [log] [blame]
bigbiff1f9e4842020-10-31 11:33:15 -04001/*
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
17#include "twinstall/adb_install.h"
18
19#include <errno.h>
20#include <fcntl.h>
21#include <signal.h>
22#include <stdlib.h>
23#include <string.h>
24#include <sys/epoll.h>
25#include <sys/socket.h>
26#include <sys/stat.h>
27#include <sys/types.h>
28#include <sys/wait.h>
29#include <unistd.h>
30
31#include <atomic>
32#include <functional>
33#include <map>
34#include <utility>
35#include <vector>
36
37#include <android-base/file.h>
38#include <android-base/logging.h>
39#include <android-base/memory.h>
40#include <android-base/properties.h>
41#include <android-base/strings.h>
42#include <android-base/unique_fd.h>
43
44#include "fuse_sideload.h"
45#include "twinstall/install.h"
AndroiableDroid136acfe2020-12-29 19:05:55 +053046#include "twinstall.h"
bigbiff1f9e4842020-10-31 11:33:15 -040047#include "twinstall/wipe_data.h"
bigbiff673c7ae2020-12-02 19:44:56 -050048#include "minadbd/types.h"
bigbiff1f9e4842020-10-31 11:33:15 -040049#include "otautil/sysutil.h"
50#include "recovery_ui/device.h"
51#include "recovery_ui/ui.h"
52
53// A CommandFunction returns a pair of (result, should_continue), which indicates the command
54// execution result and whether it should proceed to the next iteration. The execution result will
55// always be sent to the minadbd side.
56using CommandFunction = std::function<std::pair<bool, bool>()>;
57
58pid_t child;
59
60pid_t GetMiniAdbdPid() {
61 return child;
62}
63
64static bool SetUsbConfig(const std::string& state) {
65 android::base::SetProperty("sys.usb.config", state);
66 return android::base::WaitForProperty("sys.usb.state", state);
67}
68
69// Parses the minadbd command in |message|; returns MinadbdCommand::kError upon errors.
70static MinadbdCommand ParseMinadbdCommand(const std::string& message) {
71 if (!android::base::StartsWith(message, kMinadbdCommandPrefix)) {
72 LOG(ERROR) << "Failed to parse command in message " << message;
73 return MinadbdCommand::kError;
74 }
75
76 auto cmd_code_string = message.substr(strlen(kMinadbdCommandPrefix));
77 auto cmd_code = android::base::get_unaligned<uint32_t>(cmd_code_string.c_str());
78 if (cmd_code >= static_cast<uint32_t>(MinadbdCommand::kError)) {
79 LOG(ERROR) << "Unsupported command code: " << cmd_code;
80 return MinadbdCommand::kError;
81 }
82
83 return static_cast<MinadbdCommand>(cmd_code);
84}
85
86static bool WriteStatusToFd(MinadbdCommandStatus status, int fd) {
87 char message[kMinadbdMessageSize];
88 memcpy(message, kMinadbdStatusPrefix, strlen(kMinadbdStatusPrefix));
89 android::base::put_unaligned(message + strlen(kMinadbdStatusPrefix), status);
90
91 if (!android::base::WriteFully(fd, message, kMinadbdMessageSize)) {
92 PLOG(ERROR) << "Failed to write message " << message;
93 return false;
94 }
95 return true;
96}
97
98// Installs the package from FUSE. Returns the installation result and whether it should continue
99// waiting for new commands.
100static auto AdbInstallPackageHandler(int* result) {
101 // How long (in seconds) we wait for the package path to be ready. It doesn't need to be too long
102 // because the minadbd service has already issued an install command. FUSE_SIDELOAD_HOST_PATHNAME
103 // will start to exist once the host connects and starts serving a package. Poll for its
104 // appearance. (Note that inotify doesn't work with FUSE.)
105 constexpr int ADB_INSTALL_TIMEOUT = 15;
106 bool should_continue = true;
107 *result = INSTALL_ERROR;
108 for (int i = 0; i < ADB_INSTALL_TIMEOUT; ++i) {
109 PLOG(ERROR) << "i: " << i;
110 struct stat st;
111 if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &st) != 0) {
112 if (errno == ENOENT && i < ADB_INSTALL_TIMEOUT - 1) {
113 sleep(1);
114 continue;
115 } else {
116 should_continue = false;
117 break;
118 }
119 }
AndroiableDroid136acfe2020-12-29 19:05:55 +0530120 int dummy;
121 *result = TWinstall_zip(FUSE_SIDELOAD_HOST_PATHNAME, &dummy);
bigbiff1f9e4842020-10-31 11:33:15 -0400122 break;
123 }
124
125 // Calling stat() on this magic filename signals the FUSE to exit.
126 struct stat st;
127 stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &st);
128 return std::make_pair(*result == INSTALL_SUCCESS, should_continue);
129}
130
131static auto AdbRebootHandler(MinadbdCommand command, int* result,
132 Device::BuiltinAction* reboot_action) {
133 // Use Device::REBOOT_{FASTBOOT,RECOVERY,RESCUE}, instead of the ones with ENTER_. This allows
134 // rebooting back into fastboot/recovery/rescue mode through bootloader, which may use a newly
135 // installed bootloader/recovery image.
136 switch (command) {
137 case MinadbdCommand::kRebootBootloader:
138 *reboot_action = Device::REBOOT_BOOTLOADER;
139 break;
140 case MinadbdCommand::kRebootFastboot:
141 *reboot_action = Device::REBOOT_FASTBOOT;
142 break;
143 case MinadbdCommand::kRebootRecovery:
144 *reboot_action = Device::REBOOT_RECOVERY;
145 break;
146 case MinadbdCommand::kRebootRescue:
147 *reboot_action = Device::REBOOT_RESCUE;
148 break;
149 case MinadbdCommand::kRebootAndroid:
150 default:
151 *reboot_action = Device::REBOOT;
152 break;
153 }
154 *result = INSTALL_REBOOT;
155 return std::make_pair(true, false);
156}
157
158// Parses and executes the command from minadbd. Returns whether the caller should keep waiting for
159// next command.
160static bool HandleMessageFromMinadbd(int socket_fd,
161 const std::map<MinadbdCommand, CommandFunction>& command_map) {
162 char buffer[kMinadbdMessageSize];
163 if (!android::base::ReadFully(socket_fd, buffer, kMinadbdMessageSize)) {
164 PLOG(ERROR) << "Failed to read message from minadbd";
165 return false;
166 }
167
168 std::string message(buffer, buffer + kMinadbdMessageSize);
169 auto command_type = ParseMinadbdCommand(message);
170 if (command_type == MinadbdCommand::kError) {
171 return false;
172 }
173 if (command_map.find(command_type) == command_map.end()) {
174 LOG(ERROR) << "Unsupported command: "
175 << android::base::get_unaligned<unsigned int>(
176 message.substr(strlen(kMinadbdCommandPrefix)).c_str());
177 return false;
178 }
179
180 // We have received a valid command, execute the corresponding function.
181 const auto& command_func = command_map.at(command_type);
182 const auto [result, should_continue] = command_func();
183 LOG(INFO) << "Command " << static_cast<uint32_t>(command_type) << " finished with " << result;
184 if (!WriteStatusToFd(result ? MinadbdCommandStatus::kSuccess : MinadbdCommandStatus::kFailure,
185 socket_fd)) {
186 return false;
187 }
188 return should_continue;
189}
190
191// TODO(xunchang) add a wrapper function and kill the minadbd service there.
192static void ListenAndExecuteMinadbdCommands(
193 pid_t minadbd_pid, android::base::unique_fd&& socket_fd,
194 const std::map<MinadbdCommand, CommandFunction>& command_map) {
195 android::base::unique_fd epoll_fd(epoll_create1(O_CLOEXEC));
196 if (epoll_fd == -1) {
197 PLOG(ERROR) << "Failed to create epoll";
198 kill(minadbd_pid, SIGKILL);
199 return;
200 }
201
202 constexpr int EPOLL_MAX_EVENTS = 10;
203 struct epoll_event ev = {};
204 ev.events = EPOLLIN | EPOLLHUP;
205 ev.data.fd = socket_fd.get();
206 struct epoll_event events[EPOLL_MAX_EVENTS];
207 if (epoll_ctl(epoll_fd.get(), EPOLL_CTL_ADD, socket_fd.get(), &ev) == -1) {
208 PLOG(ERROR) << "Failed to add socket fd to epoll";
209 kill(minadbd_pid, SIGKILL);
210 return;
211 }
212
213 // Set the timeout to be 300s when waiting for minadbd commands.
214 constexpr int TIMEOUT_MILLIS = 300 * 1000;
215 while (true) {
216 // Poll for the status change of the socket_fd, and handle the message if the fd is ready to
217 // read.
218 int event_count =
219 TEMP_FAILURE_RETRY(epoll_wait(epoll_fd.get(), events, EPOLL_MAX_EVENTS, TIMEOUT_MILLIS));
220 if (event_count == -1) {
221 PLOG(ERROR) << "Failed to wait for epoll events";
222 kill(minadbd_pid, SIGKILL);
223 return;
224 }
225 if (event_count == 0) {
226 LOG(ERROR) << "Timeout waiting for messages from minadbd";
227 kill(minadbd_pid, SIGKILL);
228 return;
229 }
230
231 for (int n = 0; n < event_count; n++) {
232 if (events[n].events & EPOLLHUP) {
233 LOG(INFO) << "Socket has been closed";
234 kill(minadbd_pid, SIGKILL);
235 return;
236 }
237 if (!HandleMessageFromMinadbd(socket_fd.get(), command_map)) {
238 kill(minadbd_pid, SIGKILL);
239 return;
240 }
241 }
242 }
243}
244
245// Recovery starts minadbd service as a child process, and spawns another thread to listen for the
246// message from minadbd through a socket pair. Here is an example to execute one command from adb
247// host.
248// a. recovery b. listener thread c. minadbd service
249//
250// a1. create socket pair
251// a2. fork minadbd service
252// c3. wait for the adb commands
253// from host
254// c4. after receiving host commands:
255// 1) set up pre-condition (i.e.
256// start fuse for adb sideload)
257// 2) issue command through
258// socket.
259// 3) wait for result
260// a5. start listener thread
261// b6. listen for message from
262// minadbd in a loop.
263// b7. After receiving a minadbd
264// command from socket
265// 1) execute the command function
266// 2) send the result back to
267// minadbd
268// ......
269// c8. exit upon receiving the
270// result
271// a9. wait for listener thread
272// to exit.
273//
274// a10. wait for minadbd to
275// exit
276// b11. exit the listening loop
277//
278static void CreateMinadbdServiceAndExecuteCommands(
279 const std::map<MinadbdCommand, CommandFunction>& command_map,
280 bool rescue_mode __unused, std::string install_file __unused) {
281 signal(SIGPIPE, SIG_IGN);
282
283 android::base::unique_fd recovery_socket;
284 android::base::unique_fd minadbd_socket;
285 if (!android::base::Socketpair(AF_UNIX, SOCK_STREAM, 0, &recovery_socket, &minadbd_socket)) {
286 PLOG(ERROR) << "Failed to create socket";
287 return;
288 }
289
290 child = fork();
291 if (child == -1) {
292 PLOG(ERROR) << "Failed to fork child process";
293 return;
294 }
295 if (child == 0) {
296 recovery_socket.reset();
297 std::vector<std::string> minadbd_commands = {
298 "/system/bin/minadbd",
299 "--socket_fd",
300 std::to_string(minadbd_socket.release()),
301 };
302 // if (rescue_mode) {
303 // minadbd_commands.push_back("--rescue");
304 // }
305 auto exec_args = StringVectorToNullTerminatedArray(minadbd_commands);
306 execv(exec_args[0], exec_args.data());
307 _exit(EXIT_FAILURE);
308 }
309
310 minadbd_socket.reset();
311
312 // We need to call SetUsbConfig() after forking minadbd service. Because the function waits for
313 // the usb state to be updated, which depends on sys.usb.ffs.ready=1 set in the adb daemon.
314 if (!SetUsbConfig("sideload")) {
315 LOG(ERROR) << "Failed to set usb config to sideload";
316 return;
317 }
318
319 std::thread listener_thread(ListenAndExecuteMinadbdCommands, child,
320 std::move(recovery_socket), std::ref(command_map));
321 if (listener_thread.joinable()) {
322 listener_thread.join();
323 }
324
325 int status;
326 waitpid(child, &status, 0);
327 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
328 if (WEXITSTATUS(status) == MinadbdErrorCode::kMinadbdAdbVersionError) {
329 LOG(ERROR) << "\nYou need adb 1.0.32 or newer to sideload\nto this device.\n";
330 } else if (!WIFSIGNALED(status)) {
331 LOG(ERROR) << "\n(adbd status " << WEXITSTATUS(status) << ")";
332 }
333 }
334
335 signal(SIGPIPE, SIG_DFL);
336}
337
338 int twrp_sideload(const char* install_file, Device::BuiltinAction* reboot_action) {
339
340 // Save the usb state to restore after the sideload operation.
341 std::string usb_state = android::base::GetProperty("sys.usb.state", "none");
342 // Clean up state and stop adbd.
343 if (usb_state != "none" && !SetUsbConfig("none")) {
344 LOG(ERROR) << "Failed to clear USB config";
345 return INSTALL_ERROR;
346 }
347
348 int install_result = INSTALL_ERROR;
349 std::map<MinadbdCommand, CommandFunction> command_map{
350 { MinadbdCommand::kInstall, std::bind(&AdbInstallPackageHandler, &install_result) },
351 { MinadbdCommand::kRebootAndroid, std::bind(&AdbRebootHandler, MinadbdCommand::kRebootAndroid,
352 &install_result, reboot_action) },
353 { MinadbdCommand::kRebootBootloader,
354 std::bind(&AdbRebootHandler, MinadbdCommand::kRebootBootloader, &install_result,
355 reboot_action) },
356 { MinadbdCommand::kRebootFastboot, std::bind(&AdbRebootHandler, MinadbdCommand::kRebootFastboot,
357 &install_result, reboot_action) },
358 { MinadbdCommand::kRebootRecovery, std::bind(&AdbRebootHandler, MinadbdCommand::kRebootRecovery,
359 &install_result, reboot_action) },
360 { MinadbdCommand::kRebootRescue,
361 std::bind(&AdbRebootHandler, MinadbdCommand::kRebootRescue, &install_result, reboot_action) },
362};
363
364 CreateMinadbdServiceAndExecuteCommands(command_map, false, install_file);
365
366 // Clean up before switching to the older state, for example setting the state
367 // to none sets sys/class/android_usb/android0/enable to 0.
368 if (!SetUsbConfig("none")) {
369 LOG(ERROR) << "Failed to clear USB config";
370 }
371
372 if (usb_state != "none") {
373 if (!SetUsbConfig(usb_state)) {
374 LOG(ERROR) << "Failed to set USB config to " << usb_state;
375 }
376 }
377
378 return install_result;
379}