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
tcp_connect(const std::string & address,std::string * response)88 std::tuple<unique_fd, int, std::string> tcp_connect(const std::string& address,
89 std::string* response) {
90 unique_fd fd;
91 int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
92 std::string serial;
93 std::string prefix_addr = address.starts_with("vsock:") ? address : "tcp:" + address;
94 if (socket_spec_connect(&fd, prefix_addr, &port, &serial, response)) {
95 close_on_exec(fd);
96 if (!set_tcp_keepalive(fd, 1)) {
97 D("warning: failed to configure TCP keepalives (%s)", strerror(errno));
98 }
99 return std::make_tuple(std::move(fd), port, serial);
100 }
101 return std::make_tuple(unique_fd(), 0, serial);
102 }
103
connect_device(const std::string & address,std::string * response)104 void connect_device(const std::string& address, std::string* response) {
105 if (address.empty()) {
106 *response = "empty address";
107 return;
108 }
109
110 D("connection requested to '%s'", address.c_str());
111 unique_fd fd;
112 int port;
113 std::string serial;
114 std::tie(fd, port, serial) = tcp_connect(address, response);
115 if (fd.get() == -1) {
116 return;
117 }
118 auto reconnect = [address](atransport* t) {
119 std::string response;
120 unique_fd fd;
121 int port;
122 std::string serial;
123 std::tie(fd, port, serial) = tcp_connect(address, &response);
124 if (fd == -1) {
125 D("reconnect failed: %s", response.c_str());
126 return ReconnectResult::Retry;
127 }
128 // This invokes the part of register_socket_transport() that needs to be
129 // invoked if the atransport* has already been setup. This eventually
130 // calls atransport->SetConnection() with a newly created Connection*
131 // that will in turn send the CNXN packet.
132 return init_socket_transport(t, std::move(fd), port, 0) >= 0 ? ReconnectResult::Success
133 : ReconnectResult::Retry;
134 };
135
136 int error;
137 if (!register_socket_transport(std::move(fd), serial, port, 0, std::move(reconnect), &error)) {
138 if (error == EALREADY) {
139 *response = android::base::StringPrintf("already connected to %s", serial.c_str());
140 } else if (error == EPERM) {
141 *response = android::base::StringPrintf("failed to authenticate to %s", serial.c_str());
142 } else {
143 *response = android::base::StringPrintf("failed to connect to %s", serial.c_str());
144 }
145 } else {
146 *response = android::base::StringPrintf("connected to %s", serial.c_str());
147 }
148 }
149
150
local_connect_arbitrary_ports(int console_port,int adb_port,std::string * error)151 int local_connect_arbitrary_ports(int console_port, int adb_port, std::string* error) {
152 unique_fd fd;
153
154 #if ADB_HOST
155 if (find_emulator_transport_by_adb_port(adb_port) != nullptr ||
156 find_emulator_transport_by_console_port(console_port) != nullptr) {
157 return -1;
158 }
159
160 const char *host = getenv("ADBHOST");
161 if (host) {
162 fd.reset(network_connect(host, adb_port, SOCK_STREAM, 0, error));
163 }
164 #endif
165 if (fd < 0) {
166 fd.reset(network_loopback_client(adb_port, SOCK_STREAM, error));
167 }
168
169 if (fd >= 0) {
170 D("client: connected on remote on fd %d", fd.get());
171 close_on_exec(fd.get());
172 disable_tcp_nagle(fd.get());
173 std::string serial = getEmulatorSerialString(console_port);
174 if (register_socket_transport(std::move(fd), std::move(serial), adb_port, 1,
175 [](atransport*) { return ReconnectResult::Abort; })) {
176 return 0;
177 }
178 }
179 return -1;
180 }
181
182 #if ADB_HOST
183
PollAllLocalPortsForEmulator()184 static void PollAllLocalPortsForEmulator() {
185 // Try to connect to any number of running emulator instances.
186 for (int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT; port <= adb_local_transport_max_port;
187 port += 2) {
188 local_connect(port); // Note, uses port and port-1, so '=max_port' is OK.
189 }
190 }
191
192 // Retry the disconnected local port for 60 times, and sleep 1 second between two retries.
193 static constexpr uint32_t LOCAL_PORT_RETRY_COUNT = 60;
194 static constexpr auto LOCAL_PORT_RETRY_INTERVAL = 1s;
195
196 struct RetryPort {
197 int port;
198 uint32_t retry_count;
199 };
200
201 // Retry emulators just kicked.
202 static std::vector<RetryPort>& retry_ports = *new std::vector<RetryPort>;
203 std::mutex &retry_ports_lock = *new std::mutex;
204 std::condition_variable &retry_ports_cond = *new std::condition_variable;
205
client_socket_thread(int)206 static void client_socket_thread(int) {
207 adb_thread_setname("client_socket_thread");
208 D("transport: client_socket_thread() starting");
209 PollAllLocalPortsForEmulator();
210 while (true) {
211 std::vector<RetryPort> ports;
212 // Collect retry ports.
213 {
214 std::unique_lock<std::mutex> lock(retry_ports_lock);
215 while (retry_ports.empty()) {
216 retry_ports_cond.wait(lock);
217 }
218 retry_ports.swap(ports);
219 }
220 // Sleep here instead of the end of loop, because if we immediately try to reconnect
221 // the emulator just kicked, the adbd on the emulator may not have time to remove the
222 // just kicked transport.
223 std::this_thread::sleep_for(LOCAL_PORT_RETRY_INTERVAL);
224
225 // Try connecting retry ports.
226 std::vector<RetryPort> next_ports;
227 for (auto& port : ports) {
228 VLOG(TRANSPORT) << "retry port " << port.port << ", last retry_count "
229 << port.retry_count;
230 if (local_connect(port.port)) {
231 VLOG(TRANSPORT) << "retry port " << port.port << " successfully";
232 continue;
233 }
234 if (--port.retry_count > 0) {
235 next_ports.push_back(port);
236 } else {
237 VLOG(TRANSPORT) << "stop retrying port " << port.port;
238 }
239 }
240
241 // Copy back left retry ports.
242 {
243 std::unique_lock<std::mutex> lock(retry_ports_lock);
244 retry_ports.insert(retry_ports.end(), next_ports.begin(), next_ports.end());
245 }
246 }
247 }
248
249 #else // !ADB_HOST
250
server_socket_thread(std::function<unique_fd (int,std::string *)> listen_func,int port)251 void server_socket_thread(std::function<unique_fd(int, std::string*)> listen_func, int port) {
252 adb_thread_setname("server socket");
253
254 unique_fd serverfd;
255 std::string error;
256
257 while (serverfd == -1) {
258 errno = 0;
259 serverfd = listen_func(port, &error);
260 if (errno == EAFNOSUPPORT || errno == EINVAL || errno == EPROTONOSUPPORT) {
261 D("unrecoverable error: '%s'", error.c_str());
262 return;
263 } else if (serverfd < 0) {
264 D("server: cannot bind socket yet: %s", error.c_str());
265 std::this_thread::sleep_for(1s);
266 continue;
267 }
268 close_on_exec(serverfd.get());
269 }
270
271 while (true) {
272 D("server: trying to get new connection from fd %d", serverfd.get());
273 unique_fd fd(adb_socket_accept(serverfd, nullptr, nullptr));
274 if (fd >= 0) {
275 D("server: new connection on fd %d", fd.get());
276 close_on_exec(fd.get());
277 disable_tcp_nagle(fd.get());
278 std::string serial = android::base::StringPrintf("host-%d", fd.get());
279 register_socket_transport(std::move(fd), std::move(serial), port, 1,
280 [](atransport*) { return ReconnectResult::Abort; });
281 }
282 }
283 D("transport: server_socket_thread() exiting");
284 }
285
286 #endif
287
tcp_listen_inaddr_any(int port,std::string * error)288 unique_fd tcp_listen_inaddr_any(int port, std::string* error) {
289 return unique_fd{network_inaddr_any_server(port, SOCK_STREAM, error)};
290 }
291
292 #if !ADB_HOST
vsock_listen(int port,std::string * error)293 static unique_fd vsock_listen(int port, std::string* error) {
294 return unique_fd{
295 socket_spec_listen(android::base::StringPrintf("vsock:%d", port), error, nullptr)
296 };
297 }
298 #endif
299
local_init(int port)300 void local_init(int port) {
301 #if ADB_HOST
302 D("transport: local client init");
303 std::thread(client_socket_thread, port).detach();
304 adb_local_transport_max_port_env_override();
305 #elif !defined(__ANDROID__)
306 // Host adbd.
307 D("transport: local server init");
308 std::thread(server_socket_thread, tcp_listen_inaddr_any, port).detach();
309 std::thread(server_socket_thread, vsock_listen, port).detach();
310 #else
311 D("transport: local server init");
312 // For the adbd daemon in the system image we need to distinguish
313 // between the device, and the emulator.
314 if (use_qemu_goldfish()) {
315 std::thread(qemu_socket_thread, port).detach();
316 } else {
317 std::thread(server_socket_thread, tcp_listen_inaddr_any, port).detach();
318 }
319 std::thread(server_socket_thread, vsock_listen, port).detach();
320 #endif // !ADB_HOST
321 }
322
323 #if ADB_HOST
324 struct EmulatorConnection : public FdConnection {
EmulatorConnectionEmulatorConnection325 EmulatorConnection(unique_fd fd, int local_port)
326 : FdConnection(std::move(fd)), local_port_(local_port) {}
327
~EmulatorConnectionEmulatorConnection328 ~EmulatorConnection() {
329 VLOG(TRANSPORT) << "remote_close, local_port = " << local_port_;
330 std::unique_lock<std::mutex> lock(retry_ports_lock);
331 RetryPort port;
332 port.port = local_port_;
333 port.retry_count = LOCAL_PORT_RETRY_COUNT;
334 retry_ports.push_back(port);
335 retry_ports_cond.notify_one();
336 }
337
CloseEmulatorConnection338 void Close() override {
339 std::lock_guard<std::mutex> lock(local_transports_lock);
340 local_transports.erase(local_port_);
341 FdConnection::Close();
342 }
343
344 int local_port_;
345 };
346
347 /* Only call this function if you already hold local_transports_lock. */
find_emulator_transport_by_adb_port_locked(int adb_port)348 static atransport* find_emulator_transport_by_adb_port_locked(int adb_port)
349 REQUIRES(local_transports_lock) {
350 auto it = local_transports.find(adb_port);
351 if (it == local_transports.end()) {
352 return nullptr;
353 }
354 return it->second;
355 }
356
find_emulator_transport_by_adb_port(int adb_port)357 atransport* find_emulator_transport_by_adb_port(int adb_port) {
358 std::lock_guard<std::mutex> lock(local_transports_lock);
359 return find_emulator_transport_by_adb_port_locked(adb_port);
360 }
361
find_emulator_transport_by_console_port(int console_port)362 atransport* find_emulator_transport_by_console_port(int console_port) {
363 return find_transport(getEmulatorSerialString(console_port).c_str());
364 }
365 #endif
366
getEmulatorSerialString(int console_port)367 std::string getEmulatorSerialString(int console_port) {
368 return android::base::StringPrintf("emulator-%d", console_port);
369 }
370
init_socket_transport(atransport * t,unique_fd fd,int adb_port,int local)371 int init_socket_transport(atransport* t, unique_fd fd, int adb_port, int local) {
372 int fail = 0;
373
374 t->type = kTransportLocal;
375
376 #if ADB_HOST
377 // Emulator connection.
378 if (local) {
379 auto emulator_connection = std::make_unique<EmulatorConnection>(std::move(fd), adb_port);
380 t->SetConnection(
381 std::make_unique<BlockingConnectionAdapter>(std::move(emulator_connection)));
382 std::lock_guard<std::mutex> lock(local_transports_lock);
383 atransport* existing_transport = find_emulator_transport_by_adb_port_locked(adb_port);
384 if (existing_transport != nullptr) {
385 D("local transport for port %d already registered (%p)?", adb_port, existing_transport);
386 fail = -1;
387 } else {
388 local_transports[adb_port] = t;
389 }
390
391 return fail;
392 }
393 #endif
394
395 // Regular tcp connection.
396 auto fd_connection = std::make_unique<FdConnection>(std::move(fd));
397 t->SetConnection(std::make_unique<BlockingConnectionAdapter>(std::move(fd_connection)));
398 return fail;
399 }
400