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