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