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