• 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 <mutex>
30 #include <thread>
31 #include <vector>
32 
33 #include <android-base/parsenetaddress.h>
34 #include <android-base/stringprintf.h>
35 #include <cutils/sockets.h>
36 
37 #if !ADB_HOST
38 #include <android-base/properties.h>
39 #endif
40 
41 #include "adb.h"
42 #include "adb_io.h"
43 #include "adb_utils.h"
44 #include "sysdeps/chrono.h"
45 
46 #if ADB_HOST
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 limiting the number of emulators that can be
51 // connected.
52 #define ADB_LOCAL_TRANSPORT_MAX 16
53 
54 static std::mutex& local_transports_lock = *new std::mutex();
55 
56 /* we keep a list of opened transports. The atransport struct knows to which
57  * local transport it is connected. The list is used to detect when we're
58  * trying to connect twice to a given local transport.
59  */
60 static atransport*  local_transports[ ADB_LOCAL_TRANSPORT_MAX ];
61 #endif /* ADB_HOST */
62 
remote_read(apacket * p,atransport * t)63 static int remote_read(apacket *p, atransport *t)
64 {
65     if (!ReadFdExactly(t->sfd, &p->msg, sizeof(amessage))) {
66         D("remote local: read terminated (message)");
67         return -1;
68     }
69 
70     if (!check_header(p, t)) {
71         D("bad header: terminated (data)");
72         return -1;
73     }
74 
75     if (!ReadFdExactly(t->sfd, p->data, p->msg.data_length)) {
76         D("remote local: terminated (data)");
77         return -1;
78     }
79 
80     if (!check_data(p)) {
81         D("bad data: terminated (data)");
82         return -1;
83     }
84 
85     return 0;
86 }
87 
remote_write(apacket * p,atransport * t)88 static int remote_write(apacket *p, atransport *t)
89 {
90     int   length = p->msg.data_length;
91 
92     if(!WriteFdExactly(t->sfd, &p->msg, sizeof(amessage) + length)) {
93         D("remote local: write terminated");
94         return -1;
95     }
96 
97     return 0;
98 }
99 
local_connect(int port)100 bool local_connect(int port) {
101     std::string dummy;
102     return local_connect_arbitrary_ports(port-1, port, &dummy) == 0;
103 }
104 
connect_device(const std::string & address,std::string * response)105 void connect_device(const std::string& address, std::string* response) {
106     if (address.empty()) {
107         *response = "empty address";
108         return;
109     }
110 
111     std::string serial;
112     std::string host;
113     int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
114     if (!android::base::ParseNetAddress(address, &host, &port, &serial, response)) {
115         return;
116     }
117 
118     std::string error;
119     int fd = network_connect(host.c_str(), port, SOCK_STREAM, 10, &error);
120     if (fd == -1) {
121         *response = android::base::StringPrintf("unable to connect to %s: %s",
122                                                 serial.c_str(), error.c_str());
123         return;
124     }
125 
126     D("client: connected %s remote on fd %d", serial.c_str(), fd);
127     close_on_exec(fd);
128     disable_tcp_nagle(fd);
129 
130     // Send a TCP keepalive ping to the device every second so we can detect disconnects.
131     if (!set_tcp_keepalive(fd, 1)) {
132         D("warning: failed to configure TCP keepalives (%s)", strerror(errno));
133     }
134 
135     int ret = register_socket_transport(fd, serial.c_str(), port, 0);
136     if (ret < 0) {
137         adb_close(fd);
138         *response = android::base::StringPrintf("already connected to %s", serial.c_str());
139     } else {
140         *response = android::base::StringPrintf("connected to %s", serial.c_str());
141     }
142 }
143 
144 
local_connect_arbitrary_ports(int console_port,int adb_port,std::string * error)145 int local_connect_arbitrary_ports(int console_port, int adb_port, std::string* error) {
146     int fd = -1;
147 
148 #if ADB_HOST
149     if (find_emulator_transport_by_adb_port(adb_port) != nullptr ||
150         find_emulator_transport_by_console_port(console_port) != nullptr) {
151         return -1;
152     }
153 
154     const char *host = getenv("ADBHOST");
155     if (host) {
156         fd = network_connect(host, adb_port, SOCK_STREAM, 0, error);
157     }
158 #endif
159     if (fd < 0) {
160         fd = network_loopback_client(adb_port, SOCK_STREAM, error);
161     }
162 
163     if (fd >= 0) {
164         D("client: connected on remote on fd %d", fd);
165         close_on_exec(fd);
166         disable_tcp_nagle(fd);
167         std::string serial = getEmulatorSerialString(console_port);
168         if (register_socket_transport(fd, serial.c_str(), adb_port, 1) == 0) {
169             return 0;
170         }
171         adb_close(fd);
172     }
173     return -1;
174 }
175 
176 #if ADB_HOST
177 
PollAllLocalPortsForEmulator()178 static void PollAllLocalPortsForEmulator() {
179     int port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
180     int count = ADB_LOCAL_TRANSPORT_MAX;
181 
182     // Try to connect to any number of running emulator instances.
183     for ( ; count > 0; count--, port += 2 ) {
184         local_connect(port);
185     }
186 }
187 
188 // Retry the disconnected local port for 60 times, and sleep 1 second between two retries.
189 constexpr uint32_t LOCAL_PORT_RETRY_COUNT = 60;
190 constexpr auto LOCAL_PORT_RETRY_INTERVAL = 1s;
191 
192 struct RetryPort {
193     int port;
194     uint32_t retry_count;
195 };
196 
197 // Retry emulators just kicked.
198 static std::vector<RetryPort>& retry_ports = *new std::vector<RetryPort>;
199 std::mutex &retry_ports_lock = *new std::mutex;
200 std::condition_variable &retry_ports_cond = *new std::condition_variable;
201 
client_socket_thread(int)202 static void client_socket_thread(int) {
203     adb_thread_setname("client_socket_thread");
204     D("transport: client_socket_thread() starting");
205     PollAllLocalPortsForEmulator();
206     while (true) {
207         std::vector<RetryPort> ports;
208         // Collect retry ports.
209         {
210             std::unique_lock<std::mutex> lock(retry_ports_lock);
211             while (retry_ports.empty()) {
212                 retry_ports_cond.wait(lock);
213             }
214             retry_ports.swap(ports);
215         }
216         // Sleep here instead of the end of loop, because if we immediately try to reconnect
217         // the emulator just kicked, the adbd on the emulator may not have time to remove the
218         // just kicked transport.
219         std::this_thread::sleep_for(LOCAL_PORT_RETRY_INTERVAL);
220 
221         // Try connecting retry ports.
222         std::vector<RetryPort> next_ports;
223         for (auto& port : ports) {
224             VLOG(TRANSPORT) << "retry port " << port.port << ", last retry_count "
225                 << port.retry_count;
226             if (local_connect(port.port)) {
227                 VLOG(TRANSPORT) << "retry port " << port.port << " successfully";
228                 continue;
229             }
230             if (--port.retry_count > 0) {
231                 next_ports.push_back(port);
232             } else {
233                 VLOG(TRANSPORT) << "stop retrying port " << port.port;
234             }
235         }
236 
237         // Copy back left retry ports.
238         {
239             std::unique_lock<std::mutex> lock(retry_ports_lock);
240             retry_ports.insert(retry_ports.end(), next_ports.begin(), next_ports.end());
241         }
242     }
243 }
244 
245 #else // ADB_HOST
246 
server_socket_thread(int port)247 static void server_socket_thread(int port) {
248     int serverfd, fd;
249 
250     adb_thread_setname("server socket");
251     D("transport: server_socket_thread() starting");
252     serverfd = -1;
253     for(;;) {
254         if(serverfd == -1) {
255             std::string error;
256             serverfd = network_inaddr_any_server(port, SOCK_STREAM, &error);
257             if(serverfd < 0) {
258                 D("server: cannot bind socket yet: %s", error.c_str());
259                 std::this_thread::sleep_for(1s);
260                 continue;
261             }
262             close_on_exec(serverfd);
263         }
264 
265         D("server: trying to get new connection from %d", port);
266         fd = adb_socket_accept(serverfd, nullptr, nullptr);
267         if(fd >= 0) {
268             D("server: new connection on fd %d", fd);
269             close_on_exec(fd);
270             disable_tcp_nagle(fd);
271             std::string serial = android::base::StringPrintf("host-%d", fd);
272             if (register_socket_transport(fd, serial.c_str(), port, 1) != 0) {
273                 adb_close(fd);
274             }
275         }
276     }
277     D("transport: server_socket_thread() exiting");
278 }
279 
280 /* This is relevant only for ADB daemon running inside the emulator. */
281 /*
282  * Redefine open and write for qemu_pipe.h that contains inlined references
283  * to those routines. We will redefine them back after qemu_pipe.h inclusion.
284  */
285 #undef open
286 #undef read
287 #undef write
288 #define open    adb_open
289 #define read    adb_read
290 #define write   adb_write
291 #include <qemu_pipe.h>
292 #undef open
293 #undef read
294 #undef write
295 #define open    ___xxx_open
296 #define read    ___xxx_read
297 #define write   ___xxx_write
298 
299 /* A worker thread that monitors host connections, and registers a transport for
300  * every new host connection. This thread replaces server_socket_thread on
301  * condition that adbd daemon runs inside the emulator, and emulator uses QEMUD
302  * pipe to communicate with adbd daemon inside the guest. This is done in order
303  * to provide more robust communication channel between ADB host and guest. The
304  * main issue with server_socket_thread approach is that it runs on top of TCP,
305  * and thus is sensitive to network disruptions. For instance, the
306  * ConnectionManager may decide to reset all network connections, in which case
307  * the connection between ADB host and guest will be lost. To make ADB traffic
308  * independent from the network, we use here 'adb' QEMUD service to transfer data
309  * between the host, and the guest. See external/qemu/android/adb-*.* that
310  * implements the emulator's side of the protocol. Another advantage of using
311  * QEMUD approach is that ADB will be up much sooner, since it doesn't depend
312  * anymore on network being set up.
313  * The guest side of the protocol contains the following phases:
314  * - Connect with adb QEMUD service. In this phase a handle to 'adb' QEMUD service
315  *   is opened, and it becomes clear whether or not emulator supports that
316  *   protocol.
317  * - Wait for the ADB host to create connection with the guest. This is done by
318  *   sending an 'accept' request to the adb QEMUD service, and waiting on
319  *   response.
320  * - When new ADB host connection is accepted, the connection with adb QEMUD
321  *   service is registered as the transport, and a 'start' request is sent to the
322  *   adb QEMUD service, indicating that the guest is ready to receive messages.
323  *   Note that the guest will ignore messages sent down from the emulator before
324  *   the transport registration is completed. That's why we need to send the
325  *   'start' request after the transport is registered.
326  */
qemu_socket_thread(int port)327 static void qemu_socket_thread(int port) {
328     /* 'accept' request to the adb QEMUD service. */
329     static const char _accept_req[] = "accept";
330     /* 'start' request to the adb QEMUD service. */
331     static const char _start_req[] = "start";
332     /* 'ok' reply from the adb QEMUD service. */
333     static const char _ok_resp[] = "ok";
334 
335     int fd;
336     char tmp[256];
337     char con_name[32];
338 
339     adb_thread_setname("qemu socket");
340     D("transport: qemu_socket_thread() starting");
341 
342     /* adb QEMUD service connection request. */
343     snprintf(con_name, sizeof(con_name), "pipe:qemud:adb:%d", port);
344 
345     /* Connect to the adb QEMUD service. */
346     fd = qemu_pipe_open(con_name);
347     if (fd < 0) {
348         /* This could be an older version of the emulator, that doesn't
349          * implement adb QEMUD service. Fall back to the old TCP way. */
350         D("adb service is not available. Falling back to TCP socket.");
351         std::thread(server_socket_thread, port).detach();
352         return;
353     }
354 
355     for(;;) {
356         /*
357          * Wait till the host creates a new connection.
358          */
359 
360         /* Send the 'accept' request. */
361         if (WriteFdExactly(fd, _accept_req, strlen(_accept_req))) {
362             /* Wait for the response. In the response we expect 'ok' on success,
363              * or 'ko' on failure. */
364             if (!ReadFdExactly(fd, tmp, 2) || memcmp(tmp, _ok_resp, 2)) {
365                 D("Accepting ADB host connection has failed.");
366                 adb_close(fd);
367             } else {
368                 /* Host is connected. Register the transport, and start the
369                  * exchange. */
370                 std::string serial = android::base::StringPrintf("host-%d", fd);
371                 if (register_socket_transport(fd, serial.c_str(), port, 1) != 0 ||
372                     !WriteFdExactly(fd, _start_req, strlen(_start_req))) {
373                     adb_close(fd);
374                 }
375             }
376 
377             /* Prepare for accepting of the next ADB host connection. */
378             fd = qemu_pipe_open(con_name);
379             if (fd < 0) {
380                 D("adb service become unavailable.");
381                 return;
382             }
383         } else {
384             D("Unable to send the '%s' request to ADB service.", _accept_req);
385             return;
386         }
387     }
388     D("transport: qemu_socket_thread() exiting");
389     return;
390 }
391 
392 // If adbd is running inside the emulator, it will normally use QEMUD pipe (aka
393 // goldfish) as the transport. This can either be explicitly set by the
394 // service.adb.transport property, or be inferred from ro.kernel.qemu that is
395 // set to "1" for ranchu/goldfish.
use_qemu_goldfish()396 static bool use_qemu_goldfish() {
397     // Legacy way to detect if adbd should use the goldfish pipe is to check for
398     // ro.kernel.qemu, keep that behaviour for backward compatibility.
399     if (android::base::GetBoolProperty("ro.kernel.qemu", false)) {
400         return true;
401     }
402     // If service.adb.transport is present and is set to "goldfish", use the
403     // QEMUD pipe.
404     if (android::base::GetProperty("service.adb.transport", "") == "goldfish") {
405         return true;
406     }
407     return false;
408 }
409 
410 #endif  // !ADB_HOST
411 
local_init(int port)412 void local_init(int port)
413 {
414     void (*func)(int);
415     const char* debug_name = "";
416 
417 #if ADB_HOST
418     func = client_socket_thread;
419     debug_name = "client";
420 #else
421     // For the adbd daemon in the system image we need to distinguish
422     // between the device, and the emulator.
423     func = use_qemu_goldfish() ? qemu_socket_thread : server_socket_thread;
424     debug_name = "server";
425 #endif // !ADB_HOST
426 
427     D("transport: local %s init", debug_name);
428     std::thread(func, port).detach();
429 }
430 
remote_kick(atransport * t)431 static void remote_kick(atransport *t)
432 {
433     int fd = t->sfd;
434     t->sfd = -1;
435     adb_shutdown(fd);
436     adb_close(fd);
437 
438 #if ADB_HOST
439     int  nn;
440     std::lock_guard<std::mutex> lock(local_transports_lock);
441     for (nn = 0; nn < ADB_LOCAL_TRANSPORT_MAX; nn++) {
442         if (local_transports[nn] == t) {
443             local_transports[nn] = NULL;
444             break;
445         }
446     }
447 #endif
448 }
449 
remote_close(atransport * t)450 static void remote_close(atransport *t)
451 {
452     int fd = t->sfd;
453     if (fd != -1) {
454         t->sfd = -1;
455         adb_close(fd);
456     }
457 #if ADB_HOST
458     int local_port;
459     if (t->GetLocalPortForEmulator(&local_port)) {
460         VLOG(TRANSPORT) << "remote_close, local_port = " << local_port;
461         std::unique_lock<std::mutex> lock(retry_ports_lock);
462         RetryPort port;
463         port.port = local_port;
464         port.retry_count = LOCAL_PORT_RETRY_COUNT;
465         retry_ports.push_back(port);
466         retry_ports_cond.notify_one();
467     }
468 #endif
469 }
470 
471 
472 #if ADB_HOST
473 /* Only call this function if you already hold local_transports_lock. */
find_emulator_transport_by_adb_port_locked(int adb_port)474 static atransport* find_emulator_transport_by_adb_port_locked(int adb_port)
475 {
476     int i;
477     for (i = 0; i < ADB_LOCAL_TRANSPORT_MAX; i++) {
478         int local_port;
479         if (local_transports[i] && local_transports[i]->GetLocalPortForEmulator(&local_port)) {
480             if (local_port == adb_port) {
481                 return local_transports[i];
482             }
483         }
484     }
485     return NULL;
486 }
487 
getEmulatorSerialString(int console_port)488 std::string getEmulatorSerialString(int console_port)
489 {
490     return android::base::StringPrintf("emulator-%d", console_port);
491 }
492 
find_emulator_transport_by_adb_port(int adb_port)493 atransport* find_emulator_transport_by_adb_port(int adb_port)
494 {
495     std::lock_guard<std::mutex> lock(local_transports_lock);
496     atransport* result = find_emulator_transport_by_adb_port_locked(adb_port);
497     return result;
498 }
499 
find_emulator_transport_by_console_port(int console_port)500 atransport* find_emulator_transport_by_console_port(int console_port)
501 {
502     return find_transport(getEmulatorSerialString(console_port).c_str());
503 }
504 
505 
506 /* Only call this function if you already hold local_transports_lock. */
get_available_local_transport_index_locked()507 int get_available_local_transport_index_locked()
508 {
509     int i;
510     for (i = 0; i < ADB_LOCAL_TRANSPORT_MAX; i++) {
511         if (local_transports[i] == NULL) {
512             return i;
513         }
514     }
515     return -1;
516 }
517 
get_available_local_transport_index()518 int get_available_local_transport_index()
519 {
520     std::lock_guard<std::mutex> lock(local_transports_lock);
521     int result = get_available_local_transport_index_locked();
522     return result;
523 }
524 #endif
525 
init_socket_transport(atransport * t,int s,int adb_port,int local)526 int init_socket_transport(atransport *t, int s, int adb_port, int local)
527 {
528     int  fail = 0;
529 
530     t->SetKickFunction(remote_kick);
531     t->SetWriteFunction(remote_write);
532     t->close = remote_close;
533     t->read_from_remote = remote_read;
534     t->sfd = s;
535     t->sync_token = 1;
536     t->type = kTransportLocal;
537 
538 #if ADB_HOST
539     if (local) {
540         std::lock_guard<std::mutex> lock(local_transports_lock);
541         t->SetLocalPortForEmulator(adb_port);
542         atransport* existing_transport = find_emulator_transport_by_adb_port_locked(adb_port);
543         int index = get_available_local_transport_index_locked();
544         if (existing_transport != NULL) {
545             D("local transport for port %d already registered (%p)?", adb_port, existing_transport);
546             fail = -1;
547         } else if (index < 0) {
548             // Too many emulators.
549             D("cannot register more emulators. Maximum is %d", ADB_LOCAL_TRANSPORT_MAX);
550             fail = -1;
551         } else {
552             local_transports[index] = t;
553         }
554     }
555 #endif
556     return fail;
557 }
558