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 #define TRACE_TAG TRANSPORT
18
19 #include "sysdeps.h"
20 #include "transport.h"
21
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/types.h>
27
28 #include <condition_variable>
29 #include <functional>
30 #include <memory>
31 #include <mutex>
32 #include <thread>
33 #include <unordered_map>
34 #include <vector>
35
36 #include <android-base/parsenetaddress.h>
37 #include <android-base/stringprintf.h>
38 #include <android-base/thread_annotations.h>
39 #include <cutils/sockets.h>
40
41 #include "adb.h"
42 #include "adb_io.h"
43 #include "adb_unique_fd.h"
44 #include "adb_utils.h"
45 #include "socket_spec.h"
46 #include "sysdeps/chrono.h"
47
48 // Android Wear has been using port 5601 in all of its documentation/tooling,
49 // but we search for emulators on ports [5554, 5555 + ADB_LOCAL_TRANSPORT_MAX].
50 // Avoid stomping on their port by restricting the active scanning range.
51 // Once emulators self-(re-)register, they'll have to avoid 5601 in their own way.
52 static int adb_local_transport_max_port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT + 16 * 2 - 1;
53
adb_local_transport_max_port_env_override()54 static void adb_local_transport_max_port_env_override() {
55 const char* env_max_s = getenv("ADB_LOCAL_TRANSPORT_MAX_PORT");
56 if (env_max_s != nullptr) {
57 size_t env_max;
58 if (ParseUint(&env_max, env_max_s, nullptr) && env_max < 65536) {
59 // < DEFAULT_ADB_LOCAL_TRANSPORT_PORT harmlessly mimics ADB_EMU=0
60 adb_local_transport_max_port = env_max;
61 D("transport: ADB_LOCAL_TRANSPORT_MAX_PORT read as %d", adb_local_transport_max_port);
62 } else {
63 D("transport: ADB_LOCAL_TRANSPORT_MAX_PORT '%s' invalid or >= 65536, so ignored",
64 env_max_s);
65 }
66 }
67 }
68
69 static std::mutex& emulator_transports_lock = *new std::mutex();
70 // We keep a map from emulator port to transport.
71 // TODO: weak_ptr?
72 static std::unordered_map<int, atransport*> emulator_transports
73 [[clang::no_destroy]] GUARDED_BY(emulator_transports_lock);
74
connect_emulator(int port)75 bool connect_emulator(int port) {
76 std::string dummy;
77 return connect_emulator_arbitrary_ports(port - 1, port, &dummy) == 0;
78 }
79
connect_device(const std::string & address,std::string * response)80 void connect_device(const std::string& address, std::string* response) {
81 if (address.empty()) {
82 *response = "empty address";
83 return;
84 }
85
86 D("connection requested to '%s'", address.c_str());
87 unique_fd fd;
88 int port;
89 std::string serial, prefix_addr;
90
91 // If address does not match any socket type, it should default to TCP.
92 if (address.starts_with("vsock:") || address.starts_with("localfilesystem:")) {
93 prefix_addr = address;
94 } else {
95 prefix_addr = "tcp:" + address;
96 }
97
98 socket_spec_connect(&fd, prefix_addr, &port, &serial, response);
99 if (fd.get() == -1) {
100 return;
101 }
102 auto reconnect = [prefix_addr](atransport* t) {
103 std::string response;
104 unique_fd fd;
105 int port;
106 std::string serial;
107 socket_spec_connect(&fd, prefix_addr, &port, &serial, &response);
108 if (fd == -1) {
109 D("reconnect failed: %s", response.c_str());
110 return ReconnectResult::Retry;
111 }
112 // This invokes the part of register_socket_transport() that needs to be
113 // invoked if the atransport* has already been setup. This eventually
114 // calls atransport->SetConnection() with a newly created Connection*
115 // that will in turn send the CNXN packet.
116 return init_socket_transport(t, std::move(fd), port, false) >= 0 ? ReconnectResult::Success
117 : ReconnectResult::Retry;
118 };
119
120 int error;
121 if (!register_socket_transport(std::move(fd), serial, port, false, std::move(reconnect), false,
122 &error)) {
123 if (error == EALREADY) {
124 *response = android::base::StringPrintf("already connected to %s", serial.c_str());
125 } else if (error == EPERM) {
126 *response = android::base::StringPrintf("failed to authenticate to %s", serial.c_str());
127 } else {
128 *response = android::base::StringPrintf("failed to connect to %s", serial.c_str());
129 }
130 } else {
131 *response = android::base::StringPrintf("connected to %s", serial.c_str());
132 }
133 }
134
connect_emulator_arbitrary_ports(int console_port,int adb_port,std::string * error)135 int connect_emulator_arbitrary_ports(int console_port, int adb_port, std::string* error) {
136 unique_fd fd;
137
138 if (find_emulator_transport_by_adb_port(adb_port) != nullptr ||
139 find_emulator_transport_by_console_port(console_port) != nullptr) {
140 return -1;
141 }
142
143 const char* host = getenv("ADBHOST");
144 if (host) {
145 fd.reset(network_connect(host, adb_port, SOCK_STREAM, 0, error));
146 }
147
148 if (fd < 0) {
149 fd.reset(network_loopback_client(adb_port, SOCK_STREAM, error));
150 }
151
152 if (fd >= 0) {
153 D("client: connected on remote on fd %d", fd.get());
154 close_on_exec(fd.get());
155 disable_tcp_nagle(fd.get());
156 std::string serial = getEmulatorSerialString(console_port);
157 if (register_socket_transport(
158 std::move(fd), std::move(serial), adb_port, true,
159 [](atransport*) { return ReconnectResult::Abort; }, false)) {
160 return 0;
161 }
162 }
163 return -1;
164 }
165
PollAllLocalPortsForEmulator()166 static void PollAllLocalPortsForEmulator() {
167 // Try to connect to any number of running emulator instances.
168 for (int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT; port <= adb_local_transport_max_port;
169 port += 2) {
170 connect_emulator(port); // Note, uses port and port-1, so '=max_port' is OK.
171 }
172 }
173
174 // Retry the disconnected local port for 60 times, and sleep 1 second between two retries.
175 static constexpr uint32_t LOCAL_PORT_RETRY_COUNT = 60;
176 static constexpr auto LOCAL_PORT_RETRY_INTERVAL = 1s;
177
178 struct RetryPort {
179 int port;
180 uint32_t retry_count;
181 };
182
183 // Retry emulators just kicked.
184 static std::vector<RetryPort>& retry_ports = *new std::vector<RetryPort>;
185 std::mutex& retry_ports_lock = *new std::mutex;
186 std::condition_variable& retry_ports_cond = *new std::condition_variable;
187
client_socket_thread(std::string_view)188 static void client_socket_thread(std::string_view) {
189 adb_thread_setname("emulator_scanner");
190 PollAllLocalPortsForEmulator();
191 while (true) {
192 std::vector<RetryPort> ports;
193 // Collect retry ports.
194 {
195 std::unique_lock<std::mutex> lock(retry_ports_lock);
196 while (retry_ports.empty()) {
197 retry_ports_cond.wait(lock);
198 }
199 retry_ports.swap(ports);
200 }
201 // Sleep here instead of the end of loop, because if we immediately try to reconnect
202 // the emulator just kicked, the adbd on the emulator may not have time to remove the
203 // just kicked transport.
204 std::this_thread::sleep_for(LOCAL_PORT_RETRY_INTERVAL);
205
206 // Try connecting retry ports.
207 std::vector<RetryPort> next_ports;
208 for (auto& port : ports) {
209 VLOG(TRANSPORT) << "retry port " << port.port << ", last retry_count "
210 << port.retry_count;
211 if (connect_emulator(port.port)) {
212 VLOG(TRANSPORT) << "retry port " << port.port << " successfully";
213 continue;
214 }
215 if (--port.retry_count > 0) {
216 next_ports.push_back(port);
217 } else {
218 VLOG(TRANSPORT) << "stop retrying port " << port.port;
219 }
220 }
221
222 // Copy back left retry ports.
223 {
224 std::unique_lock<std::mutex> lock(retry_ports_lock);
225 retry_ports.insert(retry_ports.end(), next_ports.begin(), next_ports.end());
226 }
227 }
228 }
229
init_emulator_scanner(const std::string & addr)230 void init_emulator_scanner(const std::string& addr) {
231 VLOG(TRANSPORT) << "Starting emulator scanner on '" << addr << "'";
232 std::thread(client_socket_thread, addr).detach();
233 adb_local_transport_max_port_env_override();
234 }
235
236 struct EmulatorConnection : public FdConnection {
EmulatorConnectionEmulatorConnection237 EmulatorConnection(unique_fd fd, int local_port)
238 : FdConnection(std::move(fd)), local_port_(local_port) {}
239
~EmulatorConnectionEmulatorConnection240 ~EmulatorConnection() {
241 VLOG(TRANSPORT) << "remote_close, local_port = " << local_port_;
242 std::unique_lock<std::mutex> lock(retry_ports_lock);
243 RetryPort port;
244 port.port = local_port_;
245 port.retry_count = LOCAL_PORT_RETRY_COUNT;
246 retry_ports.push_back(port);
247 retry_ports_cond.notify_one();
248 }
249
CloseEmulatorConnection250 void Close() override {
251 std::lock_guard<std::mutex> lock(emulator_transports_lock);
252 emulator_transports.erase(local_port_);
253 FdConnection::Close();
254 }
255
256 int local_port_;
257 };
258
259 /* Only call this function if you already hold emulator_transports_lock. */
find_emulator_transport_by_adb_port_locked(int adb_port)260 static atransport* find_emulator_transport_by_adb_port_locked(int adb_port)
261 REQUIRES(emulator_transports_lock) {
262 auto it = emulator_transports.find(adb_port);
263 if (it == emulator_transports.end()) {
264 return nullptr;
265 }
266 return it->second;
267 }
268
find_emulator_transport_by_adb_port(int adb_port)269 atransport* find_emulator_transport_by_adb_port(int adb_port) {
270 std::lock_guard<std::mutex> lock(emulator_transports_lock);
271 return find_emulator_transport_by_adb_port_locked(adb_port);
272 }
273
find_emulator_transport_by_console_port(int console_port)274 atransport* find_emulator_transport_by_console_port(int console_port) {
275 return find_transport(getEmulatorSerialString(console_port).c_str());
276 }
277
getEmulatorSerialString(int console_port)278 std::string getEmulatorSerialString(int console_port) {
279 return android::base::StringPrintf("emulator-%d", console_port);
280 }
281
init_socket_transport(atransport * t,unique_fd fd,int adb_port,bool is_emulator)282 int init_socket_transport(atransport* t, unique_fd fd, int adb_port, bool is_emulator) {
283 int fail = 0;
284
285 if (is_emulator) {
286 auto emulator_connection = std::make_unique<EmulatorConnection>(std::move(fd), adb_port);
287 t->SetConnection(
288 std::make_unique<BlockingConnectionAdapter>(std::move(emulator_connection)));
289 std::lock_guard<std::mutex> lock(emulator_transports_lock);
290 atransport* existing_transport = find_emulator_transport_by_adb_port_locked(adb_port);
291 if (existing_transport != nullptr) {
292 D("is_emulator transport for port %d already registered (%p)?", adb_port,
293 existing_transport);
294 fail = -1;
295 } else {
296 emulator_transports[adb_port] = t;
297 }
298
299 return fail;
300 }
301
302 // Regular tcp connection.
303 auto fd_connection = std::make_unique<FdConnection>(std::move(fd));
304 t->SetConnection(std::make_unique<BlockingConnectionAdapter>(std::move(fd_connection)));
305 return fail;
306 }
307