1 /*
2 * Copyright (C) 2018 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 "adb.h"
18 #include "adb_io.h"
19 #include "adb_unique_fd.h"
20 #include "adb_utils.h"
21 #include "shell_service.h"
22
23 #include <android-base/cmsg.h>
24
25 namespace {
26
27 struct AbbProcess {
28 unique_fd sendCommand(std::string_view command);
29
30 private:
31 static unique_fd startAbbProcess(unique_fd* error_fd);
32
33 static constexpr auto kRetries = 2;
34 static constexpr auto kErrorProtocol = SubprocessProtocol::kShell;
35
36 std::mutex locker_;
37 unique_fd socket_fd_;
38 };
39
sendCommand(std::string_view command)40 unique_fd AbbProcess::sendCommand(std::string_view command) {
41 std::unique_lock lock{locker_};
42
43 for (int i = 0; i < kRetries; ++i) {
44 unique_fd error_fd;
45 if (socket_fd_ == -1) {
46 socket_fd_ = startAbbProcess(&error_fd);
47 }
48 if (socket_fd_ == -1) {
49 LOG(ERROR) << "failed to start abb process";
50 return error_fd;
51 }
52
53 if (!SendProtocolString(socket_fd_, command)) {
54 PLOG(ERROR) << "failed to send command to abb";
55 socket_fd_.reset();
56 continue;
57 }
58
59 unique_fd fd;
60 char buf;
61 if (android::base::ReceiveFileDescriptors(socket_fd_, &buf, 1, &fd) != 1) {
62 PLOG(ERROR) << "failed to receive FD from abb";
63 socket_fd_.reset();
64 continue;
65 }
66
67 return fd;
68 }
69
70 LOG(ERROR) << "abb is unavailable";
71 socket_fd_.reset();
72 return ReportError(kErrorProtocol, "abb is unavailable");
73 }
74
startAbbProcess(unique_fd * error_fd)75 unique_fd AbbProcess::startAbbProcess(unique_fd* error_fd) {
76 constexpr auto abb_process_type = SubprocessType::kRaw;
77 constexpr auto abb_protocol = SubprocessProtocol::kNone;
78 constexpr auto make_pty_raw = false;
79 return StartSubprocess("abb", "dumb", abb_process_type, abb_protocol, make_pty_raw,
80 kErrorProtocol, error_fd);
81 }
82
83 static auto& abbp = *new AbbProcess;
84
85 } // namespace
86
execute_abb_command(std::string_view command)87 unique_fd execute_abb_command(std::string_view command) {
88 return abbp.sendCommand(command);
89 }
90