• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 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 "minadbd_services.h"
18 
19 #include <errno.h>
20 #include <inttypes.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25 
26 #include <chrono>
27 #include <functional>
28 #include <memory>
29 #include <set>
30 #include <string>
31 #include <string_view>
32 #include <thread>
33 
34 #include <android-base/file.h>
35 #include <android-base/logging.h>
36 #include <android-base/memory.h>
37 #include <android-base/parseint.h>
38 #include <android-base/properties.h>
39 #include <android-base/stringprintf.h>
40 #include <android-base/strings.h>
41 
42 #include "adb.h"
43 #include "adb_unique_fd.h"
44 #include "adb_utils.h"
45 #include "fuse_adb_provider.h"
46 #include "fuse_sideload.h"
47 #include "minadbd/types.h"
48 #include "recovery_utils/battery_utils.h"
49 #include "services.h"
50 #include "sysdeps.h"
51 
52 static int minadbd_socket = -1;
53 static bool rescue_mode = false;
54 static std::string sideload_mount_point = FUSE_SIDELOAD_HOST_MOUNTPOINT;
55 
SetMinadbdSocketFd(int socket_fd)56 void SetMinadbdSocketFd(int socket_fd) {
57   minadbd_socket = socket_fd;
58 }
59 
SetMinadbdRescueMode(bool rescue)60 void SetMinadbdRescueMode(bool rescue) {
61   rescue_mode = rescue;
62 }
63 
SetSideloadMountPoint(const std::string & path)64 void SetSideloadMountPoint(const std::string& path) {
65   sideload_mount_point = path;
66 }
67 
WriteCommandToFd(MinadbdCommand cmd,int fd)68 static bool WriteCommandToFd(MinadbdCommand cmd, int fd) {
69   char message[kMinadbdMessageSize];
70   memcpy(message, kMinadbdCommandPrefix, strlen(kMinadbdStatusPrefix));
71   android::base::put_unaligned(message + strlen(kMinadbdStatusPrefix), cmd);
72 
73   if (!android::base::WriteFully(fd, message, kMinadbdMessageSize)) {
74     PLOG(ERROR) << "Failed to write message " << message;
75     return false;
76   }
77   return true;
78 }
79 
80 // Blocks and reads the command status from |fd|. Returns false if the received message has a
81 // format error.
WaitForCommandStatus(int fd,MinadbdCommandStatus * status)82 static bool WaitForCommandStatus(int fd, MinadbdCommandStatus* status) {
83   char buffer[kMinadbdMessageSize];
84   if (!android::base::ReadFully(fd, buffer, kMinadbdMessageSize)) {
85     PLOG(ERROR) << "Failed to response status from socket";
86     exit(kMinadbdSocketIOError);
87   }
88 
89   std::string message(buffer, buffer + kMinadbdMessageSize);
90   if (!android::base::StartsWith(message, kMinadbdStatusPrefix)) {
91     LOG(ERROR) << "Failed to parse status in " << message;
92     return false;
93   }
94 
95   *status = android::base::get_unaligned<MinadbdCommandStatus>(
96       message.substr(strlen(kMinadbdStatusPrefix)).c_str());
97   return true;
98 }
99 
RunAdbFuseSideload(int sfd,const std::string & args,MinadbdCommandStatus * status)100 static MinadbdErrorCode RunAdbFuseSideload(int sfd, const std::string& args,
101                                            MinadbdCommandStatus* status) {
102   auto pieces = android::base::Split(args, ":");
103   int64_t file_size;
104   int block_size;
105   if (pieces.size() != 2 || !android::base::ParseInt(pieces[0], &file_size) || file_size <= 0 ||
106       !android::base::ParseInt(pieces[1], &block_size) || block_size <= 0) {
107     LOG(ERROR) << "bad sideload-host arguments: " << args;
108     return kMinadbdHostCommandArgumentError;
109   }
110 
111   LOG(INFO) << "sideload-host file size " << file_size << ", block size " << block_size;
112 
113   if (!WriteCommandToFd(MinadbdCommand::kInstall, minadbd_socket)) {
114     return kMinadbdSocketIOError;
115   }
116 
117   auto adb_data_reader = std::make_unique<FuseAdbDataProvider>(sfd, file_size, block_size);
118   if (int result = run_fuse_sideload(std::move(adb_data_reader), sideload_mount_point.c_str());
119       result != 0) {
120     LOG(ERROR) << "Failed to start fuse";
121     return kMinadbdFuseStartError;
122   }
123 
124   if (!WaitForCommandStatus(minadbd_socket, status)) {
125     return kMinadbdMessageFormatError;
126   }
127 
128   // Signal host-side adb to stop. For sideload mode, we always send kMinadbdServicesExitSuccess
129   // (i.e. "DONEDONE") regardless of the install result. For rescue mode, we send failure message on
130   // install error.
131   if (!rescue_mode || *status == MinadbdCommandStatus::kSuccess) {
132     if (!android::base::WriteFully(sfd, kMinadbdServicesExitSuccess,
133                                    strlen(kMinadbdServicesExitSuccess))) {
134       return kMinadbdHostSocketIOError;
135     }
136   } else {
137     if (!android::base::WriteFully(sfd, kMinadbdServicesExitFailure,
138                                    strlen(kMinadbdServicesExitFailure))) {
139       return kMinadbdHostSocketIOError;
140     }
141   }
142 
143   return kMinadbdSuccess;
144 }
145 
WaitForSocketClose(int fd,std::chrono::milliseconds timeout)146 static bool WaitForSocketClose(int fd, std::chrono::milliseconds timeout) {
147   const auto begin = std::chrono::steady_clock::now();
148   const auto end = begin + timeout;
149   while (std::chrono::steady_clock::now() < end) {
150     // We don't care about reading the socket, we just want to wait until
151     // socket closes. In this case .events = 0 will tell the kernel to wait
152     // for close events.
153     struct pollfd pfd = { .fd = fd, .events = 0 };
154     auto timeout_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
155                           end - std::chrono::steady_clock::now())
156                           .count();
157     int rc = TEMP_FAILURE_RETRY(adb_poll(&pfd, 1, timeout_ms));
158     if (rc == 1) {
159       LOG(INFO) << "revents: " << pfd.revents;
160       if (pfd.revents & (POLLHUP | POLLRDHUP)) {
161         return true;
162       }
163     } else {
164       PLOG(ERROR) << "poll() failed";
165       // poll failed, almost definitely due to timeout
166       // If not, you're screwed anyway, because it probably means the kernel ran
167       // out of memory.
168       return false;
169     }
170   }
171   return false;
172 }
173 
174 // Sideload service always exits after serving an install command.
SideloadHostService(unique_fd sfd,const std::string & args)175 static void SideloadHostService(unique_fd sfd, const std::string& args) {
176   using namespace std::chrono_literals;
177   MinadbdCommandStatus status;
178   auto error = RunAdbFuseSideload(sfd.get(), args, &status);
179   // No need to wait if the socket is already closed, meaning the other end
180   // already exited for some reason.
181   if (error != kMinadbdHostSocketIOError) {
182     // We sleep for a little bit just to wait for the host to receive last
183     // "DONEDONE" message. However minadbd process is likely to get terminated
184     // early due to exit_on_close
185     WaitForSocketClose(sfd, 3000ms);
186   }
187   exit(error);
188 }
189 
190 // Rescue service waits for the next command after an install command.
RescueInstallHostService(unique_fd sfd,const std::string & args)191 static void RescueInstallHostService(unique_fd sfd, const std::string& args) {
192   MinadbdCommandStatus status;
193   if (auto result = RunAdbFuseSideload(sfd.get(), args, &status); result != kMinadbdSuccess) {
194     exit(result);
195   }
196 }
197 
198 // Answers the query on a given property |prop|, by writing the result to the given |sfd|. The
199 // result will be newline-terminated, so nonexistent or nonallowed query will be answered with "\n".
200 // If given an empty string, dumps all the supported properties (analogous to `adb shell getprop`)
201 // in lines, e.g. "[prop]: [value]".
RescueGetpropHostService(unique_fd sfd,const std::string & prop)202 static void RescueGetpropHostService(unique_fd sfd, const std::string& prop) {
203   constexpr const char* kRescueBatteryLevelProp = "rescue.battery_level";
204   static const std::set<std::string> kGetpropAllowedProps = {
205     // clang-format off
206     kRescueBatteryLevelProp,
207     "ro.build.date.utc",
208     "ro.build.fingerprint",
209     "ro.build.flavor",
210     "ro.build.id",
211     "ro.build.product",
212     "ro.build.tags",
213     "ro.build.version.incremental",
214     "ro.product.device",
215     "ro.product.vendor.device",
216     // clang-format on
217   };
218 
219   auto query_prop = [](const std::string& key) {
220     if (key == kRescueBatteryLevelProp) {
221       auto battery_info = GetBatteryInfo();
222       return std::to_string(battery_info.capacity);
223     }
224     return android::base::GetProperty(key, "");
225   };
226 
227   std::string result;
228   if (prop.empty()) {
229     for (const auto& key : kGetpropAllowedProps) {
230       auto value = query_prop(key);
231       if (value.empty()) {
232         continue;
233       }
234       result += "[" + key + "]: [" + value + "]\n";
235     }
236   } else if (kGetpropAllowedProps.find(prop) != kGetpropAllowedProps.end()) {
237     result = query_prop(prop) + "\n";
238   }
239   if (result.empty()) {
240     result = "\n";
241   }
242   if (!android::base::WriteFully(sfd, result.data(), result.size())) {
243     exit(kMinadbdHostSocketIOError);
244   }
245 
246   // Send heartbeat signal to keep the rescue service alive.
247   if (!WriteCommandToFd(MinadbdCommand::kNoOp, minadbd_socket)) {
248     exit(kMinadbdSocketIOError);
249   }
250   if (MinadbdCommandStatus status; !WaitForCommandStatus(minadbd_socket, &status)) {
251     exit(kMinadbdMessageFormatError);
252   }
253 }
254 
255 // Reboots into the given target. We don't reboot directly from minadbd, but going through recovery
256 // instead. This allows recovery to finish all the pending works (clear BCB, save logs etc) before
257 // the reboot.
RebootHostService(unique_fd,const std::string & target)258 static void RebootHostService(unique_fd /* sfd */, const std::string& target) {
259   MinadbdCommand command;
260   if (target == "bootloader") {
261     command = MinadbdCommand::kRebootBootloader;
262   } else if (target == "rescue") {
263     command = MinadbdCommand::kRebootRescue;
264   } else if (target == "recovery") {
265     command = MinadbdCommand::kRebootRecovery;
266   } else if (target == "fastboot") {
267     command = MinadbdCommand::kRebootFastboot;
268   } else {
269     command = MinadbdCommand::kRebootAndroid;
270   }
271   if (!WriteCommandToFd(command, minadbd_socket)) {
272     exit(kMinadbdSocketIOError);
273   }
274   MinadbdCommandStatus status;
275   if (!WaitForCommandStatus(minadbd_socket, &status)) {
276     exit(kMinadbdMessageFormatError);
277   }
278 }
279 
WipeDeviceService(unique_fd fd,const std::string & args)280 static void WipeDeviceService(unique_fd fd, const std::string& args) {
281   auto pieces = android::base::Split(args, ":");
282   if (pieces.size() != 2 || pieces[0] != "userdata") {
283     LOG(ERROR) << "Failed to parse wipe device command arguments " << args;
284     exit(kMinadbdHostCommandArgumentError);
285   }
286 
287   size_t message_size;
288   if (!android::base::ParseUint(pieces[1], &message_size) ||
289       message_size < strlen(kMinadbdServicesExitSuccess)) {
290     LOG(ERROR) << "Failed to parse wipe device message size in " << args;
291     exit(kMinadbdHostCommandArgumentError);
292   }
293 
294   WriteCommandToFd(MinadbdCommand::kWipeData, minadbd_socket);
295   MinadbdCommandStatus status;
296   if (!WaitForCommandStatus(minadbd_socket, &status)) {
297     exit(kMinadbdMessageFormatError);
298   }
299 
300   std::string response = (status == MinadbdCommandStatus::kSuccess) ? kMinadbdServicesExitSuccess
301                                                                     : kMinadbdServicesExitFailure;
302   response += std::string(message_size - response.size(), '\0');
303   if (!android::base::WriteFully(fd, response.c_str(), response.size())) {
304     exit(kMinadbdHostSocketIOError);
305   }
306 }
307 
daemon_service_to_socket(std::string_view)308 asocket* daemon_service_to_socket(std::string_view) {
309   return nullptr;
310 }
311 
daemon_service_to_fd(std::string_view name,atransport *)312 unique_fd daemon_service_to_fd(std::string_view name, atransport* /* transport */) {
313   // Common services that are supported both in sideload and rescue modes.
314   if (android::base::ConsumePrefix(&name, "reboot:")) {
315     // "reboot:<target>", where target must be one of the following.
316     std::string args(name);
317     if (args.empty() || args == "bootloader" || args == "rescue" || args == "recovery" ||
318         args == "fastboot") {
319       return create_service_thread("reboot",
320                                    std::bind(RebootHostService, std::placeholders::_1, args));
321     }
322     return unique_fd{};
323   }
324 
325   // Rescue-specific services.
326   if (rescue_mode) {
327     if (android::base::ConsumePrefix(&name, "rescue-install:")) {
328       // rescue-install:<file-size>:<block-size>
329       std::string args(name);
330       return create_service_thread(
331           "rescue-install", std::bind(RescueInstallHostService, std::placeholders::_1, args));
332     } else if (android::base::ConsumePrefix(&name, "rescue-getprop:")) {
333       // rescue-getprop:<prop>
334       std::string args(name);
335       return create_service_thread(
336           "rescue-getprop", std::bind(RescueGetpropHostService, std::placeholders::_1, args));
337     } else if (android::base::ConsumePrefix(&name, "rescue-wipe:")) {
338       // rescue-wipe:target:<message-size>
339       std::string args(name);
340       return create_service_thread("rescue-wipe",
341                                    std::bind(WipeDeviceService, std::placeholders::_1, args));
342     }
343 
344     return unique_fd{};
345   }
346 
347   // Sideload-specific services.
348   if (name.starts_with("sideload:")) {
349     // This exit status causes recovery to print a special error message saying to use a newer adb
350     // (that supports sideload-host).
351     exit(kMinadbdAdbVersionError);
352   } else if (android::base::ConsumePrefix(&name, "sideload-host:")) {
353     // sideload-host:<file-size>:<block-size>
354     std::string args(name);
355     return create_service_thread("sideload-host",
356                                  std::bind(SideloadHostService, std::placeholders::_1, args));
357   }
358   return unique_fd{};
359 }
360