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