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