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