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 
21 #include "transport.h"
22 
23 #include <ctype.h>
24 #include <errno.h>
25 #include <inttypes.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30 
31 #include <algorithm>
32 #include <list>
33 #include <memory>
34 #include <mutex>
35 #include <set>
36 #include <string>
37 #include <thread>
38 
39 #include <adb/crypto/rsa_2048_key.h>
40 #include <adb/crypto/x509_generator.h>
41 #include <adb/tls/tls_connection.h>
42 #include <android-base/logging.h>
43 #include <android-base/no_destructor.h>
44 #include <android-base/parsenetaddress.h>
45 #include <android-base/stringprintf.h>
46 #include <android-base/strings.h>
47 #include <android-base/thread_annotations.h>
48 #include <diagnose_usb.h>
49 
50 #include "adb.h"
51 #include "adb_auth.h"
52 #include "adb_io.h"
53 #include "adb_trace.h"
54 #include "adb_utils.h"
55 #include "fdevent/fdevent.h"
56 #include "sysdeps/chrono.h"
57 
58 #if ADB_HOST
59 #include <google/protobuf/text_format.h>
60 #include "client/usb.h"
61 #include "devices.pb.h"
62 #endif
63 
64 using namespace adb::crypto;
65 using namespace adb::tls;
66 using namespace std::string_literals;
67 using android::base::ScopedLockAssertion;
68 using TlsError = TlsConnection::TlsError;
69 
70 static void remove_transport(atransport* transport);
71 static void transport_destroy(atransport* transport);
72 
73 // TODO: unordered_map<TransportId, atransport*>
74 static auto& transport_list = *new std::list<atransport*>();
75 static auto& pending_list = *new std::list<atransport*>();
76 
77 static auto& transport_lock = *new std::recursive_mutex();
78 
79 const char* const kFeatureShell2 = "shell_v2";
80 const char* const kFeatureCmd = "cmd";
81 const char* const kFeatureStat2 = "stat_v2";
82 const char* const kFeatureLs2 = "ls_v2";
83 const char* const kFeatureLibusb = "libusb";
84 const char* const kFeaturePushSync = "push_sync";
85 const char* const kFeatureApex = "apex";
86 const char* const kFeatureFixedPushMkdir = "fixed_push_mkdir";
87 const char* const kFeatureAbb = "abb";
88 const char* const kFeatureFixedPushSymlinkTimestamp = "fixed_push_symlink_timestamp";
89 const char* const kFeatureAbbExec = "abb_exec";
90 const char* const kFeatureRemountShell = "remount_shell";
91 const char* const kFeatureTrackApp = "track_app";
92 const char* const kFeatureSendRecv2 = "sendrecv_v2";
93 const char* const kFeatureSendRecv2Brotli = "sendrecv_v2_brotli";
94 const char* const kFeatureSendRecv2LZ4 = "sendrecv_v2_lz4";
95 const char* const kFeatureSendRecv2Zstd = "sendrecv_v2_zstd";
96 const char* const kFeatureSendRecv2DryRunSend = "sendrecv_v2_dry_run_send";
97 const char* const kFeatureDelayedAck = "delayed_ack";
98 // TODO(joshuaduong): Bump to v2 when openscreen discovery is enabled by default
99 const char* const kFeatureOpenscreenMdns = "openscreen_mdns";
100 const char* const kFeatureDeviceTrackerProtoFormat = "devicetracker_proto_format";
101 const char* const kFeatureDevRaw = "devraw";
102 const char* const kFeatureAppInfo = "app_info";  // Add information to track-app (package name, ...)
103 
104 namespace {
105 
106 #if ADB_HOST
107 
108 // Tracks and handles atransport*s that are attempting reconnection.
109 class ReconnectHandler {
110   public:
111     ReconnectHandler() = default;
112     ~ReconnectHandler() = default;
113 
114     // Starts the ReconnectHandler thread.
115     void Start();
116 
117     // Requests the ReconnectHandler thread to stop.
118     void Stop();
119 
120     // Adds the atransport* to the queue of reconnect attempts.
121     void TrackTransport(atransport* transport);
122 
123     // Wake up the ReconnectHandler thread to have it check for kicked transports.
124     void CheckForKicked();
125 
126   private:
127     // The main thread loop.
128     void Run();
129 
130     // Tracks a reconnection attempt.
131     struct ReconnectAttempt {
132         atransport* transport;
133         std::chrono::steady_clock::time_point reconnect_time;
134         size_t attempts_left;
135 
operator <__anon85428b290111::ReconnectHandler::ReconnectAttempt136         bool operator<(const ReconnectAttempt& rhs) const {
137             if (reconnect_time == rhs.reconnect_time) {
138                 return reinterpret_cast<uintptr_t>(transport) <
139                        reinterpret_cast<uintptr_t>(rhs.transport);
140             }
141             return reconnect_time < rhs.reconnect_time;
142         }
143     };
144 
145     // Only retry for up to one minute.
146     static constexpr const std::chrono::seconds kDefaultTimeout = 3s;
147     static constexpr const size_t kMaxAttempts = 20;
148 
149     // Protects all members.
150     std::mutex reconnect_mutex_;
151     bool running_ GUARDED_BY(reconnect_mutex_) = true;
152     std::thread handler_thread_;
153     std::condition_variable reconnect_cv_;
154     std::set<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
155 
156     DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
157 };
158 
Start()159 void ReconnectHandler::Start() {
160     fdevent_check_looper();
161     handler_thread_ = std::thread(&ReconnectHandler::Run, this);
162 }
163 
Stop()164 void ReconnectHandler::Stop() {
165     fdevent_check_looper();
166     {
167         std::lock_guard<std::mutex> lock(reconnect_mutex_);
168         running_ = false;
169     }
170     reconnect_cv_.notify_one();
171     handler_thread_.join();
172 
173     // Drain the queue to free all resources.
174     std::lock_guard<std::mutex> lock(reconnect_mutex_);
175     while (!reconnect_queue_.empty()) {
176         ReconnectAttempt attempt = *reconnect_queue_.begin();
177         reconnect_queue_.erase(reconnect_queue_.begin());
178         remove_transport(attempt.transport);
179     }
180 }
181 
TrackTransport(atransport * transport)182 void ReconnectHandler::TrackTransport(atransport* transport) {
183     fdevent_check_looper();
184     {
185         std::lock_guard<std::mutex> lock(reconnect_mutex_);
186         if (!running_) return;
187         // Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
188         auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
189         reconnect_queue_.emplace(
190                 ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
191     }
192     reconnect_cv_.notify_one();
193 }
194 
CheckForKicked()195 void ReconnectHandler::CheckForKicked() {
196     reconnect_cv_.notify_one();
197 }
198 
Run()199 void ReconnectHandler::Run() {
200     while (true) {
201         ReconnectAttempt attempt;
202         {
203             std::unique_lock<std::mutex> lock(reconnect_mutex_);
204             ScopedLockAssertion assume_lock(reconnect_mutex_);
205 
206             if (!reconnect_queue_.empty()) {
207                 // FIXME: libstdc++ (used on Windows) implements condition_variable with
208                 //        system_clock as its clock, so we're probably hosed if the clock changes,
209                 //        even if we use steady_clock throughout. This problem goes away once we
210                 //        switch to libc++.
211                 reconnect_cv_.wait_until(lock, reconnect_queue_.begin()->reconnect_time);
212             } else {
213                 reconnect_cv_.wait(lock);
214             }
215 
216             if (!running_) return;
217 
218             // Scan the whole list for kicked transports, so that we immediately handle an explicit
219             // disconnect request.
220             for (auto it = reconnect_queue_.begin(); it != reconnect_queue_.end();) {
221                 if (it->transport->kicked()) {
222                     D("transport %s was kicked. giving up on it.", it->transport->serial.c_str());
223                     remove_transport(it->transport);
224                     it = reconnect_queue_.erase(it);
225                 } else {
226                     ++it;
227                 }
228             }
229 
230             if (reconnect_queue_.empty()) continue;
231 
232             // Go back to sleep if we either woke up spuriously, or we were woken up to remove
233             // a kicked transport, and the first transport isn't ready for reconnection yet.
234             auto now = std::chrono::steady_clock::now();
235             if (reconnect_queue_.begin()->reconnect_time > now) {
236                 continue;
237             }
238 
239             attempt = *reconnect_queue_.begin();
240             reconnect_queue_.erase(reconnect_queue_.begin());
241         }
242         D("attempting to reconnect %s", attempt.transport->serial.c_str());
243 
244         switch (attempt.transport->Reconnect()) {
245             case ReconnectResult::Retry: {
246                 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
247                 if (attempt.attempts_left == 0) {
248                     D("transport %s exceeded the number of retry attempts. giving up on it.",
249                       attempt.transport->serial.c_str());
250                     remove_transport(attempt.transport);
251                     continue;
252                 }
253 
254                 std::lock_guard<std::mutex> lock(reconnect_mutex_);
255                 reconnect_queue_.emplace(ReconnectAttempt{
256                         attempt.transport,
257                         std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
258                         attempt.attempts_left - 1});
259                 continue;
260             }
261 
262             case ReconnectResult::Success:
263                 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
264                 register_transport(attempt.transport);
265                 continue;
266 
267             case ReconnectResult::Abort:
268                 D("cancelling reconnection attempt to %s.", attempt.transport->serial.c_str());
269                 remove_transport(attempt.transport);
270                 continue;
271         }
272     }
273 }
274 
275 static auto& reconnect_handler = *new ReconnectHandler();
276 
277 #endif
278 
279 }  // namespace
280 
NextTransportId()281 TransportId NextTransportId() {
282     static std::atomic<TransportId> next(1);
283     return next++;
284 }
285 
Reset()286 void Connection::Reset() {
287     LOG(INFO) << "Connection::Reset(): stopping";
288     Stop();
289 }
290 
Serial() const291 std::string Connection::Serial() const {
292     return transport_ ? transport_->serial_name() : "<unknown>";
293 }
294 
BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)295 BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
296     : underlying_(std::move(connection)) {}
297 
~BlockingConnectionAdapter()298 BlockingConnectionAdapter::~BlockingConnectionAdapter() {
299     LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): destructing";
300     Stop();
301 }
302 
Start()303 void BlockingConnectionAdapter::Start() {
304     std::lock_guard<std::mutex> lock(mutex_);
305     if (started_) {
306         LOG(FATAL) << "BlockingConnectionAdapter(" << Serial() << "): started multiple times";
307     }
308 
309     StartReadThread();
310 
311     write_thread_ = std::thread([this]() {
312         LOG(INFO) << Serial() << ": write thread spawning";
313         while (true) {
314             std::unique_lock<std::mutex> lock(mutex_);
315             ScopedLockAssertion assume_locked(mutex_);
316             cv_.wait(lock, [this]() REQUIRES(mutex_) {
317                 return this->stopped_ || !this->write_queue_.empty();
318             });
319 
320             if (this->stopped_) {
321                 return;
322             }
323 
324             std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
325             this->write_queue_.pop_front();
326             lock.unlock();
327 
328             if (!this->underlying_->Write(packet.get())) {
329                 break;
330             }
331         }
332         std::call_once(this->error_flag_, [this]() { transport_->HandleError("write failed"); });
333     });
334 
335     started_ = true;
336 }
337 
StartReadThread()338 void BlockingConnectionAdapter::StartReadThread() {
339     read_thread_ = std::thread([this]() {
340         LOG(INFO) << Serial() << ": read thread spawning";
341         while (true) {
342             auto packet = std::make_unique<apacket>();
343             if (!underlying_->Read(packet.get())) {
344                 PLOG(INFO) << Serial() << ": read failed";
345                 break;
346             }
347 
348             bool got_stls_cmd = false;
349             if (packet->msg.command == A_STLS) {
350                 got_stls_cmd = true;
351             }
352 
353             transport_->HandleRead(std::move(packet));
354 
355             // If we received the STLS packet, we are about to perform the TLS
356             // handshake. So this read thread must stop and resume after the
357             // handshake completes otherwise this will interfere in the process.
358             if (got_stls_cmd) {
359                 LOG(INFO) << Serial() << ": Received STLS packet. Stopping read thread.";
360                 return;
361             }
362         }
363         std::call_once(this->error_flag_, [this]() { transport_->HandleError("read failed"); });
364     });
365 }
366 
DoTlsHandshake(RSA * key,std::string * auth_key)367 bool BlockingConnectionAdapter::DoTlsHandshake(RSA* key, std::string* auth_key) {
368     std::lock_guard<std::mutex> lock(mutex_);
369     if (read_thread_.joinable()) {
370         read_thread_.join();
371     }
372     bool success = this->underlying_->DoTlsHandshake(key, auth_key);
373     StartReadThread();
374     return success;
375 }
376 
Reset()377 void BlockingConnectionAdapter::Reset() {
378     {
379         std::lock_guard<std::mutex> lock(mutex_);
380         if (!started_) {
381             LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): not started";
382             return;
383         }
384 
385         if (stopped_) {
386             LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): already stopped";
387             return;
388         }
389     }
390 
391     LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): resetting";
392     this->underlying_->Reset();
393     Stop();
394 }
395 
Stop()396 void BlockingConnectionAdapter::Stop() {
397     {
398         std::lock_guard<std::mutex> lock(mutex_);
399         if (!started_) {
400             LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): not started";
401             return;
402         }
403 
404         if (stopped_) {
405             LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): already stopped";
406             return;
407         }
408 
409         stopped_ = true;
410     }
411 
412     LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): stopping";
413 
414     this->underlying_->Close();
415     this->cv_.notify_one();
416 
417     // Move the threads out into locals with the lock taken, and then unlock to let them exit.
418     std::thread read_thread;
419     std::thread write_thread;
420 
421     {
422         std::lock_guard<std::mutex> lock(mutex_);
423         read_thread = std::move(read_thread_);
424         write_thread = std::move(write_thread_);
425     }
426 
427     read_thread.join();
428     write_thread.join();
429 
430     LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): stopped";
431     std::call_once(this->error_flag_, [this]() { transport_->HandleError("requested stop"); });
432 }
433 
Write(std::unique_ptr<apacket> packet)434 bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
435     {
436         std::lock_guard<std::mutex> lock(this->mutex_);
437         write_queue_.emplace_back(std::move(packet));
438     }
439 
440     cv_.notify_one();
441     return true;
442 }
443 
FdConnection(unique_fd fd)444 FdConnection::FdConnection(unique_fd fd) : fd_(std::move(fd)) {}
445 
~FdConnection()446 FdConnection::~FdConnection() {}
447 
DispatchRead(void * buf,size_t len)448 bool FdConnection::DispatchRead(void* buf, size_t len) {
449     if (tls_ != nullptr) {
450         // The TlsConnection doesn't allow 0 byte reads
451         if (len == 0) {
452             return true;
453         }
454         return tls_->ReadFully(buf, len);
455     }
456 
457     return ReadFdExactly(fd_.get(), buf, len);
458 }
459 
DispatchWrite(void * buf,size_t len)460 bool FdConnection::DispatchWrite(void* buf, size_t len) {
461     if (tls_ != nullptr) {
462         // The TlsConnection doesn't allow 0 byte writes
463         if (len == 0) {
464             return true;
465         }
466         return tls_->WriteFully(std::string_view(reinterpret_cast<const char*>(buf), len));
467     }
468 
469     return WriteFdExactly(fd_.get(), buf, len);
470 }
471 
Read(apacket * packet)472 bool FdConnection::Read(apacket* packet) {
473     if (!DispatchRead(&packet->msg, sizeof(amessage))) {
474         D("remote local: read terminated (message)");
475         return false;
476     }
477 
478     if (packet->msg.data_length > MAX_PAYLOAD) {
479         D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
480         return false;
481     }
482 
483     packet->payload.resize(packet->msg.data_length);
484 
485     if (!DispatchRead(&packet->payload[0], packet->payload.size())) {
486         D("remote local: terminated (data)");
487         return false;
488     }
489 
490     return true;
491 }
492 
Write(apacket * packet)493 bool FdConnection::Write(apacket* packet) {
494     if (!DispatchWrite(&packet->msg, sizeof(packet->msg))) {
495         D("remote local: write terminated");
496         return false;
497     }
498 
499     if (packet->msg.data_length) {
500         if (!DispatchWrite(&packet->payload[0], packet->msg.data_length)) {
501             D("remote local: write terminated");
502             return false;
503         }
504     }
505 
506     return true;
507 }
508 
DoTlsHandshake(RSA * key,std::string * auth_key)509 bool FdConnection::DoTlsHandshake(RSA* key, std::string* auth_key) {
510     bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
511     if (!EVP_PKEY_set1_RSA(evp_pkey.get(), key)) {
512         LOG(ERROR) << "EVP_PKEY_set1_RSA failed";
513         return false;
514     }
515     auto x509 = GenerateX509Certificate(evp_pkey.get());
516     auto x509_str = X509ToPEMString(x509.get());
517     auto evp_str = Key::ToPEMString(evp_pkey.get());
518 
519     int osh = cast_handle_to_int(adb_get_os_handle(fd_));
520 #if ADB_HOST
521     tls_ = TlsConnection::Create(TlsConnection::Role::Client, x509_str, evp_str, osh);
522 #else
523     tls_ = TlsConnection::Create(TlsConnection::Role::Server, x509_str, evp_str, osh);
524 #endif
525     CHECK(tls_);
526 #if ADB_HOST
527     // TLS 1.3 gives the client no message if the server rejected the
528     // certificate. This will enable a check in the tls connection to check
529     // whether the client certificate got rejected. Note that this assumes
530     // that, on handshake success, the server speaks first.
531     tls_->EnableClientPostHandshakeCheck(true);
532     // Add callback to set the certificate when server issues the
533     // CertificateRequest.
534     tls_->SetCertificateCallback(adb_tls_set_certificate);
535     // Allow any server certificate
536     tls_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
537 #else
538     // Add callback to check certificate against a list of known public keys
539     tls_->SetCertVerifyCallback(
540             [auth_key](X509_STORE_CTX* ctx) { return adbd_tls_verify_cert(ctx, auth_key); });
541     // Add the list of allowed client CA issuers
542     auto ca_list = adbd_tls_client_ca_list();
543     tls_->SetClientCAList(ca_list.get());
544 #endif
545 
546     auto err = tls_->DoHandshake();
547     if (err == TlsError::Success) {
548         return true;
549     }
550 
551     tls_.reset();
552     return false;
553 }
554 
Close()555 void FdConnection::Close() {
556     adb_shutdown(fd_.get());
557     fd_.reset();
558 }
559 
send_packet(apacket * p,atransport * t)560 void send_packet(apacket* p, atransport* t) {
561     p->msg.magic = p->msg.command ^ 0xffffffff;
562     // compute a checksum for connection/auth packets for compatibility reasons
563     if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
564         p->msg.data_check = 0;
565     } else {
566         p->msg.data_check = calculate_apacket_checksum(p);
567     }
568 
569     VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
570 
571     if (t == nullptr) {
572         LOG(FATAL) << "Transport is null";
573     }
574 
575     if (t->Write(p) != 0) {
576         D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
577         t->Kick();
578     }
579 }
580 
kick_transport(atransport * t,bool reset)581 void kick_transport(atransport* t, bool reset) {
582     std::lock_guard<std::recursive_mutex> lock(transport_lock);
583     // As kick_transport() can be called from threads without guarantee that t is valid,
584     // check if the transport is in transport_list first.
585     //
586     // TODO(jmgao): WTF? Is this actually true?
587     if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
588         if (reset) {
589             t->Reset();
590         } else {
591             t->Kick();
592         }
593     }
594 
595 #if ADB_HOST
596     reconnect_handler.CheckForKicked();
597 #endif
598 }
599 
600 #if ADB_HOST
601 
602 /* this adds support required by the 'track-devices' service.
603  * this is used to send the content of "list_transport" to any
604  * number of client connections that want it through a single
605  * live TCP connection
606  */
607 struct device_tracker {
608     asocket socket;
609     bool update_needed = false;
610     TrackerOutputType output_type = SHORT_TEXT;
611     device_tracker* next = nullptr;
612 };
613 
614 /* linked list of all device trackers */
615 static device_tracker* device_tracker_list;
616 
device_tracker_remove(device_tracker * tracker)617 static void device_tracker_remove(device_tracker* tracker) {
618     device_tracker** pnode = &device_tracker_list;
619     device_tracker* node = *pnode;
620 
621     std::lock_guard<std::recursive_mutex> lock(transport_lock);
622     while (node) {
623         if (node == tracker) {
624             *pnode = node->next;
625             break;
626         }
627         pnode = &node->next;
628         node = *pnode;
629     }
630 }
631 
device_tracker_close(asocket * socket)632 static void device_tracker_close(asocket* socket) {
633     device_tracker* tracker = (device_tracker*)socket;
634     asocket* peer = socket->peer;
635 
636     D("device tracker %p removed", tracker);
637     if (peer) {
638         peer->peer = nullptr;
639         peer->close(peer);
640     }
641     device_tracker_remove(tracker);
642     delete tracker;
643 }
644 
device_tracker_enqueue(asocket * socket,apacket::payload_type)645 static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
646     /* you can't read from a device tracker, close immediately */
647     device_tracker_close(socket);
648     return -1;
649 }
650 
device_tracker_send(device_tracker * tracker,const std::string & string)651 static int device_tracker_send(device_tracker* tracker, const std::string& string) {
652     asocket* peer = tracker->socket.peer;
653 
654     apacket::payload_type data;
655     data.resize(4 + string.size());
656     char buf[5];
657     snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
658     memcpy(&data[0], buf, 4);
659     memcpy(&data[4], string.data(), string.size());
660     return peer->enqueue(peer, std::move(data));
661 }
662 
device_tracker_ready(asocket * socket)663 static void device_tracker_ready(asocket* socket) {
664     device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
665 
666     // We want to send the device list when the tracker connects
667     // for the first time, even if no update occurred.
668     if (tracker->update_needed) {
669         tracker->update_needed = false;
670         device_tracker_send(tracker, list_transports(tracker->output_type));
671     }
672 }
673 
create_device_tracker(TrackerOutputType output_type)674 asocket* create_device_tracker(TrackerOutputType output_type) {
675     device_tracker* tracker = new device_tracker();
676     if (tracker == nullptr) LOG(FATAL) << "cannot allocate device tracker";
677 
678     D("device tracker %p created", tracker);
679 
680     tracker->socket.enqueue = device_tracker_enqueue;
681     tracker->socket.ready = device_tracker_ready;
682     tracker->socket.close = device_tracker_close;
683     tracker->update_needed = true;
684     tracker->output_type = output_type;
685 
686     tracker->next = device_tracker_list;
687     device_tracker_list = tracker;
688 
689     return &tracker->socket;
690 }
691 
692 // Check if all of the USB transports are connected.
iterate_transports(std::function<bool (const atransport *)> fn)693 bool iterate_transports(std::function<bool(const atransport*)> fn) {
694     std::lock_guard<std::recursive_mutex> lock(transport_lock);
695     for (const auto& t : transport_list) {
696         if (!fn(t)) {
697             return false;
698         }
699     }
700     for (const auto& t : pending_list) {
701         if (!fn(t)) {
702             return false;
703         }
704     }
705     return true;
706 }
707 
708 // Call this function each time the transport list has changed.
update_transports()709 void update_transports() {
710     update_transport_status();
711 
712     // Notify `adb track-devices` clients.
713     device_tracker* tracker = device_tracker_list;
714     while (tracker != nullptr) {
715         device_tracker* next = tracker->next;
716         // This may destroy the tracker if the connection is closed.
717         device_tracker_send(tracker, list_transports(tracker->output_type));
718         tracker = next;
719     }
720 }
721 
722 #else
723 
update_transports()724 void update_transports() {
725     // Nothing to do on the device side.
726 }
727 
728 #endif  // ADB_HOST
729 
730 #if ADB_HOST
usb_devices_start_detached()731 static bool usb_devices_start_detached() {
732     static const char* env = getenv("ADB_LIBUSB_START_DETACHED");
733     static bool result = env && strcmp("1", env) == 0;
734     return should_use_libusb() && result;
735 }
736 #endif
737 
fdevent_unregister_transport(atransport * t)738 static void fdevent_unregister_transport(atransport* t) {
739     D("transport: %s deleting", t->serial.c_str());
740 
741     {
742         std::lock_guard<std::recursive_mutex> lock(transport_lock);
743         transport_list.remove(t);
744     }
745 
746     delete t;
747 
748     update_transports();
749 }
750 
fdevent_register_transport(atransport * t)751 static void fdevent_register_transport(atransport* t) {
752     /* don't create transport threads for inaccessible devices */
753     if (t->GetConnectionState() != kCsNoPerm) {
754         t->connection()->SetTransport(t);
755 
756         if (t->type == kTransportUsb
757 #if ADB_HOST
758             && usb_devices_start_detached()  // -d setting propagated from the
759                                              // host device, hence n/a on-device.
760 #endif
761         ) {
762             t->SetConnectionState(kCsDetached);
763         } else {
764             t->connection()->Start();
765 #if ADB_HOST
766             send_connect(t);
767 #endif
768         }
769     }
770 
771     {
772         std::lock_guard<std::recursive_mutex> lock(transport_lock);
773         auto it = std::find(pending_list.begin(), pending_list.end(), t);
774         if (it != pending_list.end()) {
775             pending_list.remove(t);
776             transport_list.push_front(t);
777         }
778     }
779 
780     update_transports();
781 }
782 
783 #if ADB_HOST
init_reconnect_handler(void)784 void init_reconnect_handler(void) {
785     reconnect_handler.Start();
786 }
787 #endif
788 
kick_all_transports()789 void kick_all_transports() {
790 #if ADB_HOST
791     reconnect_handler.Stop();
792 #endif
793     // To avoid only writing part of a packet to a transport after exit, kick all transports.
794     std::lock_guard<std::recursive_mutex> lock(transport_lock);
795     for (auto t : transport_list) {
796         t->Kick();
797     }
798 }
799 
kick_all_tcp_tls_transports()800 void kick_all_tcp_tls_transports() {
801     std::lock_guard<std::recursive_mutex> lock(transport_lock);
802     for (auto t : transport_list) {
803         if (t->IsTcpDevice() && t->use_tls) {
804             t->Kick();
805         }
806     }
807 }
808 
809 #if !ADB_HOST
kick_all_transports_by_auth_key(std::string_view auth_key)810 void kick_all_transports_by_auth_key(std::string_view auth_key) {
811     std::lock_guard<std::recursive_mutex> lock(transport_lock);
812     for (auto t : transport_list) {
813         if (auth_key == t->auth_key) {
814             t->Kick();
815         }
816     }
817 }
818 #endif
819 
register_transport(atransport * transport)820 void register_transport(atransport* transport) {
821     D("transport: %s registered", transport->serial.c_str());
822     fdevent_run_on_looper([=]() { fdevent_register_transport(transport); });
823 }
824 
remove_transport(atransport * transport)825 static void remove_transport(atransport* transport) {
826     D("transport: %s removed", transport->serial.c_str());
827     fdevent_run_on_looper([=]() { fdevent_unregister_transport(transport); });
828 }
829 
transport_destroy(atransport * t)830 static void transport_destroy(atransport* t) {
831     fdevent_check_looper();
832     CHECK(t != nullptr);
833 
834     std::lock_guard<std::recursive_mutex> lock(transport_lock);
835     LOG(INFO) << "destroying transport " << t->serial_name();
836     t->connection()->Stop();
837 #if ADB_HOST
838     if (t->IsTcpDevice() && !t->kicked()) {
839         D("transport: %s destroy (attempting reconnection)", t->serial.c_str());
840 
841         // We need to clear the transport's keys, so that on the next connection, it tries
842         // again from the beginning.
843         t->ResetKeys();
844         reconnect_handler.TrackTransport(t);
845         return;
846     }
847 #endif
848 
849     D("transport: %s destroy (kicking and closing)", t->serial.c_str());
850     remove_transport(t);
851 }
852 
853 #if ADB_HOST
qual_match(const std::string & to_test,const char * prefix,const std::string & qual,bool sanitize_qual)854 static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
855                       bool sanitize_qual) {
856     if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
857         return qual.empty();
858 
859     if (qual.empty()) return 0;
860 
861     const char* ptr = to_test.c_str();
862     if (prefix) {
863         while (*prefix) {
864             if (*prefix++ != *ptr++) return 0;
865         }
866     }
867 
868     for (char ch : qual) {
869         if (sanitize_qual && !isalnum(ch)) ch = '_';
870         if (ch != *ptr++) return 0;
871     }
872 
873     /* Everything matched so far.  Return true if *ptr is a NUL. */
874     return !*ptr;
875 }
876 
877 // Contains either a device serial string or a USB device address like "usb:2-6"
878 const char* __transport_server_one_device = nullptr;
879 
transport_set_one_device(const char * adb_one_device)880 void transport_set_one_device(const char* adb_one_device) {
881     __transport_server_one_device = adb_one_device;
882 }
883 
transport_get_one_device()884 const char* transport_get_one_device() {
885     return __transport_server_one_device;
886 }
887 
transport_server_owns_device(std::string_view serial)888 bool transport_server_owns_device(std::string_view serial) {
889     if (!__transport_server_one_device) {
890         // If the server doesn't own one device, server owns all devices.
891         return true;
892     }
893     return serial.compare(__transport_server_one_device) == 0;
894 }
895 
transport_server_owns_device(std::string_view dev_path,std::string_view serial)896 bool transport_server_owns_device(std::string_view dev_path, std::string_view serial) {
897     if (!__transport_server_one_device) {
898         // If the server doesn't own one device, server owns all devices.
899         return true;
900     }
901     return serial.compare(__transport_server_one_device) == 0 ||
902            dev_path.compare(__transport_server_one_device) == 0;
903 }
904 
acquire_one_transport(TransportType type,const char * serial,TransportId transport_id,bool * is_ambiguous,std::string * error_out,bool accept_any_state)905 atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
906                                   bool* is_ambiguous, std::string* error_out,
907                                   bool accept_any_state) {
908     atransport* result = nullptr;
909 
910     if (transport_id != 0) {
911         *error_out = android::base::StringPrintf("no device with transport id '%" PRIu64 "'",
912                                                  transport_id);
913     } else if (serial) {
914         *error_out = android::base::StringPrintf("device '%s' not found", serial);
915     } else if (type == kTransportLocal) {
916         *error_out = "no emulators found";
917     } else if (type == kTransportAny) {
918         *error_out = "no devices/emulators found";
919     } else {
920         *error_out = "no devices found";
921     }
922 
923     std::unique_lock<std::recursive_mutex> lock(transport_lock);
924     for (const auto& t : transport_list) {
925         if (t->GetConnectionState() == kCsNoPerm) {
926             *error_out = UsbNoPermissionsLongHelpText();
927             continue;
928         }
929 
930         if (transport_id) {
931             if (t->id == transport_id) {
932                 result = t;
933                 break;
934             }
935         } else if (serial) {
936             if (t->MatchesTarget(serial)) {
937                 if (result) {
938                     *error_out = "more than one device with serial "s + serial;
939                     if (is_ambiguous) *is_ambiguous = true;
940                     result = nullptr;
941                     break;
942                 }
943                 result = t;
944             }
945         } else {
946             if (type == kTransportUsb && t->type == kTransportUsb) {
947                 if (result) {
948                     *error_out = "more than one USB device";
949                     if (is_ambiguous) *is_ambiguous = true;
950                     result = nullptr;
951                     break;
952                 }
953                 result = t;
954             } else if (type == kTransportLocal && t->type == kTransportLocal) {
955                 if (result) {
956                     *error_out = "more than one emulator";
957                     if (is_ambiguous) *is_ambiguous = true;
958                     result = nullptr;
959                     break;
960                 }
961                 result = t;
962             } else if (type == kTransportAny) {
963                 if (result) {
964                     *error_out = "more than one device/emulator";
965                     if (is_ambiguous) *is_ambiguous = true;
966                     result = nullptr;
967                     break;
968                 }
969                 result = t;
970             }
971         }
972     }
973     lock.unlock();
974 
975     if (result && !accept_any_state) {
976         // The caller requires an active transport.
977         // Make sure that we're actually connected.
978         ConnectionState state = result->GetConnectionState();
979         switch (state) {
980             case kCsConnecting:
981                 *error_out = "device still connecting";
982                 result = nullptr;
983                 break;
984 
985             case kCsAuthorizing:
986                 *error_out = "device still authorizing";
987                 result = nullptr;
988                 break;
989 
990             case kCsUnauthorized: {
991                 *error_out = "device unauthorized.\n";
992                 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
993                 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
994                 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
995                 *error_out += "\n";
996                 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
997                 *error_out += "Otherwise check for a confirmation dialog on your device.";
998                 result = nullptr;
999                 break;
1000             }
1001 
1002             case kCsOffline:
1003                 *error_out = "device offline";
1004                 result = nullptr;
1005                 break;
1006 
1007             default:
1008                 break;
1009         }
1010     }
1011 
1012     if (result) {
1013         *error_out = "success";
1014     }
1015 
1016     return result;
1017 }
1018 
WaitForConnection(std::chrono::milliseconds timeout)1019 bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
1020     std::unique_lock<std::mutex> lock(mutex_);
1021     ScopedLockAssertion assume_locked(mutex_);
1022     return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
1023         return connection_established_ready_;
1024     }) && connection_established_;
1025 }
1026 
SetConnectionEstablished(bool success)1027 void ConnectionWaitable::SetConnectionEstablished(bool success) {
1028     {
1029         std::lock_guard<std::mutex> lock(mutex_);
1030         if (connection_established_ready_) return;
1031         connection_established_ready_ = true;
1032         connection_established_ = success;
1033         D("connection established with %d", success);
1034     }
1035     cv_.notify_one();
1036 }
1037 #endif
1038 
~atransport()1039 atransport::~atransport() {
1040 #if ADB_HOST
1041     // If the connection callback had not been run before, run it now.
1042     SetConnectionEstablished(false);
1043 #endif
1044 }
1045 
Write(apacket * p)1046 int atransport::Write(apacket* p) {
1047     return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
1048 }
1049 
Reset()1050 void atransport::Reset() {
1051     if (!kicked_.exchange(true)) {
1052         LOG(INFO) << "resetting transport " << this << " " << this->serial;
1053         this->connection()->Reset();
1054     }
1055 }
1056 
Kick()1057 void atransport::Kick() {
1058     if (!kicked_.exchange(true)) {
1059         LOG(INFO) << "kicking transport " << this << " " << this->serial;
1060         this->connection()->Stop();
1061     }
1062 }
1063 
GetConnectionState() const1064 ConnectionState atransport::GetConnectionState() const {
1065     return connection_state_;
1066 }
1067 
SetConnectionState(ConnectionState state)1068 void atransport::SetConnectionState(ConnectionState state) {
1069     fdevent_check_looper();
1070     connection_state_ = state;
1071     update_transports();
1072 }
1073 
1074 #if ADB_HOST
Attach(std::string * error)1075 bool atransport::Attach(std::string* error) {
1076     D("%s: attach", serial.c_str());
1077     fdevent_check_looper();
1078 
1079     if (!should_use_libusb()) {
1080         *error = "attach/detach only implemented for libusb backend";
1081         return false;
1082     }
1083 
1084     if (GetConnectionState() != ConnectionState::kCsDetached) {
1085         *error = android::base::StringPrintf("transport %s is not detached", serial.c_str());
1086         return false;
1087     }
1088 
1089     ResetKeys();
1090 
1091     {
1092         std::lock_guard<std::mutex> lock(mutex_);
1093         if (!connection_->Attach(error)) {
1094             return false;
1095         }
1096     }
1097 
1098     send_connect(this);
1099     return true;
1100 }
1101 
Detach(std::string * error)1102 bool atransport::Detach(std::string* error) {
1103     D("%s: detach", serial.c_str());
1104     fdevent_check_looper();
1105 
1106     if (!should_use_libusb()) {
1107         *error = "attach/detach only implemented for libusb backend";
1108         return false;
1109     }
1110 
1111     if (GetConnectionState() == ConnectionState::kCsDetached) {
1112         *error = android::base::StringPrintf("transport %s is already detached", serial.c_str());
1113         return false;
1114     }
1115 
1116     handle_offline(this);
1117 
1118     {
1119         std::lock_guard<std::mutex> lock(mutex_);
1120         if (!connection_->Detach(error)) {
1121             return false;
1122         }
1123     }
1124 
1125     this->SetConnectionState(kCsDetached);
1126     return true;
1127 }
1128 #endif  // ADB_HOST
1129 
SetConnection(std::shared_ptr<Connection> connection)1130 void atransport::SetConnection(std::shared_ptr<Connection> connection) {
1131     std::lock_guard<std::mutex> lock(mutex_);
1132     connection_ = std::shared_ptr<Connection>(std::move(connection));
1133 }
1134 
HandleRead(std::unique_ptr<apacket> p)1135 bool atransport::HandleRead(std::unique_ptr<apacket> p) {
1136     if (!check_header(p.get(), this)) {
1137         D("%s: remote read: bad header", serial.c_str());
1138         return false;
1139     }
1140 
1141     VLOG(TRANSPORT) << dump_packet(serial.c_str(), "from remote", p.get());
1142     apacket* packet = p.release();
1143 
1144     // This needs to run on the looper thread since the associated fdevent
1145     // message pump exists in that context.
1146     fdevent_run_on_looper([packet, this]() { handle_packet(packet, this); });
1147 
1148     return true;
1149 }
1150 
HandleError(const std::string & error)1151 void atransport::HandleError(const std::string& error) {
1152     LOG(INFO) << serial_name() << ": connection terminated: " << error;
1153     fdevent_run_on_looper([this]() {
1154         handle_offline(this);
1155         transport_destroy(this);
1156     });
1157 }
1158 
update_version(int version,size_t payload)1159 void atransport::update_version(int version, size_t payload) {
1160     protocol_version = std::min(version, A_VERSION);
1161     max_payload = std::min(payload, MAX_PAYLOAD);
1162 }
1163 
get_protocol_version() const1164 int atransport::get_protocol_version() const {
1165     return protocol_version;
1166 }
1167 
get_tls_version() const1168 int atransport::get_tls_version() const {
1169     return tls_version;
1170 }
1171 
get_max_payload() const1172 size_t atransport::get_max_payload() const {
1173     return max_payload;
1174 }
1175 
1176 #if ADB_HOST
delayed_ack_enabled()1177 static bool delayed_ack_enabled() {
1178     static const char* env = getenv("ADB_DELAYED_ACK");
1179     static bool result = env && strcmp(env, "1") == 0;
1180     return result;
1181 }
1182 #endif
1183 
supported_features()1184 const FeatureSet& supported_features() {
1185     static const android::base::NoDestructor<FeatureSet> features([]() {
1186         // Increment ADB_SERVER_VERSION when adding a feature that adbd needs
1187         // to know about. Otherwise, the client can be stuck running an old
1188         // version of the server even after upgrading their copy of adb.
1189         // (http://b/24370690)
1190 
1191         // clang-format off
1192         FeatureSet result {
1193             kFeatureShell2,
1194             kFeatureCmd,
1195             kFeatureStat2,
1196             kFeatureLs2,
1197             kFeatureFixedPushMkdir,
1198             kFeatureApex,
1199             kFeatureAbb,
1200             kFeatureFixedPushSymlinkTimestamp,
1201             kFeatureAbbExec,
1202             kFeatureRemountShell,
1203             kFeatureTrackApp,
1204             kFeatureSendRecv2,
1205             kFeatureSendRecv2Brotli,
1206             kFeatureSendRecv2LZ4,
1207             kFeatureSendRecv2Zstd,
1208             kFeatureSendRecv2DryRunSend,
1209             kFeatureOpenscreenMdns,
1210             kFeatureDeviceTrackerProtoFormat,
1211             kFeatureDevRaw,
1212             kFeatureAppInfo,
1213         };
1214         // clang-format on
1215 
1216 #if ADB_HOST
1217         if (delayed_ack_enabled()) {
1218             result.push_back(kFeatureDelayedAck);
1219         }
1220 #else
1221         result.push_back(kFeatureDelayedAck);
1222 #endif
1223         return result;
1224     }());
1225 
1226     return *features;
1227 }
1228 
FeatureSetToString(const FeatureSet & features)1229 std::string FeatureSetToString(const FeatureSet& features) {
1230     return android::base::Join(features, ',');
1231 }
1232 
StringToFeatureSet(const std::string & features_string)1233 FeatureSet StringToFeatureSet(const std::string& features_string) {
1234     if (features_string.empty()) {
1235         return FeatureSet();
1236     }
1237 
1238     return android::base::Split(features_string, ",");
1239 }
1240 
1241 template <class Range, class Value>
contains(const Range & r,const Value & v)1242 static bool contains(const Range& r, const Value& v) {
1243     return std::find(std::begin(r), std::end(r), v) != std::end(r);
1244 }
1245 
CanUseFeature(const FeatureSet & feature_set,const std::string & feature)1246 bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
1247     return contains(feature_set, feature) && contains(supported_features(), feature);
1248 }
1249 
has_feature(const std::string & feature) const1250 bool atransport::has_feature(const std::string& feature) const {
1251     return contains(features_, feature);
1252 }
1253 
SetFeatures(const std::string & features_string)1254 void atransport::SetFeatures(const std::string& features_string) {
1255     features_ = StringToFeatureSet(features_string);
1256     delayed_ack_ = CanUseFeature(features_, kFeatureDelayedAck);
1257 }
1258 
AddDisconnect(adisconnect * disconnect)1259 void atransport::AddDisconnect(adisconnect* disconnect) {
1260     disconnects_.push_back(disconnect);
1261 }
1262 
RemoveDisconnect(adisconnect * disconnect)1263 void atransport::RemoveDisconnect(adisconnect* disconnect) {
1264     disconnects_.remove(disconnect);
1265 }
1266 
RunDisconnects()1267 void atransport::RunDisconnects() {
1268     for (const auto& disconnect : disconnects_) {
1269         disconnect->func(disconnect->opaque, this);
1270     }
1271     disconnects_.clear();
1272 }
1273 
1274 #if ADB_HOST
MatchesTarget(const std::string & target) const1275 bool atransport::MatchesTarget(const std::string& target) const {
1276     if (!serial.empty()) {
1277         if (target == serial) {
1278             return true;
1279         } else if (type == kTransportLocal) {
1280             // Local transports can match [tcp:|udp:]<hostname>[:port].
1281             const char* local_target_ptr = target.c_str();
1282 
1283             // For fastboot compatibility, ignore protocol prefixes.
1284             if (android::base::StartsWith(target, "tcp:") ||
1285                 android::base::StartsWith(target, "udp:")) {
1286                 local_target_ptr += 4;
1287             }
1288 
1289             // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1290             std::string serial_host, error;
1291             int serial_port = -1;
1292             if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr,
1293                                                &error)) {
1294                 // |target| may omit the port to default to ours.
1295                 std::string target_host;
1296                 int target_port = serial_port;
1297                 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1298                                                    nullptr, &error) &&
1299                     serial_host == target_host && serial_port == target_port) {
1300                     return true;
1301                 }
1302             }
1303         }
1304     }
1305 
1306     return (target == devpath) || qual_match(target, "product:", product, false) ||
1307            qual_match(target, "model:", model, true) ||
1308            qual_match(target, "device:", device, false);
1309 }
1310 
SetConnectionEstablished(bool success)1311 void atransport::SetConnectionEstablished(bool success) {
1312     connection_waitable_->SetConnectionEstablished(success);
1313 }
1314 
Reconnect()1315 ReconnectResult atransport::Reconnect() {
1316     return reconnect_(this);
1317 }
1318 
1319 // We use newline as our delimiter, make sure to never output it.
sanitize(std::string str,bool alphanumeric)1320 static std::string sanitize(std::string str, bool alphanumeric) {
1321     auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1322                              : [](const char c) { return c == '\n'; };
1323     std::replace_if(str.begin(), str.end(), pred, '_');
1324     return str;
1325 }
1326 
adbStateFromProto(ConnectionState state)1327 static adb::proto::ConnectionState adbStateFromProto(ConnectionState state) {
1328     switch (state) {
1329         case kCsConnecting:
1330             return adb::proto::ConnectionState::CONNECTING;
1331         case kCsAuthorizing:
1332             return adb::proto::ConnectionState::AUTHORIZING;
1333         case kCsUnauthorized:
1334             return adb::proto::ConnectionState::UNAUTHORIZED;
1335         case kCsNoPerm:
1336             return adb::proto::ConnectionState::NOPERMISSION;
1337         case kCsDetached:
1338             return adb::proto::ConnectionState::DETACHED;
1339         case kCsOffline:
1340             return adb::proto::ConnectionState::OFFLINE;
1341         case kCsBootloader:
1342             return adb::proto::ConnectionState::BOOTLOADER;
1343         case kCsDevice:
1344             return adb::proto::ConnectionState::DEVICE;
1345         case kCsHost:
1346             return adb::proto::ConnectionState::HOST;
1347         case kCsRecovery:
1348             return adb::proto::ConnectionState::RECOVERY;
1349         case kCsSideload:
1350             return adb::proto::ConnectionState::SIDELOAD;
1351         case kCsRescue:
1352             return adb::proto::ConnectionState::RESCUE;
1353         case kCsAny:
1354             return adb::proto::ConnectionState::ANY;
1355     }
1356 }
1357 
transportListToProto(const std::list<atransport * > & sorted_transport_list,bool text_version)1358 static std::string transportListToProto(const std::list<atransport*>& sorted_transport_list,
1359                                         bool text_version) {
1360     adb::proto::Devices devices;
1361     for (const auto& t : sorted_transport_list) {
1362         auto* device = devices.add_device();
1363         device->set_serial(t->serial.c_str());
1364         device->set_connection_type(t->type == kTransportUsb ? adb::proto::ConnectionType::USB
1365                                                              : adb::proto::ConnectionType::SOCKET);
1366         device->set_state(adbStateFromProto(t->GetConnectionState()));
1367         device->set_bus_address(sanitize(t->devpath, false));
1368         device->set_product(sanitize(t->product, false));
1369         device->set_model(sanitize(t->model, true));
1370         device->set_device(sanitize(t->device, false));
1371         device->set_negotiated_speed(t->connection()->NegotiatedSpeedMbps());
1372         device->set_max_speed(t->connection()->MaxSpeedMbps());
1373         device->set_transport_id(t->id);
1374     }
1375 
1376     std::string proto;
1377     if (text_version) {
1378         google::protobuf::TextFormat::PrintToString(devices, &proto);
1379     } else {
1380         devices.SerializeToString(&proto);
1381     }
1382     return proto;
1383 }
1384 
append_transport_info(std::string * result,const char * key,const std::string & value,bool alphanumeric)1385 static void append_transport_info(std::string* result, const char* key, const std::string& value,
1386                                   bool alphanumeric) {
1387     if (value.empty()) {
1388         return;
1389     }
1390 
1391     *result += ' ';
1392     *result += key;
1393     *result += sanitize(value, alphanumeric);
1394 }
1395 
append_transport(const atransport * t,std::string * result,bool long_listing)1396 static void append_transport(const atransport* t, std::string* result, bool long_listing) {
1397     std::string serial = t->serial;
1398     if (serial.empty()) {
1399         serial = "(no serial number)";
1400     }
1401 
1402     if (!long_listing) {
1403         *result += serial;
1404         *result += '\t';
1405         *result += to_string(t->GetConnectionState());
1406     } else {
1407         android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1408                                      to_string(t->GetConnectionState()).c_str());
1409 
1410         append_transport_info(result, "", t->devpath, false);
1411         append_transport_info(result, "product:", t->product, false);
1412         append_transport_info(result, "model:", t->model, true);
1413         append_transport_info(result, "device:", t->device, false);
1414 
1415         // Put id at the end, so that anyone parsing the output here can always find it by scanning
1416         // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1417         *result += " transport_id:";
1418         *result += std::to_string(t->id);
1419     }
1420     *result += '\n';
1421 }
1422 
transportListToText(const std::list<atransport * > & sorted_transport_list,bool long_listing)1423 static std::string transportListToText(const std::list<atransport*>& sorted_transport_list,
1424                                        bool long_listing) {
1425     std::string result;
1426     for (const auto& t : sorted_transport_list) {
1427         append_transport(t, &result, long_listing);
1428     }
1429     return result;
1430 }
1431 
list_transports(TrackerOutputType outputType)1432 std::string list_transports(TrackerOutputType outputType) {
1433     std::lock_guard<std::recursive_mutex> lock(transport_lock);
1434 
1435     auto sorted_transport_list = transport_list;
1436     sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1437         if (x->type != y->type) {
1438             return x->type < y->type;
1439         }
1440         return x->serial < y->serial;
1441     });
1442 
1443     switch (outputType) {
1444         case SHORT_TEXT:
1445         case LONG_TEXT: {
1446             return transportListToText(sorted_transport_list, outputType == LONG_TEXT);
1447         }
1448         case PROTOBUF:
1449         case TEXT_PROTOBUF: {
1450             return transportListToProto(sorted_transport_list, outputType == TEXT_PROTOBUF);
1451         }
1452     }
1453 }
1454 
close_usb_devices(std::function<bool (const atransport *)> predicate,bool reset)1455 void close_usb_devices(std::function<bool(const atransport*)> predicate, bool reset) {
1456     std::lock_guard<std::recursive_mutex> lock(transport_lock);
1457     for (auto& t : transport_list) {
1458         if (predicate(t)) {
1459             if (reset) {
1460                 t->Reset();
1461             } else {
1462                 t->Kick();
1463             }
1464         }
1465     }
1466 }
1467 
1468 /* hack for osx */
close_usb_devices(bool reset)1469 void close_usb_devices(bool reset) {
1470     close_usb_devices([](const atransport*) { return true; }, reset);
1471 }
1472 #endif
1473 
validate_transport_list(const std::list<atransport * > & list,const std::string & serial,atransport * t,int * error)1474 bool validate_transport_list(const std::list<atransport*>& list, const std::string& serial,
1475                              atransport* t, int* error) {
1476     for (const auto& transport : list) {
1477         if (serial == transport->serial) {
1478             const std::string list_name(&list == &pending_list ? "pending" : "transport");
1479             VLOG(TRANSPORT) << "socket transport " << transport->serial << " is already in the "
1480                             << list_name << " list and fails to register";
1481             delete t;
1482             if (error) *error = EALREADY;
1483             return false;
1484         }
1485     }
1486     return true;
1487 }
1488 
register_socket_transport(unique_fd s,std::string serial,int port,int local,atransport::ReconnectCallback reconnect,bool use_tls,int * error)1489 bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
1490                                atransport::ReconnectCallback reconnect, bool use_tls, int* error) {
1491     atransport* t = new atransport(std::move(reconnect), kCsOffline);
1492     t->use_tls = use_tls;
1493     t->serial = std::move(serial);
1494 
1495     D("transport: %s init'ing for socket %d, on port %d", t->serial.c_str(), s.get(), port);
1496     if (init_socket_transport(t, std::move(s), port, local) < 0) {
1497         delete t;
1498         if (error) *error = errno;
1499         return false;
1500     }
1501 
1502     std::unique_lock<std::recursive_mutex> lock(transport_lock);
1503     if (!validate_transport_list(pending_list, t->serial, t, error)) {
1504         return false;
1505     }
1506 
1507     if (!validate_transport_list(transport_list, t->serial, t, error)) {
1508         return false;
1509     }
1510 
1511     pending_list.push_front(t);
1512 
1513     lock.unlock();
1514 
1515 #if ADB_HOST
1516     auto waitable = t->connection_waitable();
1517 #endif
1518     register_transport(t);
1519 
1520     if (local == 1) {
1521         // Do not wait for emulator transports.
1522         return true;
1523     }
1524 
1525 #if ADB_HOST
1526     if (!waitable->WaitForConnection(std::chrono::seconds(10))) {
1527         if (error) *error = ETIMEDOUT;
1528         return false;
1529     }
1530 
1531     if (t->GetConnectionState() == kCsUnauthorized) {
1532         if (error) *error = EPERM;
1533         return false;
1534     }
1535 #endif
1536 
1537     return true;
1538 }
1539 
1540 #if ADB_HOST
find_transport(const char * serial)1541 atransport* find_transport(const char* serial) {
1542     atransport* result = nullptr;
1543 
1544     std::lock_guard<std::recursive_mutex> lock(transport_lock);
1545     for (auto& t : transport_list) {
1546         if (strcmp(serial, t->serial.c_str()) == 0) {
1547             result = t;
1548             break;
1549         }
1550     }
1551 
1552     return result;
1553 }
1554 
kick_all_tcp_devices()1555 void kick_all_tcp_devices() {
1556     std::lock_guard<std::recursive_mutex> lock(transport_lock);
1557     for (auto& t : transport_list) {
1558         if (t->IsTcpDevice()) {
1559             // Kicking breaks the read_transport thread of this transport out of any read, then
1560             // the read_transport thread will notify the main thread to make this transport
1561             // offline. Then the main thread will notify the write_transport thread to exit.
1562             // Finally, this transport will be closed and freed in the main thread.
1563             t->Kick();
1564         }
1565     }
1566     reconnect_handler.CheckForKicked();
1567 }
1568 
1569 #if ADB_HOST
register_usb_transport(std::shared_ptr<Connection> connection,const char * serial,const char * devpath,unsigned writeable)1570 void register_usb_transport(std::shared_ptr<Connection> connection, const char* serial,
1571                             const char* devpath, unsigned writeable) {
1572     atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
1573     if (serial) {
1574         t->serial = serial;
1575     }
1576     if (devpath) {
1577         t->devpath = devpath;
1578     }
1579 
1580     t->SetConnection(std::move(connection));
1581     t->type = kTransportUsb;
1582 
1583     {
1584         std::lock_guard<std::recursive_mutex> lock(transport_lock);
1585         pending_list.push_front(t);
1586     }
1587 
1588     register_transport(t);
1589 }
1590 
register_usb_transport(usb_handle * usb,const char * serial,const char * devpath,unsigned writeable)1591 void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1592                             unsigned writeable) {
1593     atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
1594 
1595     D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
1596     init_usb_transport(t, usb);
1597     if (serial) {
1598         t->serial = serial;
1599     }
1600 
1601     if (devpath) {
1602         t->devpath = devpath;
1603     }
1604 
1605     {
1606         std::lock_guard<std::recursive_mutex> lock(transport_lock);
1607         pending_list.push_front(t);
1608     }
1609 
1610     register_transport(t);
1611 }
1612 
1613 // This should only be used for transports with connection_state == kCsNoPerm.
unregister_usb_transport(usb_handle * usb)1614 void unregister_usb_transport(usb_handle* usb) {
1615     std::lock_guard<std::recursive_mutex> lock(transport_lock);
1616     transport_list.remove_if([usb](atransport* t) {
1617         return t->GetUsbHandle() == usb && t->GetConnectionState() == kCsNoPerm;
1618     });
1619 }
1620 #endif
1621 
1622 // Track reverse:forward commands, so that info can be used to develop
1623 // an 'allow-list':
1624 //   - adb reverse tcp:<device_port> localhost:<host_port> : responds with the
1625 //   device_port
1626 //   - adb reverse --remove tcp:<device_port> : responds OKAY
1627 //   - adb reverse --remove-all : responds OKAY
UpdateReverseConfig(std::string_view service_addr)1628 void atransport::UpdateReverseConfig(std::string_view service_addr) {
1629     fdevent_check_looper();
1630     if (!android::base::ConsumePrefix(&service_addr, "reverse:")) {
1631         return;
1632     }
1633 
1634     if (android::base::ConsumePrefix(&service_addr, "forward:")) {
1635         // forward:[norebind:]<remote>;<local>
1636         bool norebind = android::base::ConsumePrefix(&service_addr, "norebind:");
1637         auto it = service_addr.find(';');
1638         if (it == std::string::npos) {
1639             return;
1640         }
1641         std::string remote(service_addr.substr(0, it));
1642 
1643         if (norebind && reverse_forwards_.find(remote) != reverse_forwards_.end()) {
1644             // This will fail, don't update the map.
1645             LOG(DEBUG) << "ignoring reverse forward that will fail due to norebind";
1646             return;
1647         }
1648 
1649         std::string local(service_addr.substr(it + 1));
1650         reverse_forwards_[remote] = local;
1651     } else if (android::base::ConsumePrefix(&service_addr, "killforward:")) {
1652         // kill-forward:<remote>
1653         auto it = service_addr.find(';');
1654         if (it != std::string::npos) {
1655             return;
1656         }
1657         reverse_forwards_.erase(std::string(service_addr));
1658     } else if (service_addr == "killforward-all") {
1659         reverse_forwards_.clear();
1660     } else if (service_addr == "list-forward") {
1661         LOG(DEBUG) << __func__ << " ignoring --list";
1662     } else {  // Anything else we need to know about?
1663         LOG(FATAL) << "unhandled reverse service: " << service_addr;
1664     }
1665 }
1666 
1667 // Is this an authorized :connect request?
IsReverseConfigured(const std::string & local_addr)1668 bool atransport::IsReverseConfigured(const std::string& local_addr) {
1669     fdevent_check_looper();
1670     for (const auto& [remote, local] : reverse_forwards_) {
1671         if (local == local_addr) {
1672             return true;
1673         }
1674     }
1675     return false;
1676 }
1677 
1678 #endif
1679 
check_header(apacket * p,atransport * t)1680 bool check_header(apacket* p, atransport* t) {
1681     if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
1682         VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1683                   << ", magic = " << p->msg.magic;
1684         return false;
1685     }
1686 
1687     if (p->msg.data_length > t->get_max_payload()) {
1688         VLOG(RWX) << "check_header(): " << p->msg.data_length
1689                   << " atransport::max_payload = " << t->get_max_payload();
1690         return false;
1691     }
1692 
1693     return true;
1694 }
1695 
1696 #if ADB_HOST
Key()1697 std::shared_ptr<RSA> atransport::Key() {
1698     if (keys_.empty()) {
1699         return nullptr;
1700     }
1701 
1702     std::shared_ptr<RSA> result = keys_[0];
1703     return result;
1704 }
1705 
NextKey()1706 std::shared_ptr<RSA> atransport::NextKey() {
1707     if (keys_.empty()) {
1708         LOG(INFO) << "fetching keys for transport " << this->serial_name();
1709         keys_ = adb_auth_get_private_keys();
1710 
1711         // We should have gotten at least one key: the one that's automatically generated.
1712         CHECK(!keys_.empty());
1713     } else {
1714         keys_.pop_front();
1715     }
1716 
1717     return Key();
1718 }
1719 
ResetKeys()1720 void atransport::ResetKeys() {
1721     keys_.clear();
1722 }
1723 #endif
1724