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 #if !ADB_HOST
42 #include <android-base/properties.h>
43 #endif
44
45 #include "adb.h"
46 #include "adb_io.h"
47 #include "adb_unique_fd.h"
48 #include "adb_utils.h"
49 #include "socket_spec.h"
50 #include "sysdeps/chrono.h"
51
52 #if ADB_HOST
53
54 // Android Wear has been using port 5601 in all of its documentation/tooling,
55 // but we search for emulators on ports [5554, 5555 + ADB_LOCAL_TRANSPORT_MAX].
56 // Avoid stomping on their port by restricting the active scanning range.
57 // Once emulators self-(re-)register, they'll have to avoid 5601 in their own way.
58 static int adb_local_transport_max_port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT + 16 * 2 - 1;
59
60 static std::mutex& local_transports_lock = *new std::mutex();
61
adb_local_transport_max_port_env_override()62 static void adb_local_transport_max_port_env_override() {
63 const char* env_max_s = getenv("ADB_LOCAL_TRANSPORT_MAX_PORT");
64 if (env_max_s != nullptr) {
65 size_t env_max;
66 if (ParseUint(&env_max, env_max_s, nullptr) && env_max < 65536) {
67 // < DEFAULT_ADB_LOCAL_TRANSPORT_PORT harmlessly mimics ADB_EMU=0
68 adb_local_transport_max_port = env_max;
69 D("transport: ADB_LOCAL_TRANSPORT_MAX_PORT read as %d", adb_local_transport_max_port);
70 } else {
71 D("transport: ADB_LOCAL_TRANSPORT_MAX_PORT '%s' invalid or >= 65536, so ignored",
72 env_max_s);
73 }
74 }
75 }
76
77 // We keep a map from emulator port to transport.
78 // TODO: weak_ptr?
79 static auto& local_transports GUARDED_BY(local_transports_lock) =
80 *new std::unordered_map<int, atransport*>();
81 #endif /* ADB_HOST */
82
local_connect(int port)83 bool local_connect(int port) {
84 std::string dummy;
85 return local_connect_arbitrary_ports(port - 1, port, &dummy) == 0;
86 }
87
connect_device(const std::string & address,std::string * response)88 void connect_device(const std::string& address, std::string* response) {
89 if (address.empty()) {
90 *response = "empty address";
91 return;
92 }
93
94 D("connection requested to '%s'", address.c_str());
95 unique_fd fd;
96 int port;
97 std::string serial, prefix_addr;
98
99 // If address does not match any socket type, it should default to TCP.
100 if (address.starts_with("vsock:") || address.starts_with("localfilesystem:")) {
101 prefix_addr = address;
102 } else {
103 prefix_addr = "tcp:" + address;
104 }
105
106 socket_spec_connect(&fd, prefix_addr, &port, &serial, response);
107 if (fd.get() == -1) {
108 return;
109 }
110 auto reconnect = [prefix_addr](atransport* t) {
111 std::string response;
112 unique_fd fd;
113 int port;
114 std::string serial;
115 socket_spec_connect(&fd, prefix_addr, &port, &serial, &response);
116 if (fd == -1) {
117 D("reconnect failed: %s", response.c_str());
118 return ReconnectResult::Retry;
119 }
120 // This invokes the part of register_socket_transport() that needs to be
121 // invoked if the atransport* has already been setup. This eventually
122 // calls atransport->SetConnection() with a newly created Connection*
123 // that will in turn send the CNXN packet.
124 return init_socket_transport(t, std::move(fd), port, 0) >= 0 ? ReconnectResult::Success
125 : ReconnectResult::Retry;
126 };
127
128 int error;
129 if (!register_socket_transport(std::move(fd), serial, port, 0, std::move(reconnect), false,
130 &error)) {
131 if (error == EALREADY) {
132 *response = android::base::StringPrintf("already connected to %s", serial.c_str());
133 } else if (error == EPERM) {
134 *response = android::base::StringPrintf("failed to authenticate to %s", serial.c_str());
135 } else {
136 *response = android::base::StringPrintf("failed to connect to %s", serial.c_str());
137 }
138 } else {
139 *response = android::base::StringPrintf("connected to %s", serial.c_str());
140 }
141 }
142
143
local_connect_arbitrary_ports(int console_port,int adb_port,std::string * error)144 int local_connect_arbitrary_ports(int console_port, int adb_port, std::string* error) {
145 unique_fd fd;
146
147 #if ADB_HOST
148 if (find_emulator_transport_by_adb_port(adb_port) != nullptr ||
149 find_emulator_transport_by_console_port(console_port) != nullptr) {
150 return -1;
151 }
152
153 const char *host = getenv("ADBHOST");
154 if (host) {
155 fd.reset(network_connect(host, adb_port, SOCK_STREAM, 0, error));
156 }
157 #endif
158 if (fd < 0) {
159 fd.reset(network_loopback_client(adb_port, SOCK_STREAM, error));
160 }
161
162 if (fd >= 0) {
163 D("client: connected on remote on fd %d", fd.get());
164 close_on_exec(fd.get());
165 disable_tcp_nagle(fd.get());
166 std::string serial = getEmulatorSerialString(console_port);
167 if (register_socket_transport(
168 std::move(fd), std::move(serial), adb_port, 1,
169 [](atransport*) { return ReconnectResult::Abort; }, false)) {
170 return 0;
171 }
172 }
173 return -1;
174 }
175
176 #if ADB_HOST
177
PollAllLocalPortsForEmulator()178 static void PollAllLocalPortsForEmulator() {
179 // Try to connect to any number of running emulator instances.
180 for (int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT; port <= adb_local_transport_max_port;
181 port += 2) {
182 local_connect(port); // Note, uses port and port-1, so '=max_port' is OK.
183 }
184 }
185
186 // Retry the disconnected local port for 60 times, and sleep 1 second between two retries.
187 static constexpr uint32_t LOCAL_PORT_RETRY_COUNT = 60;
188 static constexpr auto LOCAL_PORT_RETRY_INTERVAL = 1s;
189
190 struct RetryPort {
191 int port;
192 uint32_t retry_count;
193 };
194
195 // Retry emulators just kicked.
196 static std::vector<RetryPort>& retry_ports = *new std::vector<RetryPort>;
197 std::mutex &retry_ports_lock = *new std::mutex;
198 std::condition_variable &retry_ports_cond = *new std::condition_variable;
199
client_socket_thread(std::string_view)200 static void client_socket_thread(std::string_view) {
201 adb_thread_setname("client_socket_thread");
202 D("transport: client_socket_thread() starting");
203 PollAllLocalPortsForEmulator();
204 while (true) {
205 std::vector<RetryPort> ports;
206 // Collect retry ports.
207 {
208 std::unique_lock<std::mutex> lock(retry_ports_lock);
209 while (retry_ports.empty()) {
210 retry_ports_cond.wait(lock);
211 }
212 retry_ports.swap(ports);
213 }
214 // Sleep here instead of the end of loop, because if we immediately try to reconnect
215 // the emulator just kicked, the adbd on the emulator may not have time to remove the
216 // just kicked transport.
217 std::this_thread::sleep_for(LOCAL_PORT_RETRY_INTERVAL);
218
219 // Try connecting retry ports.
220 std::vector<RetryPort> next_ports;
221 for (auto& port : ports) {
222 VLOG(TRANSPORT) << "retry port " << port.port << ", last retry_count "
223 << port.retry_count;
224 if (local_connect(port.port)) {
225 VLOG(TRANSPORT) << "retry port " << port.port << " successfully";
226 continue;
227 }
228 if (--port.retry_count > 0) {
229 next_ports.push_back(port);
230 } else {
231 VLOG(TRANSPORT) << "stop retrying port " << port.port;
232 }
233 }
234
235 // Copy back left retry ports.
236 {
237 std::unique_lock<std::mutex> lock(retry_ports_lock);
238 retry_ports.insert(retry_ports.end(), next_ports.begin(), next_ports.end());
239 }
240 }
241 }
242
243 #else // !ADB_HOST
244
server_socket_thread(std::function<unique_fd (std::string_view,std::string *)> listen_func,std::string_view addr)245 void server_socket_thread(std::function<unique_fd(std::string_view, std::string*)> listen_func,
246 std::string_view addr) {
247 adb_thread_setname("server socket");
248
249 unique_fd serverfd;
250 std::string error;
251
252 while (serverfd == -1) {
253 errno = 0;
254 serverfd = listen_func(addr, &error);
255 if (errno == EAFNOSUPPORT || errno == EINVAL || errno == EPROTONOSUPPORT) {
256 D("unrecoverable error: '%s'", error.c_str());
257 return;
258 } else if (serverfd < 0) {
259 D("server: cannot bind socket yet: %s", error.c_str());
260 std::this_thread::sleep_for(1s);
261 continue;
262 }
263 close_on_exec(serverfd.get());
264 }
265
266 while (true) {
267 D("server: trying to get new connection from fd %d", serverfd.get());
268 unique_fd fd(adb_socket_accept(serverfd, nullptr, nullptr));
269 if (fd >= 0) {
270 D("server: new connection on fd %d", fd.get());
271 close_on_exec(fd.get());
272 disable_tcp_nagle(fd.get());
273 std::string serial = android::base::StringPrintf("host-%d", fd.get());
274 // We don't care about port value in "register_socket_transport" as it is used
275 // only from ADB_HOST. "server_socket_thread" is never called from ADB_HOST.
276 register_socket_transport(
277 std::move(fd), std::move(serial), 0, 1,
278 [](atransport*) { return ReconnectResult::Abort; }, false);
279 }
280 }
281 D("transport: server_socket_thread() exiting");
282 }
283
284 #endif
285
286 #if !ADB_HOST
adb_listen(std::string_view addr,std::string * error)287 unique_fd adb_listen(std::string_view addr, std::string* error) {
288 return unique_fd{socket_spec_listen(addr, error, nullptr)};
289 }
290 #endif
291
local_init(const std::string & addr)292 void local_init(const std::string& addr) {
293 #if ADB_HOST
294 D("transport: local client init");
295 std::thread(client_socket_thread, addr).detach();
296 adb_local_transport_max_port_env_override();
297 #elif !defined(__ANDROID__)
298 // Host adbd.
299 D("transport: local server init");
300 std::thread(server_socket_thread, adb_listen, addr).detach();
301 #else
302 D("transport: local server init");
303 // For the adbd daemon in the system image we need to distinguish
304 // between the device, and the emulator.
305 if (addr.starts_with("tcp:") && use_qemu_goldfish()) {
306 std::thread(qemu_socket_thread, addr).detach();
307 } else {
308 std::thread(server_socket_thread, adb_listen, addr).detach();
309 }
310 #endif // !ADB_HOST
311 }
312
313 #if ADB_HOST
314 struct EmulatorConnection : public FdConnection {
EmulatorConnectionEmulatorConnection315 EmulatorConnection(unique_fd fd, int local_port)
316 : FdConnection(std::move(fd)), local_port_(local_port) {}
317
~EmulatorConnectionEmulatorConnection318 ~EmulatorConnection() {
319 VLOG(TRANSPORT) << "remote_close, local_port = " << local_port_;
320 std::unique_lock<std::mutex> lock(retry_ports_lock);
321 RetryPort port;
322 port.port = local_port_;
323 port.retry_count = LOCAL_PORT_RETRY_COUNT;
324 retry_ports.push_back(port);
325 retry_ports_cond.notify_one();
326 }
327
CloseEmulatorConnection328 void Close() override {
329 std::lock_guard<std::mutex> lock(local_transports_lock);
330 local_transports.erase(local_port_);
331 FdConnection::Close();
332 }
333
334 int local_port_;
335 };
336
337 /* Only call this function if you already hold local_transports_lock. */
find_emulator_transport_by_adb_port_locked(int adb_port)338 static atransport* find_emulator_transport_by_adb_port_locked(int adb_port)
339 REQUIRES(local_transports_lock) {
340 auto it = local_transports.find(adb_port);
341 if (it == local_transports.end()) {
342 return nullptr;
343 }
344 return it->second;
345 }
346
find_emulator_transport_by_adb_port(int adb_port)347 atransport* find_emulator_transport_by_adb_port(int adb_port) {
348 std::lock_guard<std::mutex> lock(local_transports_lock);
349 return find_emulator_transport_by_adb_port_locked(adb_port);
350 }
351
find_emulator_transport_by_console_port(int console_port)352 atransport* find_emulator_transport_by_console_port(int console_port) {
353 return find_transport(getEmulatorSerialString(console_port).c_str());
354 }
355 #endif
356
getEmulatorSerialString(int console_port)357 std::string getEmulatorSerialString(int console_port) {
358 return android::base::StringPrintf("emulator-%d", console_port);
359 }
360
init_socket_transport(atransport * t,unique_fd fd,int adb_port,int local)361 int init_socket_transport(atransport* t, unique_fd fd, int adb_port, int local) {
362 int fail = 0;
363
364 t->type = kTransportLocal;
365
366 #if ADB_HOST
367 // Emulator connection.
368 if (local) {
369 auto emulator_connection = std::make_unique<EmulatorConnection>(std::move(fd), adb_port);
370 t->SetConnection(
371 std::make_unique<BlockingConnectionAdapter>(std::move(emulator_connection)));
372 std::lock_guard<std::mutex> lock(local_transports_lock);
373 atransport* existing_transport = find_emulator_transport_by_adb_port_locked(adb_port);
374 if (existing_transport != nullptr) {
375 D("local transport for port %d already registered (%p)?", adb_port, existing_transport);
376 fail = -1;
377 } else {
378 local_transports[adb_port] = t;
379 }
380
381 return fail;
382 }
383 #endif
384
385 // Regular tcp connection.
386 auto fd_connection = std::make_unique<FdConnection>(std::move(fd));
387 t->SetConnection(std::make_unique<BlockingConnectionAdapter>(std::move(fd_connection)));
388 return fail;
389 }
390