blob: 548b6e5b9fd7b09f6529f8f655799dcad8b258e8 [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>
34
35#include <android-base/file.h>
Tao Bao0167d4c2017-05-11 14:44:15 -070036#include <android-base/logging.h>
xunchang34690ce2019-04-05 16:16:07 -070037#include <android-base/memory.h>
Elliott Hughescb220402016-09-23 15:30:55 -070038#include <android-base/properties.h>
xunchang34690ce2019-04-05 16:16:07 -070039#include <android-base/strings.h>
40#include <android-base/unique_fd.h>
Elliott Hughescb220402016-09-23 15:30:55 -070041
Tao Bao0150d012017-05-01 11:31:28 -070042#include "fuse_sideload.h"
xunchang24788852019-03-22 16:08:52 -070043#include "install/install.h"
xunchang34690ce2019-04-05 16:16:07 -070044#include "minadbd_types.h"
Tianjie Xu8f397302018-08-20 13:40:47 -070045#include "recovery_ui/ui.h"
Tao Bao0150d012017-05-01 11:31:28 -070046
xunchang34690ce2019-04-05 16:16:07 -070047using CommandFunction = std::function<bool()>;
48
xunchang24788852019-03-22 16:08:52 -070049static bool SetUsbConfig(const std::string& state) {
50 android::base::SetProperty("sys.usb.config", state);
51 return android::base::WaitForProperty("sys.usb.state", state);
52}
53
xunchang34690ce2019-04-05 16:16:07 -070054// Parses the minadbd command in |message|; returns MinadbdCommands::kError upon errors.
55static MinadbdCommands ParseMinadbdCommands(const std::string& message) {
56 if (!android::base::StartsWith(message, kMinadbdCommandPrefix)) {
57 LOG(ERROR) << "Failed to parse command in message " << message;
58 return MinadbdCommands::kError;
59 }
60
61 auto cmd_code_string = message.substr(strlen(kMinadbdCommandPrefix));
62 auto cmd_code = android::base::get_unaligned<uint32_t>(cmd_code_string.c_str());
63 if (cmd_code >= static_cast<uint32_t>(MinadbdCommands::kError)) {
64 LOG(ERROR) << "Unsupported command code: " << cmd_code;
65 return MinadbdCommands::kError;
66 }
67
68 return static_cast<MinadbdCommands>(cmd_code);
69}
70
71static bool WriteStatusToFd(MinadbdCommandStatus status, int fd) {
72 char message[kMinadbdMessageSize];
73 memcpy(message, kMinadbdStatusPrefix, strlen(kMinadbdStatusPrefix));
74 android::base::put_unaligned(message + strlen(kMinadbdStatusPrefix), status);
75
76 if (!android::base::WriteFully(fd, message, kMinadbdMessageSize)) {
77 PLOG(ERROR) << "Failed to write message " << message;
78 return false;
79 }
80 return true;
81}
82
83// Installs the package from FUSE. Returns true if the installation succeeds, and false otherwise.
xunchang316e9712019-04-12 16:22:15 -070084static bool AdbInstallPackageHandler(RecoveryUI* ui, int* result) {
xunchang34690ce2019-04-05 16:16:07 -070085 // How long (in seconds) we wait for the package path to be ready. It doesn't need to be too long
86 // because the minadbd service has already issued an install command. FUSE_SIDELOAD_HOST_PATHNAME
87 // will start to exist once the host connects and starts serving a package. Poll for its
88 // appearance. (Note that inotify doesn't work with FUSE.)
89 constexpr int ADB_INSTALL_TIMEOUT = 15;
90 *result = INSTALL_ERROR;
91 for (int i = 0; i < ADB_INSTALL_TIMEOUT; ++i) {
92 struct stat st;
93 if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &st) != 0) {
94 if (errno == ENOENT && i < ADB_INSTALL_TIMEOUT - 1) {
95 sleep(1);
96 continue;
97 } else {
98 ui->Print("\nTimed out waiting for fuse to be ready.\n\n");
99 break;
100 }
101 }
xunchang316e9712019-04-12 16:22:15 -0700102 *result = install_package(FUSE_SIDELOAD_HOST_PATHNAME, false, false, 0, ui);
xunchang34690ce2019-04-05 16:16:07 -0700103 break;
104 }
105
106 // Calling stat() on this magic filename signals the FUSE to exit.
107 struct stat st;
108 stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &st);
109 return *result == INSTALL_SUCCESS;
110}
111
112// Parses and executes the command from minadbd. Returns false if we enter an invalid state so that
113// the caller can kill the minadbd service properly.
114static bool HandleMessageFromMinadbd(
115 int socket_fd, const std::map<MinadbdCommands, CommandFunction>& command_map) {
116 char buffer[kMinadbdMessageSize];
117 if (!android::base::ReadFully(socket_fd, buffer, kMinadbdMessageSize)) {
118 PLOG(ERROR) << "Failed to read message from minadbd";
119 return false;
120 }
121
122 std::string message(buffer, buffer + kMinadbdMessageSize);
123 auto command_type = ParseMinadbdCommands(message);
124 if (command_type == MinadbdCommands::kError) {
125 return false;
126 }
127 if (command_map.find(command_type) == command_map.end()) {
128 LOG(ERROR) << "Unsupported command: "
129 << android::base::get_unaligned<unsigned int>(
130 message.substr(strlen(kMinadbdCommandPrefix)).c_str());
131 return false;
132 }
133
134 // We have received a valid command, execute the corresponding function.
135 const auto& command_func = command_map.at(command_type);
136 if (!command_func()) {
137 LOG(ERROR) << "Failed to execute command " << static_cast<unsigned int>(command_type);
138 return WriteStatusToFd(MinadbdCommandStatus::kFailure, socket_fd);
139 }
140 return WriteStatusToFd(MinadbdCommandStatus::kSuccess, socket_fd);
141}
142
143// TODO(xunchang) add a wrapper function and kill the minadbd service there.
144static void ListenAndExecuteMinadbdCommands(
145 pid_t minadbd_pid, android::base::unique_fd&& socket_fd,
146 const std::map<MinadbdCommands, CommandFunction>& command_map) {
147 android::base::unique_fd epoll_fd(epoll_create1(O_CLOEXEC));
148 if (epoll_fd == -1) {
149 PLOG(ERROR) << "Failed to create epoll";
150 kill(minadbd_pid, SIGKILL);
151 return;
152 }
153
154 constexpr int EPOLL_MAX_EVENTS = 10;
155 struct epoll_event ev = {};
156 ev.events = EPOLLIN | EPOLLHUP;
157 ev.data.fd = socket_fd.get();
158 struct epoll_event events[EPOLL_MAX_EVENTS];
159 if (epoll_ctl(epoll_fd.get(), EPOLL_CTL_ADD, socket_fd.get(), &ev) == -1) {
160 PLOG(ERROR) << "Failed to add socket fd to epoll";
161 kill(minadbd_pid, SIGKILL);
162 return;
163 }
164
165 // Set the timeout to be 300s when waiting for minadbd commands.
166 constexpr int TIMEOUT_MILLIS = 300 * 1000;
167 while (true) {
168 // Poll for the status change of the socket_fd, and handle the message if the fd is ready to
169 // read.
170 int event_count =
171 TEMP_FAILURE_RETRY(epoll_wait(epoll_fd.get(), events, EPOLL_MAX_EVENTS, TIMEOUT_MILLIS));
172 if (event_count == -1) {
173 PLOG(ERROR) << "Failed to wait for epoll events";
174 kill(minadbd_pid, SIGKILL);
175 return;
176 }
177 if (event_count == 0) {
178 LOG(ERROR) << "Timeout waiting for messages from minadbd";
179 kill(minadbd_pid, SIGKILL);
180 return;
181 }
182
183 for (int n = 0; n < event_count; n++) {
184 if (events[n].events & EPOLLHUP) {
185 LOG(INFO) << "Socket has been closed";
186 kill(minadbd_pid, SIGKILL);
187 return;
188 }
189 if (!HandleMessageFromMinadbd(socket_fd.get(), command_map)) {
190 kill(minadbd_pid, SIGKILL);
191 return;
192 }
193 }
194 }
195}
196
197// Recovery starts minadbd service as a child process, and spawns another thread to listen for the
198// message from minadbd through a socket pair. Here is an example to execute one command from adb
199// host.
200// a. recovery b. listener thread c. minadbd service
201//
202// a1. create socket pair
203// a2. fork minadbd service
204// c3. wait for the adb commands
205// from host
206// c4. after receiving host commands:
207// 1) set up pre-condition (i.e.
208// start fuse for adb sideload)
209// 2) issue command through
210// socket.
211// 3) wait for result
212// a5. start listener thread
213// b6. listen for message from
214// minadbd in a loop.
215// b7. After receiving a minadbd
216// command from socket
217// 1) execute the command function
218// 2) send the result back to
219// minadbd
220// ......
221// c8. exit upon receiving the
222// result
223// a9. wait for listener thread
224// to exit.
225//
226// a10. wait for minadbd to
227// exit
228// b11. exit the listening loop
229//
230static void CreateMinadbdServiceAndExecuteCommands(
231 const std::map<MinadbdCommands, CommandFunction>& command_map) {
232 signal(SIGPIPE, SIG_IGN);
233
234 android::base::unique_fd recovery_socket;
235 android::base::unique_fd minadbd_socket;
236 if (!android::base::Socketpair(AF_UNIX, SOCK_STREAM, 0, &recovery_socket, &minadbd_socket)) {
237 PLOG(ERROR) << "Failed to create socket";
238 return;
239 }
240
241 pid_t child = fork();
242 if (child == -1) {
243 PLOG(ERROR) << "Failed to fork child process";
244 return;
245 }
246 if (child == 0) {
247 recovery_socket.reset();
248 execl("/system/bin/minadbd", "minadbd", "--socket_fd",
249 std::to_string(minadbd_socket.release()).c_str(), nullptr);
250
251 _exit(EXIT_FAILURE);
252 }
253
254 minadbd_socket.reset();
255
256 // We need to call SetUsbConfig() after forking minadbd service. Because the function waits for
257 // the usb state to be updated, which depends on sys.usb.ffs.ready=1 set in the adb daemon.
258 if (!SetUsbConfig("sideload")) {
259 LOG(ERROR) << "Failed to set usb config to sideload";
260 return;
261 }
262
263 std::thread listener_thread(ListenAndExecuteMinadbdCommands, child, std::move(recovery_socket),
264 std::ref(command_map));
265
266 if (listener_thread.joinable()) {
267 listener_thread.join();
268 }
269
270 int status;
271 waitpid(child, &status, 0);
272 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
273 if (WEXITSTATUS(status) == MinadbdErrorCode::kMinadbdAdbVersionError) {
274 LOG(ERROR) << "\nYou need adb 1.0.32 or newer to sideload\nto this device.\n";
275 } else if (!WIFSIGNALED(status)) {
276 LOG(ERROR) << "\n(adbd status " << WEXITSTATUS(status) << ")";
277 }
278 }
279
280 signal(SIGPIPE, SIG_DFL);
281}
282
xunchang316e9712019-04-12 16:22:15 -0700283int apply_from_adb(RecoveryUI* ui) {
Hridya Valsarajue4ef4532018-08-31 11:57:51 -0700284 // Save the usb state to restore after the sideload operation.
285 std::string usb_state = android::base::GetProperty("sys.usb.state", "none");
286 // Clean up state and stop adbd.
287 if (usb_state != "none" && !SetUsbConfig("none")) {
288 LOG(ERROR) << "Failed to clear USB config";
289 return INSTALL_ERROR;
290 }
Tao Bao682c34b2015-04-07 17:16:35 -0700291
Tao Bao0150d012017-05-01 11:31:28 -0700292 ui->Print(
293 "\n\nNow send the package you want to apply\n"
294 "to the device with \"adb sideload <filename>\"...\n");
Doug Zongker9270a202012-01-09 15:16:13 -0800295
xunchang34690ce2019-04-05 16:16:07 -0700296 int install_result = INSTALL_ERROR;
297 std::map<MinadbdCommands, CommandFunction> command_map{
xunchang316e9712019-04-12 16:22:15 -0700298 { MinadbdCommands::kInstall, std::bind(&AdbInstallPackageHandler, ui, &install_result) },
xunchang34690ce2019-04-05 16:16:07 -0700299 };
Doug Zongker9270a202012-01-09 15:16:13 -0800300
xunchang34690ce2019-04-05 16:16:07 -0700301 CreateMinadbdServiceAndExecuteCommands(command_map);
Doug Zongker075ad802014-06-26 15:35:51 -0700302
Hridya Valsarajue4ef4532018-08-31 11:57:51 -0700303 // Clean up before switching to the older state, for example setting the state
304 // to none sets sys/class/android_usb/android0/enable to 0.
305 if (!SetUsbConfig("none")) {
306 LOG(ERROR) << "Failed to clear USB config";
307 }
308
309 if (usb_state != "none") {
310 if (!SetUsbConfig(usb_state)) {
311 LOG(ERROR) << "Failed to set USB config to " << usb_state;
312 }
313 }
Doug Zongker9270a202012-01-09 15:16:13 -0800314
xunchang34690ce2019-04-05 16:16:07 -0700315 return install_result;
Doug Zongker9270a202012-01-09 15:16:13 -0800316}