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 <ctype.h>
     23 #include <errno.h>
     24 #include <inttypes.h>
     25 #include <stdio.h>
     26 #include <stdlib.h>
     27 #include <string.h>
     28 #include <unistd.h>
     29 
     30 #include <algorithm>
     31 #include <list>
     32 #include <mutex>
     33 #include <thread>
     34 
     35 #include <android-base/logging.h>
     36 #include <android-base/parsenetaddress.h>
     37 #include <android-base/stringprintf.h>
     38 #include <android-base/strings.h>
     39 #include <android-base/thread_annotations.h>
     40 
     41 #include "adb.h"
     42 #include "adb_auth.h"
     43 #include "adb_io.h"
     44 #include "adb_trace.h"
     45 #include "adb_utils.h"
     46 #include "diagnose_usb.h"
     47 #include "fdevent.h"
     48 
     49 static void transport_unref(atransport *t);
     50 
     51 // TODO: unordered_map<TransportId, atransport*>
     52 static auto& transport_list = *new std::list<atransport*>();
     53 static auto& pending_list = *new std::list<atransport*>();
     54 
     55 static auto& transport_lock = *new std::recursive_mutex();
     56 
     57 const char* const kFeatureShell2 = "shell_v2";
     58 const char* const kFeatureCmd = "cmd";
     59 const char* const kFeatureStat2 = "stat_v2";
     60 const char* const kFeatureLibusb = "libusb";
     61 const char* const kFeaturePushSync = "push_sync";
     62 
     63 TransportId NextTransportId() {
     64     static std::atomic<TransportId> next(1);
     65     return next++;
     66 }
     67 
     68 bool FdConnection::Read(apacket* packet) {
     69     if (!ReadFdExactly(fd_.get(), &packet->msg, sizeof(amessage))) {
     70         D("remote local: read terminated (message)");
     71         return false;
     72     }
     73 
     74     if (packet->msg.data_length > MAX_PAYLOAD) {
     75         D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
     76         return false;
     77     }
     78 
     79     packet->payload.resize(packet->msg.data_length);
     80 
     81     if (!ReadFdExactly(fd_.get(), &packet->payload[0], packet->payload.size())) {
     82         D("remote local: terminated (data)");
     83         return false;
     84     }
     85 
     86     return true;
     87 }
     88 
     89 bool FdConnection::Write(apacket* packet) {
     90     if (!WriteFdExactly(fd_.get(), &packet->msg, sizeof(packet->msg))) {
     91         D("remote local: write terminated");
     92         return false;
     93     }
     94 
     95     if (packet->msg.data_length) {
     96         if (!WriteFdExactly(fd_.get(), &packet->payload[0], packet->msg.data_length)) {
     97             D("remote local: write terminated");
     98             return false;
     99         }
    100     }
    101 
    102     return true;
    103 }
    104 
    105 void FdConnection::Close() {
    106     adb_shutdown(fd_.get());
    107     fd_.reset();
    108 }
    109 
    110 static std::string dump_packet(const char* name, const char* func, apacket* p) {
    111     unsigned command = p->msg.command;
    112     int len = p->msg.data_length;
    113     char cmd[9];
    114     char arg0[12], arg1[12];
    115     int n;
    116 
    117     for (n = 0; n < 4; n++) {
    118         int b = (command >> (n * 8)) & 255;
    119         if (b < 32 || b >= 127) break;
    120         cmd[n] = (char)b;
    121     }
    122     if (n == 4) {
    123         cmd[4] = 0;
    124     } else {
    125         /* There is some non-ASCII name in the command, so dump
    126             * the hexadecimal value instead */
    127         snprintf(cmd, sizeof cmd, "%08x", command);
    128     }
    129 
    130     if (p->msg.arg0 < 256U)
    131         snprintf(arg0, sizeof arg0, "%d", p->msg.arg0);
    132     else
    133         snprintf(arg0, sizeof arg0, "0x%x", p->msg.arg0);
    134 
    135     if (p->msg.arg1 < 256U)
    136         snprintf(arg1, sizeof arg1, "%d", p->msg.arg1);
    137     else
    138         snprintf(arg1, sizeof arg1, "0x%x", p->msg.arg1);
    139 
    140     std::string result = android::base::StringPrintf("%s: %s: [%s] arg0=%s arg1=%s (len=%d) ", name,
    141                                                      func, cmd, arg0, arg1, len);
    142     result += dump_hex(p->payload.data(), p->payload.size());
    143     return result;
    144 }
    145 
    146 static int read_packet(int fd, const char* name, apacket** ppacket) {
    147     ATRACE_NAME("read_packet");
    148     char buff[8];
    149     if (!name) {
    150         snprintf(buff, sizeof buff, "fd=%d", fd);
    151         name = buff;
    152     }
    153     char* p = reinterpret_cast<char*>(ppacket); /* really read a packet address */
    154     int len = sizeof(apacket*);
    155     while (len > 0) {
    156         int r = adb_read(fd, p, len);
    157         if (r > 0) {
    158             len -= r;
    159             p += r;
    160         } else {
    161             D("%s: read_packet (fd=%d), error ret=%d: %s", name, fd, r, strerror(errno));
    162             return -1;
    163         }
    164     }
    165 
    166     VLOG(TRANSPORT) << dump_packet(name, "from remote", *ppacket);
    167     return 0;
    168 }
    169 
    170 static int write_packet(int fd, const char* name, apacket** ppacket) {
    171     ATRACE_NAME("write_packet");
    172     char buff[8];
    173     if (!name) {
    174         snprintf(buff, sizeof buff, "fd=%d", fd);
    175         name = buff;
    176     }
    177     VLOG(TRANSPORT) << dump_packet(name, "to remote", *ppacket);
    178     char* p = reinterpret_cast<char*>(ppacket); /* we really write the packet address */
    179     int len = sizeof(apacket*);
    180     while (len > 0) {
    181         int r = adb_write(fd, p, len);
    182         if (r > 0) {
    183             len -= r;
    184             p += r;
    185         } else {
    186             D("%s: write_packet (fd=%d) error ret=%d: %s", name, fd, r, strerror(errno));
    187             return -1;
    188         }
    189     }
    190     return 0;
    191 }
    192 
    193 static void transport_socket_events(int fd, unsigned events, void* _t) {
    194     atransport* t = reinterpret_cast<atransport*>(_t);
    195     D("transport_socket_events(fd=%d, events=%04x,...)", fd, events);
    196     if (events & FDE_READ) {
    197         apacket* p = 0;
    198         if (read_packet(fd, t->serial, &p)) {
    199             D("%s: failed to read packet from transport socket on fd %d", t->serial, fd);
    200             return;
    201         }
    202 
    203         handle_packet(p, (atransport*)_t);
    204     }
    205 }
    206 
    207 void send_packet(apacket* p, atransport* t) {
    208     p->msg.magic = p->msg.command ^ 0xffffffff;
    209     // compute a checksum for connection/auth packets for compatibility reasons
    210     if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
    211         p->msg.data_check = 0;
    212     } else {
    213         p->msg.data_check = calculate_apacket_checksum(p);
    214     }
    215 
    216     print_packet("send", p);
    217 
    218     if (t == NULL) {
    219         fatal("Transport is null");
    220     }
    221 
    222     if (write_packet(t->transport_socket, t->serial, &p)) {
    223         fatal_errno("cannot enqueue packet on transport socket");
    224     }
    225 }
    226 
    227 // The transport is opened by transport_register_func before
    228 // the read_transport and write_transport threads are started.
    229 //
    230 // The read_transport thread issues a SYNC(1, token) message to let
    231 // the write_transport thread know to start things up.  In the event
    232 // of transport IO failure, the read_transport thread will post a
    233 // SYNC(0,0) message to ensure shutdown.
    234 //
    235 // The transport will not actually be closed until both threads exit, but the threads
    236 // will kick the transport on their way out to disconnect the underlying device.
    237 //
    238 // read_transport thread reads data from a transport (representing a usb/tcp connection),
    239 // and makes the main thread call handle_packet().
    240 static void read_transport_thread(void* _t) {
    241     atransport* t = reinterpret_cast<atransport*>(_t);
    242     apacket* p;
    243 
    244     adb_thread_setname(
    245         android::base::StringPrintf("<-%s", (t->serial != nullptr ? t->serial : "transport")));
    246     D("%s: starting read_transport thread on fd %d, SYNC online (%d)", t->serial, t->fd,
    247       t->sync_token + 1);
    248     p = get_apacket();
    249     p->msg.command = A_SYNC;
    250     p->msg.arg0 = 1;
    251     p->msg.arg1 = ++(t->sync_token);
    252     p->msg.magic = A_SYNC ^ 0xffffffff;
    253     D("sending SYNC packet (len = %u, payload.size() = %zu)", p->msg.data_length, p->payload.size());
    254     if (write_packet(t->fd, t->serial, &p)) {
    255         put_apacket(p);
    256         D("%s: failed to write SYNC packet", t->serial);
    257         goto oops;
    258     }
    259 
    260     D("%s: data pump started", t->serial);
    261     for (;;) {
    262         ATRACE_NAME("read_transport loop");
    263         p = get_apacket();
    264 
    265         {
    266             ATRACE_NAME("read_transport read_remote");
    267             if (!t->connection->Read(p)) {
    268                 D("%s: remote read failed for transport", t->serial);
    269                 put_apacket(p);
    270                 break;
    271             }
    272 
    273             if (!check_header(p, t)) {
    274                 D("%s: remote read: bad header", t->serial);
    275                 put_apacket(p);
    276                 break;
    277             }
    278 
    279 #if ADB_HOST
    280             if (p->msg.command == 0) {
    281                 put_apacket(p);
    282                 continue;
    283             }
    284 #endif
    285         }
    286 
    287         D("%s: received remote packet, sending to transport", t->serial);
    288         if (write_packet(t->fd, t->serial, &p)) {
    289             put_apacket(p);
    290             D("%s: failed to write apacket to transport", t->serial);
    291             goto oops;
    292         }
    293     }
    294 
    295     D("%s: SYNC offline for transport", t->serial);
    296     p = get_apacket();
    297     p->msg.command = A_SYNC;
    298     p->msg.arg0 = 0;
    299     p->msg.arg1 = 0;
    300     p->msg.magic = A_SYNC ^ 0xffffffff;
    301     if (write_packet(t->fd, t->serial, &p)) {
    302         put_apacket(p);
    303         D("%s: failed to write SYNC apacket to transport", t->serial);
    304     }
    305 
    306 oops:
    307     D("%s: read_transport thread is exiting", t->serial);
    308     kick_transport(t);
    309     transport_unref(t);
    310 }
    311 
    312 // write_transport thread gets packets sent by the main thread (through send_packet()),
    313 // and writes to a transport (representing a usb/tcp connection).
    314 static void write_transport_thread(void* _t) {
    315     atransport* t = reinterpret_cast<atransport*>(_t);
    316     apacket* p;
    317     int active = 0;
    318 
    319     adb_thread_setname(
    320         android::base::StringPrintf("->%s", (t->serial != nullptr ? t->serial : "transport")));
    321     D("%s: starting write_transport thread, reading from fd %d", t->serial, t->fd);
    322 
    323     for (;;) {
    324         ATRACE_NAME("write_transport loop");
    325         if (read_packet(t->fd, t->serial, &p)) {
    326             D("%s: failed to read apacket from transport on fd %d", t->serial, t->fd);
    327             break;
    328         }
    329 
    330         if (p->msg.command == A_SYNC) {
    331             if (p->msg.arg0 == 0) {
    332                 D("%s: transport SYNC offline", t->serial);
    333                 put_apacket(p);
    334                 break;
    335             } else {
    336                 if (p->msg.arg1 == t->sync_token) {
    337                     D("%s: transport SYNC online", t->serial);
    338                     active = 1;
    339                 } else {
    340                     D("%s: transport ignoring SYNC %d != %d", t->serial, p->msg.arg1, t->sync_token);
    341                 }
    342             }
    343         } else {
    344             if (active) {
    345                 D("%s: transport got packet, sending to remote", t->serial);
    346                 ATRACE_NAME("write_transport write_remote");
    347 
    348                 // Allow sending the payload's implicit null terminator.
    349                 if (p->msg.data_length != p->payload.size()) {
    350                     LOG(FATAL) << "packet data length doesn't match payload: msg.data_length = "
    351                                << p->msg.data_length << ", payload.size() = " << p->payload.size();
    352                 }
    353 
    354                 if (t->Write(p) != 0) {
    355                     D("%s: remote write failed for transport", t->serial);
    356                     put_apacket(p);
    357                     break;
    358                 }
    359             } else {
    360                 D("%s: transport ignoring packet while offline", t->serial);
    361             }
    362         }
    363 
    364         put_apacket(p);
    365     }
    366 
    367     D("%s: write_transport thread is exiting, fd %d", t->serial, t->fd);
    368     kick_transport(t);
    369     transport_unref(t);
    370 }
    371 
    372 void kick_transport(atransport* t) {
    373     std::lock_guard<std::recursive_mutex> lock(transport_lock);
    374     // As kick_transport() can be called from threads without guarantee that t is valid,
    375     // check if the transport is in transport_list first.
    376     //
    377     // TODO(jmgao): WTF? Is this actually true?
    378     if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
    379         t->Kick();
    380     }
    381 }
    382 
    383 static int transport_registration_send = -1;
    384 static int transport_registration_recv = -1;
    385 static fdevent transport_registration_fde;
    386 
    387 #if ADB_HOST
    388 
    389 /* this adds support required by the 'track-devices' service.
    390  * this is used to send the content of "list_transport" to any
    391  * number of client connections that want it through a single
    392  * live TCP connection
    393  */
    394 struct device_tracker {
    395     asocket socket;
    396     bool update_needed = false;
    397     bool long_output = false;
    398     device_tracker* next = nullptr;
    399 };
    400 
    401 /* linked list of all device trackers */
    402 static device_tracker* device_tracker_list;
    403 
    404 static void device_tracker_remove(device_tracker* tracker) {
    405     device_tracker** pnode = &device_tracker_list;
    406     device_tracker* node = *pnode;
    407 
    408     std::lock_guard<std::recursive_mutex> lock(transport_lock);
    409     while (node) {
    410         if (node == tracker) {
    411             *pnode = node->next;
    412             break;
    413         }
    414         pnode = &node->next;
    415         node = *pnode;
    416     }
    417 }
    418 
    419 static void device_tracker_close(asocket* socket) {
    420     device_tracker* tracker = (device_tracker*)socket;
    421     asocket* peer = socket->peer;
    422 
    423     D("device tracker %p removed", tracker);
    424     if (peer) {
    425         peer->peer = NULL;
    426         peer->close(peer);
    427     }
    428     device_tracker_remove(tracker);
    429     delete tracker;
    430 }
    431 
    432 static int device_tracker_enqueue(asocket* socket, std::string) {
    433     /* you can't read from a device tracker, close immediately */
    434     device_tracker_close(socket);
    435     return -1;
    436 }
    437 
    438 static int device_tracker_send(device_tracker* tracker, const std::string& string) {
    439     asocket* peer = tracker->socket.peer;
    440 
    441     std::string data;
    442     data.resize(4 + string.size());
    443     char buf[5];
    444     snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
    445     memcpy(&data[0], buf, 4);
    446     memcpy(&data[4], string.data(), string.size());
    447     return peer->enqueue(peer, std::move(data));
    448 }
    449 
    450 static void device_tracker_ready(asocket* socket) {
    451     device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
    452 
    453     // We want to send the device list when the tracker connects
    454     // for the first time, even if no update occurred.
    455     if (tracker->update_needed) {
    456         tracker->update_needed = false;
    457 
    458         std::string transports = list_transports(tracker->long_output);
    459         device_tracker_send(tracker, transports);
    460     }
    461 }
    462 
    463 asocket* create_device_tracker(bool long_output) {
    464     device_tracker* tracker = new device_tracker();
    465     if (tracker == nullptr) fatal("cannot allocate device tracker");
    466 
    467     D("device tracker %p created", tracker);
    468 
    469     tracker->socket.enqueue = device_tracker_enqueue;
    470     tracker->socket.ready = device_tracker_ready;
    471     tracker->socket.close = device_tracker_close;
    472     tracker->update_needed = true;
    473     tracker->long_output = long_output;
    474 
    475     tracker->next = device_tracker_list;
    476     device_tracker_list = tracker;
    477 
    478     return &tracker->socket;
    479 }
    480 
    481 // Check if all of the USB transports are connected.
    482 bool iterate_transports(std::function<bool(const atransport*)> fn) {
    483     std::lock_guard<std::recursive_mutex> lock(transport_lock);
    484     for (const auto& t : transport_list) {
    485         if (!fn(t)) {
    486             return false;
    487         }
    488     }
    489     for (const auto& t : pending_list) {
    490         if (!fn(t)) {
    491             return false;
    492         }
    493     }
    494     return true;
    495 }
    496 
    497 // Call this function each time the transport list has changed.
    498 void update_transports() {
    499     update_transport_status();
    500 
    501     // Notify `adb track-devices` clients.
    502     std::string transports = list_transports(false);
    503 
    504     device_tracker* tracker = device_tracker_list;
    505     while (tracker != nullptr) {
    506         device_tracker* next = tracker->next;
    507         // This may destroy the tracker if the connection is closed.
    508         device_tracker_send(tracker, transports);
    509         tracker = next;
    510     }
    511 }
    512 
    513 #else
    514 
    515 void update_transports() {
    516     // Nothing to do on the device side.
    517 }
    518 
    519 #endif  // ADB_HOST
    520 
    521 struct tmsg {
    522     atransport* transport;
    523     int action;
    524 };
    525 
    526 static int transport_read_action(int fd, struct tmsg* m) {
    527     char* p = (char*)m;
    528     int len = sizeof(*m);
    529     int r;
    530 
    531     while (len > 0) {
    532         r = adb_read(fd, p, len);
    533         if (r > 0) {
    534             len -= r;
    535             p += r;
    536         } else {
    537             D("transport_read_action: on fd %d: %s", fd, strerror(errno));
    538             return -1;
    539         }
    540     }
    541     return 0;
    542 }
    543 
    544 static int transport_write_action(int fd, struct tmsg* m) {
    545     char* p = (char*)m;
    546     int len = sizeof(*m);
    547     int r;
    548 
    549     while (len > 0) {
    550         r = adb_write(fd, p, len);
    551         if (r > 0) {
    552             len -= r;
    553             p += r;
    554         } else {
    555             D("transport_write_action: on fd %d: %s", fd, strerror(errno));
    556             return -1;
    557         }
    558     }
    559     return 0;
    560 }
    561 
    562 static void transport_registration_func(int _fd, unsigned ev, void* data) {
    563     tmsg m;
    564     int s[2];
    565     atransport* t;
    566 
    567     if (!(ev & FDE_READ)) {
    568         return;
    569     }
    570 
    571     if (transport_read_action(_fd, &m)) {
    572         fatal_errno("cannot read transport registration socket");
    573     }
    574 
    575     t = m.transport;
    576 
    577     if (m.action == 0) {
    578         D("transport: %s removing and free'ing %d", t->serial, t->transport_socket);
    579 
    580         /* IMPORTANT: the remove closes one half of the
    581         ** socket pair.  The close closes the other half.
    582         */
    583         fdevent_remove(&(t->transport_fde));
    584         adb_close(t->fd);
    585 
    586         {
    587             std::lock_guard<std::recursive_mutex> lock(transport_lock);
    588             transport_list.remove(t);
    589         }
    590 
    591         if (t->product) free(t->product);
    592         if (t->serial) free(t->serial);
    593         if (t->model) free(t->model);
    594         if (t->device) free(t->device);
    595         if (t->devpath) free(t->devpath);
    596 
    597         delete t;
    598 
    599         update_transports();
    600         return;
    601     }
    602 
    603     /* don't create transport threads for inaccessible devices */
    604     if (t->GetConnectionState() != kCsNoPerm) {
    605         /* initial references are the two threads */
    606         t->ref_count = 2;
    607 
    608         if (adb_socketpair(s)) {
    609             fatal_errno("cannot open transport socketpair");
    610         }
    611 
    612         D("transport: %s socketpair: (%d,%d) starting", t->serial, s[0], s[1]);
    613 
    614         t->transport_socket = s[0];
    615         t->fd = s[1];
    616 
    617         fdevent_install(&(t->transport_fde), t->transport_socket, transport_socket_events, t);
    618 
    619         fdevent_set(&(t->transport_fde), FDE_READ);
    620 
    621         std::thread(write_transport_thread, t).detach();
    622         std::thread(read_transport_thread, t).detach();
    623     }
    624 
    625     {
    626         std::lock_guard<std::recursive_mutex> lock(transport_lock);
    627         pending_list.remove(t);
    628         transport_list.push_front(t);
    629     }
    630 
    631     update_transports();
    632 }
    633 
    634 void init_transport_registration(void) {
    635     int s[2];
    636 
    637     if (adb_socketpair(s)) {
    638         fatal_errno("cannot open transport registration socketpair");
    639     }
    640     D("socketpair: (%d,%d)", s[0], s[1]);
    641 
    642     transport_registration_send = s[0];
    643     transport_registration_recv = s[1];
    644 
    645     fdevent_install(&transport_registration_fde, transport_registration_recv,
    646                     transport_registration_func, 0);
    647 
    648     fdevent_set(&transport_registration_fde, FDE_READ);
    649 }
    650 
    651 void kick_all_transports() {
    652     // To avoid only writing part of a packet to a transport after exit, kick all transports.
    653     std::lock_guard<std::recursive_mutex> lock(transport_lock);
    654     for (auto t : transport_list) {
    655         t->Kick();
    656     }
    657 }
    658 
    659 /* the fdevent select pump is single threaded */
    660 static void register_transport(atransport* transport) {
    661     tmsg m;
    662     m.transport = transport;
    663     m.action = 1;
    664     D("transport: %s registered", transport->serial);
    665     if (transport_write_action(transport_registration_send, &m)) {
    666         fatal_errno("cannot write transport registration socket\n");
    667     }
    668 }
    669 
    670 static void remove_transport(atransport* transport) {
    671     tmsg m;
    672     m.transport = transport;
    673     m.action = 0;
    674     D("transport: %s removed", transport->serial);
    675     if (transport_write_action(transport_registration_send, &m)) {
    676         fatal_errno("cannot write transport registration socket\n");
    677     }
    678 }
    679 
    680 static void transport_unref(atransport* t) {
    681     CHECK(t != nullptr);
    682 
    683     std::lock_guard<std::recursive_mutex> lock(transport_lock);
    684     CHECK_GT(t->ref_count, 0u);
    685     t->ref_count--;
    686     if (t->ref_count == 0) {
    687         D("transport: %s unref (kicking and closing)", t->serial);
    688         t->connection->Close();
    689         remove_transport(t);
    690     } else {
    691         D("transport: %s unref (count=%zu)", t->serial, t->ref_count);
    692     }
    693 }
    694 
    695 static int qual_match(const char* to_test, const char* prefix, const char* qual,
    696                       bool sanitize_qual) {
    697     if (!to_test || !*to_test) /* Return true if both the qual and to_test are null strings. */
    698         return !qual || !*qual;
    699 
    700     if (!qual) return 0;
    701 
    702     if (prefix) {
    703         while (*prefix) {
    704             if (*prefix++ != *to_test++) return 0;
    705         }
    706     }
    707 
    708     while (*qual) {
    709         char ch = *qual++;
    710         if (sanitize_qual && !isalnum(ch)) ch = '_';
    711         if (ch != *to_test++) return 0;
    712     }
    713 
    714     /* Everything matched so far.  Return true if *to_test is a NUL. */
    715     return !*to_test;
    716 }
    717 
    718 atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
    719                                   bool* is_ambiguous, std::string* error_out,
    720                                   bool accept_any_state) {
    721     atransport* result = nullptr;
    722 
    723     if (transport_id != 0) {
    724         *error_out =
    725             android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
    726     } else if (serial) {
    727         *error_out = android::base::StringPrintf("device '%s' not found", serial);
    728     } else if (type == kTransportLocal) {
    729         *error_out = "no emulators found";
    730     } else if (type == kTransportAny) {
    731         *error_out = "no devices/emulators found";
    732     } else {
    733         *error_out = "no devices found";
    734     }
    735 
    736     std::unique_lock<std::recursive_mutex> lock(transport_lock);
    737     for (const auto& t : transport_list) {
    738         if (t->GetConnectionState() == kCsNoPerm) {
    739 #if ADB_HOST
    740             *error_out = UsbNoPermissionsLongHelpText();
    741 #endif
    742             continue;
    743         }
    744 
    745         if (transport_id) {
    746             if (t->id == transport_id) {
    747                 result = t;
    748                 break;
    749             }
    750         } else if (serial) {
    751             if (t->MatchesTarget(serial)) {
    752                 if (result) {
    753                     *error_out = "more than one device";
    754                     if (is_ambiguous) *is_ambiguous = true;
    755                     result = nullptr;
    756                     break;
    757                 }
    758                 result = t;
    759             }
    760         } else {
    761             if (type == kTransportUsb && t->type == kTransportUsb) {
    762                 if (result) {
    763                     *error_out = "more than one device";
    764                     if (is_ambiguous) *is_ambiguous = true;
    765                     result = nullptr;
    766                     break;
    767                 }
    768                 result = t;
    769             } else if (type == kTransportLocal && t->type == kTransportLocal) {
    770                 if (result) {
    771                     *error_out = "more than one emulator";
    772                     if (is_ambiguous) *is_ambiguous = true;
    773                     result = nullptr;
    774                     break;
    775                 }
    776                 result = t;
    777             } else if (type == kTransportAny) {
    778                 if (result) {
    779                     *error_out = "more than one device/emulator";
    780                     if (is_ambiguous) *is_ambiguous = true;
    781                     result = nullptr;
    782                     break;
    783                 }
    784                 result = t;
    785             }
    786         }
    787     }
    788     lock.unlock();
    789 
    790     // Don't return unauthorized devices; the caller can't do anything with them.
    791     if (result && result->GetConnectionState() == kCsUnauthorized && !accept_any_state) {
    792         *error_out = "device unauthorized.\n";
    793         char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
    794         *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
    795         *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
    796         *error_out += "\n";
    797         *error_out += "Try 'adb kill-server' if that seems wrong.\n";
    798         *error_out += "Otherwise check for a confirmation dialog on your device.";
    799         result = nullptr;
    800     }
    801 
    802     // Don't return offline devices; the caller can't do anything with them.
    803     if (result && result->GetConnectionState() == kCsOffline && !accept_any_state) {
    804         *error_out = "device offline";
    805         result = nullptr;
    806     }
    807 
    808     if (result) {
    809         *error_out = "success";
    810     }
    811 
    812     return result;
    813 }
    814 
    815 int atransport::Write(apacket* p) {
    816     return this->connection->Write(p) ? 0 : -1;
    817 }
    818 
    819 void atransport::Kick() {
    820     if (!kicked_) {
    821         D("kicking transport %s", this->serial);
    822         kicked_ = true;
    823         this->connection->Close();
    824     }
    825 }
    826 
    827 ConnectionState atransport::GetConnectionState() const {
    828     return connection_state_;
    829 }
    830 
    831 void atransport::SetConnectionState(ConnectionState state) {
    832     check_main_thread();
    833     connection_state_ = state;
    834 }
    835 
    836 const std::string atransport::connection_state_name() const {
    837     ConnectionState state = GetConnectionState();
    838     switch (state) {
    839         case kCsOffline:
    840             return "offline";
    841         case kCsBootloader:
    842             return "bootloader";
    843         case kCsDevice:
    844             return "device";
    845         case kCsHost:
    846             return "host";
    847         case kCsRecovery:
    848             return "recovery";
    849         case kCsNoPerm:
    850             return UsbNoPermissionsShortHelpText();
    851         case kCsSideload:
    852             return "sideload";
    853         case kCsUnauthorized:
    854             return "unauthorized";
    855         default:
    856             return "unknown";
    857     }
    858 }
    859 
    860 void atransport::update_version(int version, size_t payload) {
    861     protocol_version = std::min(version, A_VERSION);
    862     max_payload = std::min(payload, MAX_PAYLOAD);
    863 }
    864 
    865 int atransport::get_protocol_version() const {
    866     return protocol_version;
    867 }
    868 
    869 size_t atransport::get_max_payload() const {
    870     return max_payload;
    871 }
    872 
    873 namespace {
    874 
    875 constexpr char kFeatureStringDelimiter = ',';
    876 
    877 }  // namespace
    878 
    879 const FeatureSet& supported_features() {
    880     // Local static allocation to avoid global non-POD variables.
    881     static const FeatureSet* features = new FeatureSet{
    882         kFeatureShell2, kFeatureCmd, kFeatureStat2,
    883         // Increment ADB_SERVER_VERSION whenever the feature list changes to
    884         // make sure that the adb client and server features stay in sync
    885         // (http://b/24370690).
    886     };
    887 
    888     return *features;
    889 }
    890 
    891 std::string FeatureSetToString(const FeatureSet& features) {
    892     return android::base::Join(features, kFeatureStringDelimiter);
    893 }
    894 
    895 FeatureSet StringToFeatureSet(const std::string& features_string) {
    896     if (features_string.empty()) {
    897         return FeatureSet();
    898     }
    899 
    900     auto names = android::base::Split(features_string, {kFeatureStringDelimiter});
    901     return FeatureSet(names.begin(), names.end());
    902 }
    903 
    904 bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
    905     return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
    906 }
    907 
    908 bool atransport::has_feature(const std::string& feature) const {
    909     return features_.count(feature) > 0;
    910 }
    911 
    912 void atransport::SetFeatures(const std::string& features_string) {
    913     features_ = StringToFeatureSet(features_string);
    914 }
    915 
    916 void atransport::AddDisconnect(adisconnect* disconnect) {
    917     disconnects_.push_back(disconnect);
    918 }
    919 
    920 void atransport::RemoveDisconnect(adisconnect* disconnect) {
    921     disconnects_.remove(disconnect);
    922 }
    923 
    924 void atransport::RunDisconnects() {
    925     for (const auto& disconnect : disconnects_) {
    926         disconnect->func(disconnect->opaque, this);
    927     }
    928     disconnects_.clear();
    929 }
    930 
    931 bool atransport::MatchesTarget(const std::string& target) const {
    932     if (serial) {
    933         if (target == serial) {
    934             return true;
    935         } else if (type == kTransportLocal) {
    936             // Local transports can match [tcp:|udp:]<hostname>[:port].
    937             const char* local_target_ptr = target.c_str();
    938 
    939             // For fastboot compatibility, ignore protocol prefixes.
    940             if (android::base::StartsWith(target, "tcp:") ||
    941                 android::base::StartsWith(target, "udp:")) {
    942                 local_target_ptr += 4;
    943             }
    944 
    945             // Parse our |serial| and the given |target| to check if the hostnames and ports match.
    946             std::string serial_host, error;
    947             int serial_port = -1;
    948             if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
    949                 // |target| may omit the port to default to ours.
    950                 std::string target_host;
    951                 int target_port = serial_port;
    952                 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
    953                                                    nullptr, &error) &&
    954                     serial_host == target_host && serial_port == target_port) {
    955                     return true;
    956                 }
    957             }
    958         }
    959     }
    960 
    961     return (devpath && target == devpath) ||
    962            qual_match(target.c_str(), "product:", product, false) ||
    963            qual_match(target.c_str(), "model:", model, true) ||
    964            qual_match(target.c_str(), "device:", device, false);
    965 }
    966 
    967 #if ADB_HOST
    968 
    969 // We use newline as our delimiter, make sure to never output it.
    970 static std::string sanitize(std::string str, bool alphanumeric) {
    971     auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
    972                              : [](const char c) { return c == '\n'; };
    973     std::replace_if(str.begin(), str.end(), pred, '_');
    974     return str;
    975 }
    976 
    977 static void append_transport_info(std::string* result, const char* key, const char* value,
    978                                   bool alphanumeric) {
    979     if (value == nullptr || *value == '\0') {
    980         return;
    981     }
    982 
    983     *result += ' ';
    984     *result += key;
    985     *result += sanitize(value, alphanumeric);
    986 }
    987 
    988 static void append_transport(const atransport* t, std::string* result, bool long_listing) {
    989     const char* serial = t->serial;
    990     if (!serial || !serial[0]) {
    991         serial = "(no serial number)";
    992     }
    993 
    994     if (!long_listing) {
    995         *result += serial;
    996         *result += '\t';
    997         *result += t->connection_state_name();
    998     } else {
    999         android::base::StringAppendF(result, "%-22s %s", serial, t->connection_state_name().c_str());
   1000 
   1001         append_transport_info(result, "", t->devpath, false);
   1002         append_transport_info(result, "product:", t->product, false);
   1003         append_transport_info(result, "model:", t->model, true);
   1004         append_transport_info(result, "device:", t->device, false);
   1005 
   1006         // Put id at the end, so that anyone parsing the output here can always find it by scanning
   1007         // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
   1008         *result += " transport_id:";
   1009         *result += std::to_string(t->id);
   1010     }
   1011     *result += '\n';
   1012 }
   1013 
   1014 std::string list_transports(bool long_listing) {
   1015     std::lock_guard<std::recursive_mutex> lock(transport_lock);
   1016 
   1017     auto sorted_transport_list = transport_list;
   1018     sorted_transport_list.sort([](atransport*& x, atransport*& y) {
   1019         if (x->type != y->type) {
   1020             return x->type < y->type;
   1021         }
   1022         return strcmp(x->serial, y->serial) < 0;
   1023     });
   1024 
   1025     std::string result;
   1026     for (const auto& t : sorted_transport_list) {
   1027         append_transport(t, &result, long_listing);
   1028     }
   1029     return result;
   1030 }
   1031 
   1032 void close_usb_devices(std::function<bool(const atransport*)> predicate) {
   1033     std::lock_guard<std::recursive_mutex> lock(transport_lock);
   1034     for (auto& t : transport_list) {
   1035         if (predicate(t)) {
   1036             t->Kick();
   1037         }
   1038     }
   1039 }
   1040 
   1041 /* hack for osx */
   1042 void close_usb_devices() {
   1043     close_usb_devices([](const atransport*) { return true; });
   1044 }
   1045 #endif  // ADB_HOST
   1046 
   1047 int register_socket_transport(int s, const char* serial, int port, int local) {
   1048     atransport* t = new atransport();
   1049 
   1050     if (!serial) {
   1051         char buf[32];
   1052         snprintf(buf, sizeof(buf), "T-%p", t);
   1053         serial = buf;
   1054     }
   1055 
   1056     D("transport: %s init'ing for socket %d, on port %d", serial, s, port);
   1057     if (init_socket_transport(t, s, port, local) < 0) {
   1058         delete t;
   1059         return -1;
   1060     }
   1061 
   1062     std::unique_lock<std::recursive_mutex> lock(transport_lock);
   1063     for (const auto& transport : pending_list) {
   1064         if (transport->serial && strcmp(serial, transport->serial) == 0) {
   1065             VLOG(TRANSPORT) << "socket transport " << transport->serial
   1066                             << " is already in pending_list and fails to register";
   1067             delete t;
   1068             return -1;
   1069         }
   1070     }
   1071 
   1072     for (const auto& transport : transport_list) {
   1073         if (transport->serial && strcmp(serial, transport->serial) == 0) {
   1074             VLOG(TRANSPORT) << "socket transport " << transport->serial
   1075                             << " is already in transport_list and fails to register";
   1076             delete t;
   1077             return -1;
   1078         }
   1079     }
   1080 
   1081     pending_list.push_front(t);
   1082     t->serial = strdup(serial);
   1083 
   1084     lock.unlock();
   1085 
   1086     register_transport(t);
   1087     return 0;
   1088 }
   1089 
   1090 #if ADB_HOST
   1091 atransport* find_transport(const char* serial) {
   1092     atransport* result = nullptr;
   1093 
   1094     std::lock_guard<std::recursive_mutex> lock(transport_lock);
   1095     for (auto& t : transport_list) {
   1096         if (t->serial && strcmp(serial, t->serial) == 0) {
   1097             result = t;
   1098             break;
   1099         }
   1100     }
   1101 
   1102     return result;
   1103 }
   1104 
   1105 void kick_all_tcp_devices() {
   1106     std::lock_guard<std::recursive_mutex> lock(transport_lock);
   1107     for (auto& t : transport_list) {
   1108         if (t->IsTcpDevice()) {
   1109             // Kicking breaks the read_transport thread of this transport out of any read, then
   1110             // the read_transport thread will notify the main thread to make this transport
   1111             // offline. Then the main thread will notify the write_transport thread to exit.
   1112             // Finally, this transport will be closed and freed in the main thread.
   1113             t->Kick();
   1114         }
   1115     }
   1116 }
   1117 
   1118 #endif
   1119 
   1120 void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
   1121                             unsigned writeable) {
   1122     atransport* t = new atransport((writeable ? kCsOffline : kCsNoPerm));
   1123 
   1124     D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
   1125     init_usb_transport(t, usb);
   1126     if (serial) {
   1127         t->serial = strdup(serial);
   1128     }
   1129 
   1130     if (devpath) {
   1131         t->devpath = strdup(devpath);
   1132     }
   1133 
   1134     {
   1135         std::lock_guard<std::recursive_mutex> lock(transport_lock);
   1136         pending_list.push_front(t);
   1137     }
   1138 
   1139     register_transport(t);
   1140 }
   1141 
   1142 // This should only be used for transports with connection_state == kCsNoPerm.
   1143 void unregister_usb_transport(usb_handle* usb) {
   1144     std::lock_guard<std::recursive_mutex> lock(transport_lock);
   1145     transport_list.remove_if([usb](atransport* t) {
   1146         if (auto connection = dynamic_cast<UsbConnection*>(t->connection.get())) {
   1147             return connection->handle_ == usb && t->GetConnectionState() == kCsNoPerm;
   1148         }
   1149         return false;
   1150     });
   1151 }
   1152 
   1153 bool check_header(apacket* p, atransport* t) {
   1154     if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
   1155         VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
   1156                   << ", magic = " << p->msg.magic;
   1157         return false;
   1158     }
   1159 
   1160     if (p->msg.data_length > t->get_max_payload()) {
   1161         VLOG(RWX) << "check_header(): " << p->msg.data_length
   1162                   << " atransport::max_payload = " << t->get_max_payload();
   1163         return false;
   1164     }
   1165 
   1166     return true;
   1167 }
   1168 
   1169 #if ADB_HOST
   1170 std::shared_ptr<RSA> atransport::NextKey() {
   1171     if (keys_.empty()) keys_ = adb_auth_get_private_keys();
   1172 
   1173     std::shared_ptr<RSA> result = keys_[0];
   1174     keys_.pop_front();
   1175     return result;
   1176 }
   1177 #endif
   1178