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