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