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