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