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