-
Notifications
You must be signed in to change notification settings - Fork 1
/
transport.cpp
1719 lines (1447 loc) · 53 KB
/
transport.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define TRACE_TAG TRANSPORT
#include "sysdeps.h"
#include "transport.h"
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <algorithm>
#include <list>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <thread>
#include <adb/crypto/rsa_2048_key.h>
#include <adb/crypto/x509_generator.h>
#include <adb/tls/tls_connection.h>
#include <android-base/logging.h>
#include <android-base/no_destructor.h>
#include <android-base/parsenetaddress.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <android-base/thread_annotations.h>
#include <diagnose_usb.h>
#include "adb.h"
#include "adb_auth.h"
#include "adb_io.h"
#include "adb_trace.h"
#include "adb_utils.h"
#include "fdevent/fdevent.h"
#include "sysdeps/chrono.h"
#if ADB_HOST
#include <google/protobuf/text_format.h>
#include "client/usb.h"
#include "devices.pb.h"
#endif
using namespace adb::crypto;
using namespace adb::tls;
using namespace std::string_literals;
using android::base::ScopedLockAssertion;
using TlsError = TlsConnection::TlsError;
static void remove_transport(atransport* transport);
static void transport_destroy(atransport* transport);
// TODO: unordered_map<TransportId, atransport*>
static auto& transport_list = *new std::list<atransport*>();
static auto& pending_list = *new std::list<atransport*>();
static auto& transport_lock = *new std::recursive_mutex();
const char* const kFeatureShell2 = "shell_v2";
const char* const kFeatureCmd = "cmd";
const char* const kFeatureStat2 = "stat_v2";
const char* const kFeatureLs2 = "ls_v2";
const char* const kFeatureLibusb = "libusb";
const char* const kFeaturePushSync = "push_sync";
const char* const kFeatureApex = "apex";
const char* const kFeatureFixedPushMkdir = "fixed_push_mkdir";
const char* const kFeatureAbb = "abb";
const char* const kFeatureFixedPushSymlinkTimestamp = "fixed_push_symlink_timestamp";
const char* const kFeatureAbbExec = "abb_exec";
const char* const kFeatureRemountShell = "remount_shell";
const char* const kFeatureTrackApp = "track_app";
const char* const kFeatureSendRecv2 = "sendrecv_v2";
const char* const kFeatureSendRecv2Brotli = "sendrecv_v2_brotli";
const char* const kFeatureSendRecv2LZ4 = "sendrecv_v2_lz4";
const char* const kFeatureSendRecv2Zstd = "sendrecv_v2_zstd";
const char* const kFeatureSendRecv2DryRunSend = "sendrecv_v2_dry_run_send";
const char* const kFeatureDelayedAck = "delayed_ack";
// TODO(joshuaduong): Bump to v2 when openscreen discovery is enabled by default
const char* const kFeatureOpenscreenMdns = "openscreen_mdns";
const char* const kFeatureDeviceTrackerProtoFormat = "devicetracker_proto_format";
namespace {
#if ADB_HOST
// Tracks and handles atransport*s that are attempting reconnection.
class ReconnectHandler {
public:
ReconnectHandler() = default;
~ReconnectHandler() = default;
// Starts the ReconnectHandler thread.
void Start();
// Requests the ReconnectHandler thread to stop.
void Stop();
// Adds the atransport* to the queue of reconnect attempts.
void TrackTransport(atransport* transport);
// Wake up the ReconnectHandler thread to have it check for kicked transports.
void CheckForKicked();
private:
// The main thread loop.
void Run();
// Tracks a reconnection attempt.
struct ReconnectAttempt {
atransport* transport;
std::chrono::steady_clock::time_point reconnect_time;
size_t attempts_left;
bool operator<(const ReconnectAttempt& rhs) const {
if (reconnect_time == rhs.reconnect_time) {
return reinterpret_cast<uintptr_t>(transport) <
reinterpret_cast<uintptr_t>(rhs.transport);
}
return reconnect_time < rhs.reconnect_time;
}
};
// Only retry for up to one minute.
static constexpr const std::chrono::seconds kDefaultTimeout = 3s;
static constexpr const size_t kMaxAttempts = 20;
// Protects all members.
std::mutex reconnect_mutex_;
bool running_ GUARDED_BY(reconnect_mutex_) = true;
std::thread handler_thread_;
std::condition_variable reconnect_cv_;
std::set<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
};
void ReconnectHandler::Start() {
fdevent_check_looper();
handler_thread_ = std::thread(&ReconnectHandler::Run, this);
}
void ReconnectHandler::Stop() {
fdevent_check_looper();
{
std::lock_guard<std::mutex> lock(reconnect_mutex_);
running_ = false;
}
reconnect_cv_.notify_one();
handler_thread_.join();
// Drain the queue to free all resources.
std::lock_guard<std::mutex> lock(reconnect_mutex_);
while (!reconnect_queue_.empty()) {
ReconnectAttempt attempt = *reconnect_queue_.begin();
reconnect_queue_.erase(reconnect_queue_.begin());
remove_transport(attempt.transport);
}
}
void ReconnectHandler::TrackTransport(atransport* transport) {
fdevent_check_looper();
{
std::lock_guard<std::mutex> lock(reconnect_mutex_);
if (!running_) return;
// Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
reconnect_queue_.emplace(
ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
}
reconnect_cv_.notify_one();
}
void ReconnectHandler::CheckForKicked() {
reconnect_cv_.notify_one();
}
void ReconnectHandler::Run() {
while (true) {
ReconnectAttempt attempt;
{
std::unique_lock<std::mutex> lock(reconnect_mutex_);
ScopedLockAssertion assume_lock(reconnect_mutex_);
if (!reconnect_queue_.empty()) {
// FIXME: libstdc++ (used on Windows) implements condition_variable with
// system_clock as its clock, so we're probably hosed if the clock changes,
// even if we use steady_clock throughout. This problem goes away once we
// switch to libc++.
reconnect_cv_.wait_until(lock, reconnect_queue_.begin()->reconnect_time);
} else {
reconnect_cv_.wait(lock);
}
if (!running_) return;
// Scan the whole list for kicked transports, so that we immediately handle an explicit
// disconnect request.
for (auto it = reconnect_queue_.begin(); it != reconnect_queue_.end();) {
if (it->transport->kicked()) {
D("transport %s was kicked. giving up on it.", it->transport->serial.c_str());
remove_transport(it->transport);
it = reconnect_queue_.erase(it);
} else {
++it;
}
}
if (reconnect_queue_.empty()) continue;
// Go back to sleep if we either woke up spuriously, or we were woken up to remove
// a kicked transport, and the first transport isn't ready for reconnection yet.
auto now = std::chrono::steady_clock::now();
if (reconnect_queue_.begin()->reconnect_time > now) {
continue;
}
attempt = *reconnect_queue_.begin();
reconnect_queue_.erase(reconnect_queue_.begin());
}
D("attempting to reconnect %s", attempt.transport->serial.c_str());
switch (attempt.transport->Reconnect()) {
case ReconnectResult::Retry: {
D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
if (attempt.attempts_left == 0) {
D("transport %s exceeded the number of retry attempts. giving up on it.",
attempt.transport->serial.c_str());
remove_transport(attempt.transport);
continue;
}
std::lock_guard<std::mutex> lock(reconnect_mutex_);
reconnect_queue_.emplace(ReconnectAttempt{
attempt.transport,
std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
attempt.attempts_left - 1});
continue;
}
case ReconnectResult::Success:
D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
register_transport(attempt.transport);
continue;
case ReconnectResult::Abort:
D("cancelling reconnection attempt to %s.", attempt.transport->serial.c_str());
remove_transport(attempt.transport);
continue;
}
}
}
static auto& reconnect_handler = *new ReconnectHandler();
#endif
} // namespace
TransportId NextTransportId() {
static std::atomic<TransportId> next(1);
return next++;
}
void Connection::Reset() {
LOG(INFO) << "Connection::Reset(): stopping";
Stop();
}
std::string Connection::Serial() const {
return transport_ ? transport_->serial_name() : "<unknown>";
}
BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
: underlying_(std::move(connection)) {}
BlockingConnectionAdapter::~BlockingConnectionAdapter() {
LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): destructing";
Stop();
}
void BlockingConnectionAdapter::Start() {
std::lock_guard<std::mutex> lock(mutex_);
if (started_) {
LOG(FATAL) << "BlockingConnectionAdapter(" << Serial() << "): started multiple times";
}
StartReadThread();
write_thread_ = std::thread([this]() {
LOG(INFO) << Serial() << ": write thread spawning";
while (true) {
std::unique_lock<std::mutex> lock(mutex_);
ScopedLockAssertion assume_locked(mutex_);
cv_.wait(lock, [this]() REQUIRES(mutex_) {
return this->stopped_ || !this->write_queue_.empty();
});
if (this->stopped_) {
return;
}
std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
this->write_queue_.pop_front();
lock.unlock();
if (!this->underlying_->Write(packet.get())) {
break;
}
}
std::call_once(this->error_flag_, [this]() { transport_->HandleError("write failed"); });
});
started_ = true;
}
void BlockingConnectionAdapter::StartReadThread() {
read_thread_ = std::thread([this]() {
LOG(INFO) << Serial() << ": read thread spawning";
while (true) {
auto packet = std::make_unique<apacket>();
if (!underlying_->Read(packet.get())) {
PLOG(INFO) << Serial() << ": read failed";
break;
}
bool got_stls_cmd = false;
if (packet->msg.command == A_STLS) {
got_stls_cmd = true;
}
transport_->HandleRead(std::move(packet));
// If we received the STLS packet, we are about to perform the TLS
// handshake. So this read thread must stop and resume after the
// handshake completes otherwise this will interfere in the process.
if (got_stls_cmd) {
LOG(INFO) << Serial() << ": Received STLS packet. Stopping read thread.";
return;
}
}
std::call_once(this->error_flag_, [this]() { transport_->HandleError("read failed"); });
});
}
bool BlockingConnectionAdapter::DoTlsHandshake(RSA* key, std::string* auth_key) {
std::lock_guard<std::mutex> lock(mutex_);
if (read_thread_.joinable()) {
read_thread_.join();
}
bool success = this->underlying_->DoTlsHandshake(key, auth_key);
StartReadThread();
return success;
}
void BlockingConnectionAdapter::Reset() {
{
std::lock_guard<std::mutex> lock(mutex_);
if (!started_) {
LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): not started";
return;
}
if (stopped_) {
LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): already stopped";
return;
}
}
LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): resetting";
this->underlying_->Reset();
Stop();
}
void BlockingConnectionAdapter::Stop() {
{
std::lock_guard<std::mutex> lock(mutex_);
if (!started_) {
LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): not started";
return;
}
if (stopped_) {
LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): already stopped";
return;
}
stopped_ = true;
}
LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): stopping";
this->underlying_->Close();
this->cv_.notify_one();
// Move the threads out into locals with the lock taken, and then unlock to let them exit.
std::thread read_thread;
std::thread write_thread;
{
std::lock_guard<std::mutex> lock(mutex_);
read_thread = std::move(read_thread_);
write_thread = std::move(write_thread_);
}
read_thread.join();
write_thread.join();
LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): stopped";
std::call_once(this->error_flag_, [this]() { transport_->HandleError("requested stop"); });
}
bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
{
std::lock_guard<std::mutex> lock(this->mutex_);
write_queue_.emplace_back(std::move(packet));
}
cv_.notify_one();
return true;
}
FdConnection::FdConnection(unique_fd fd) : fd_(std::move(fd)) {}
FdConnection::~FdConnection() {}
bool FdConnection::DispatchRead(void* buf, size_t len) {
if (tls_ != nullptr) {
// The TlsConnection doesn't allow 0 byte reads
if (len == 0) {
return true;
}
return tls_->ReadFully(buf, len);
}
return ReadFdExactly(fd_.get(), buf, len);
}
bool FdConnection::DispatchWrite(void* buf, size_t len) {
if (tls_ != nullptr) {
// The TlsConnection doesn't allow 0 byte writes
if (len == 0) {
return true;
}
return tls_->WriteFully(std::string_view(reinterpret_cast<const char*>(buf), len));
}
return WriteFdExactly(fd_.get(), buf, len);
}
bool FdConnection::Read(apacket* packet) {
if (!DispatchRead(&packet->msg, sizeof(amessage))) {
D("remote local: read terminated (message)");
return false;
}
if (packet->msg.data_length > MAX_PAYLOAD) {
D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
return false;
}
packet->payload.resize(packet->msg.data_length);
if (!DispatchRead(&packet->payload[0], packet->payload.size())) {
D("remote local: terminated (data)");
return false;
}
return true;
}
bool FdConnection::Write(apacket* packet) {
if (!DispatchWrite(&packet->msg, sizeof(packet->msg))) {
D("remote local: write terminated");
return false;
}
if (packet->msg.data_length) {
if (!DispatchWrite(&packet->payload[0], packet->msg.data_length)) {
D("remote local: write terminated");
return false;
}
}
return true;
}
bool FdConnection::DoTlsHandshake(RSA* key, std::string* auth_key) {
bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
if (!EVP_PKEY_set1_RSA(evp_pkey.get(), key)) {
LOG(ERROR) << "EVP_PKEY_set1_RSA failed";
return false;
}
auto x509 = GenerateX509Certificate(evp_pkey.get());
auto x509_str = X509ToPEMString(x509.get());
auto evp_str = Key::ToPEMString(evp_pkey.get());
int osh = cast_handle_to_int(adb_get_os_handle(fd_));
#if ADB_HOST
tls_ = TlsConnection::Create(TlsConnection::Role::Client, x509_str, evp_str, osh);
#else
tls_ = TlsConnection::Create(TlsConnection::Role::Server, x509_str, evp_str, osh);
#endif
CHECK(tls_);
#if ADB_HOST
// TLS 1.3 gives the client no message if the server rejected the
// certificate. This will enable a check in the tls connection to check
// whether the client certificate got rejected. Note that this assumes
// that, on handshake success, the server speaks first.
tls_->EnableClientPostHandshakeCheck(true);
// Add callback to set the certificate when server issues the
// CertificateRequest.
tls_->SetCertificateCallback(adb_tls_set_certificate);
// Allow any server certificate
tls_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
#else
// Add callback to check certificate against a list of known public keys
tls_->SetCertVerifyCallback(
[auth_key](X509_STORE_CTX* ctx) { return adbd_tls_verify_cert(ctx, auth_key); });
// Add the list of allowed client CA issuers
auto ca_list = adbd_tls_client_ca_list();
tls_->SetClientCAList(ca_list.get());
#endif
auto err = tls_->DoHandshake();
if (err == TlsError::Success) {
return true;
}
tls_.reset();
return false;
}
void FdConnection::Close() {
adb_shutdown(fd_.get());
fd_.reset();
}
void send_packet(apacket* p, atransport* t) {
p->msg.magic = p->msg.command ^ 0xffffffff;
// compute a checksum for connection/auth packets for compatibility reasons
if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
p->msg.data_check = 0;
} else {
p->msg.data_check = calculate_apacket_checksum(p);
}
VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
if (t == nullptr) {
LOG(FATAL) << "Transport is null";
}
if (t->Write(p) != 0) {
D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
t->Kick();
}
}
void kick_transport(atransport* t, bool reset) {
std::lock_guard<std::recursive_mutex> lock(transport_lock);
// As kick_transport() can be called from threads without guarantee that t is valid,
// check if the transport is in transport_list first.
//
// TODO(jmgao): WTF? Is this actually true?
if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
if (reset) {
t->Reset();
} else {
t->Kick();
}
}
#if ADB_HOST
reconnect_handler.CheckForKicked();
#endif
}
#if ADB_HOST
/* this adds support required by the 'track-devices' service.
* this is used to send the content of "list_transport" to any
* number of client connections that want it through a single
* live TCP connection
*/
struct device_tracker {
asocket socket;
bool update_needed = false;
TrackerOutputType output_type = SHORT_TEXT;
device_tracker* next = nullptr;
};
/* linked list of all device trackers */
static device_tracker* device_tracker_list;
static void device_tracker_remove(device_tracker* tracker) {
device_tracker** pnode = &device_tracker_list;
device_tracker* node = *pnode;
std::lock_guard<std::recursive_mutex> lock(transport_lock);
while (node) {
if (node == tracker) {
*pnode = node->next;
break;
}
pnode = &node->next;
node = *pnode;
}
}
static void device_tracker_close(asocket* socket) {
device_tracker* tracker = (device_tracker*)socket;
asocket* peer = socket->peer;
D("device tracker %p removed", tracker);
if (peer) {
peer->peer = nullptr;
peer->close(peer);
}
device_tracker_remove(tracker);
delete tracker;
}
static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
/* you can't read from a device tracker, close immediately */
device_tracker_close(socket);
return -1;
}
static int device_tracker_send(device_tracker* tracker, const std::string& string) {
asocket* peer = tracker->socket.peer;
apacket::payload_type data;
data.resize(4 + string.size());
char buf[5];
snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
memcpy(&data[0], buf, 4);
memcpy(&data[4], string.data(), string.size());
return peer->enqueue(peer, std::move(data));
}
static void device_tracker_ready(asocket* socket) {
device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
// We want to send the device list when the tracker connects
// for the first time, even if no update occurred.
if (tracker->update_needed) {
tracker->update_needed = false;
device_tracker_send(tracker, list_transports(tracker->output_type));
}
}
asocket* create_device_tracker(TrackerOutputType output_type) {
device_tracker* tracker = new device_tracker();
if (tracker == nullptr) LOG(FATAL) << "cannot allocate device tracker";
D("device tracker %p created", tracker);
tracker->socket.enqueue = device_tracker_enqueue;
tracker->socket.ready = device_tracker_ready;
tracker->socket.close = device_tracker_close;
tracker->update_needed = true;
tracker->output_type = output_type;
tracker->next = device_tracker_list;
device_tracker_list = tracker;
return &tracker->socket;
}
// Check if all of the USB transports are connected.
bool iterate_transports(std::function<bool(const atransport*)> fn) {
std::lock_guard<std::recursive_mutex> lock(transport_lock);
for (const auto& t : transport_list) {
if (!fn(t)) {
return false;
}
}
for (const auto& t : pending_list) {
if (!fn(t)) {
return false;
}
}
return true;
}
// Call this function each time the transport list has changed.
void update_transports() {
update_transport_status();
// Notify `adb track-devices` clients.
device_tracker* tracker = device_tracker_list;
while (tracker != nullptr) {
device_tracker* next = tracker->next;
// This may destroy the tracker if the connection is closed.
device_tracker_send(tracker, list_transports(tracker->output_type));
tracker = next;
}
}
#else
void update_transports() {
// Nothing to do on the device side.
}
#endif // ADB_HOST
#if ADB_HOST
static bool usb_devices_start_detached() {
static const char* env = getenv("ADB_LIBUSB_START_DETACHED");
static bool result = env && strcmp("1", env) == 0;
return should_use_libusb() && result;
}
#endif
static void fdevent_unregister_transport(atransport* t) {
D("transport: %s deleting", t->serial.c_str());
{
std::lock_guard<std::recursive_mutex> lock(transport_lock);
transport_list.remove(t);
}
delete t;
update_transports();
}
static void fdevent_register_transport(atransport* t) {
/* don't create transport threads for inaccessible devices */
if (t->GetConnectionState() != kCsNoPerm) {
t->connection()->SetTransport(t);
if (t->type == kTransportUsb
#if ADB_HOST
&& usb_devices_start_detached() // -d setting propagated from the
// host device, hence n/a on-device.
#endif
) {
t->SetConnectionState(kCsDetached);
} else {
t->connection()->Start();
#if ADB_HOST
send_connect(t);
#endif
}
}
{
std::lock_guard<std::recursive_mutex> lock(transport_lock);
auto it = std::find(pending_list.begin(), pending_list.end(), t);
if (it != pending_list.end()) {
pending_list.remove(t);
transport_list.push_front(t);
}
}
update_transports();
}
#if ADB_HOST
void init_reconnect_handler(void) {
reconnect_handler.Start();
}
#endif
void kick_all_transports() {
#if ADB_HOST
reconnect_handler.Stop();
#endif
// To avoid only writing part of a packet to a transport after exit, kick all transports.
std::lock_guard<std::recursive_mutex> lock(transport_lock);
for (auto t : transport_list) {
t->Kick();
}
}
void kick_all_tcp_tls_transports() {
std::lock_guard<std::recursive_mutex> lock(transport_lock);
for (auto t : transport_list) {
if (t->IsTcpDevice() && t->use_tls) {
t->Kick();
}
}
}
#if !ADB_HOST
void kick_all_transports_by_auth_key(std::string_view auth_key) {
std::lock_guard<std::recursive_mutex> lock(transport_lock);
for (auto t : transport_list) {
if (auth_key == t->auth_key) {
t->Kick();
}
}
}
#endif
void register_transport(atransport* transport) {
D("transport: %s registered", transport->serial.c_str());
fdevent_run_on_looper([=]() { fdevent_register_transport(transport); });
}
static void remove_transport(atransport* transport) {
D("transport: %s removed", transport->serial.c_str());
fdevent_run_on_looper([=]() { fdevent_unregister_transport(transport); });
}
static void transport_destroy(atransport* t) {
fdevent_check_looper();
CHECK(t != nullptr);
std::lock_guard<std::recursive_mutex> lock(transport_lock);
LOG(INFO) << "destroying transport " << t->serial_name();
t->connection()->Stop();
#if ADB_HOST
if (t->IsTcpDevice() && !t->kicked()) {
D("transport: %s destroy (attempting reconnection)", t->serial.c_str());
// We need to clear the transport's keys, so that on the next connection, it tries
// again from the beginning.
t->ResetKeys();
reconnect_handler.TrackTransport(t);
return;
}
#endif
D("transport: %s destroy (kicking and closing)", t->serial.c_str());
remove_transport(t);
}
#if ADB_HOST
static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
bool sanitize_qual) {
if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
return qual.empty();
if (qual.empty()) return 0;
const char* ptr = to_test.c_str();
if (prefix) {
while (*prefix) {
if (*prefix++ != *ptr++) return 0;
}
}
for (char ch : qual) {
if (sanitize_qual && !isalnum(ch)) ch = '_';
if (ch != *ptr++) return 0;
}
/* Everything matched so far. Return true if *ptr is a NUL. */
return !*ptr;
}
// Contains either a device serial string or a USB device address like "usb:2-6"
const char* __transport_server_one_device = nullptr;
void transport_set_one_device(const char* adb_one_device) {
__transport_server_one_device = adb_one_device;
}
const char* transport_get_one_device() {
return __transport_server_one_device;
}
bool transport_server_owns_device(std::string_view serial) {
if (!__transport_server_one_device) {
// If the server doesn't own one device, server owns all devices.
return true;
}
return serial.compare(__transport_server_one_device) == 0;
}
bool transport_server_owns_device(std::string_view dev_path, std::string_view serial) {
if (!__transport_server_one_device) {
// If the server doesn't own one device, server owns all devices.
return true;
}
return serial.compare(__transport_server_one_device) == 0 ||
dev_path.compare(__transport_server_one_device) == 0;
}
atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
bool* is_ambiguous, std::string* error_out,
bool accept_any_state) {
atransport* result = nullptr;
if (transport_id != 0) {
*error_out = android::base::StringPrintf("no device with transport id '%" PRIu64 "'",
transport_id);
} else if (serial) {
*error_out = android::base::StringPrintf("device '%s' not found", serial);
} else if (type == kTransportLocal) {
*error_out = "no emulators found";
} else if (type == kTransportAny) {
*error_out = "no devices/emulators found";
} else {
*error_out = "no devices found";
}
std::unique_lock<std::recursive_mutex> lock(transport_lock);
for (const auto& t : transport_list) {
if (t->GetConnectionState() == kCsNoPerm) {
*error_out = UsbNoPermissionsLongHelpText();
continue;
}
if (transport_id) {
if (t->id == transport_id) {
result = t;
break;
}
} else if (serial) {
if (t->MatchesTarget(serial)) {
if (result) {
*error_out = "more than one device with serial "s + serial;
if (is_ambiguous) *is_ambiguous = true;
result = nullptr;
break;
}
result = t;
}
} else {
if (type == kTransportUsb && t->type == kTransportUsb) {
if (result) {
*error_out = "more than one USB device";
if (is_ambiguous) *is_ambiguous = true;
result = nullptr;
break;
}
result = t;
} else if (type == kTransportLocal && t->type == kTransportLocal) {
if (result) {
*error_out = "more than one emulator";
if (is_ambiguous) *is_ambiguous = true;
result = nullptr;
break;
}
result = t;
} else if (type == kTransportAny) {
if (result) {
*error_out = "more than one device/emulator";
if (is_ambiguous) *is_ambiguous = true;
result = nullptr;
break;
}
result = t;
}
}
}
lock.unlock();
if (result && !accept_any_state) {
// The caller requires an active transport.
// Make sure that we're actually connected.
ConnectionState state = result->GetConnectionState();
switch (state) {
case kCsConnecting:
*error_out = "device still connecting";
result = nullptr;
break;
case kCsAuthorizing:
*error_out = "device still authorizing";
result = nullptr;
break;
case kCsUnauthorized: {
*error_out = "device unauthorized.\n";
char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
*error_out += "This adb server's $ADB_VENDOR_KEYS is ";
*error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
*error_out += "\n";
*error_out += "Try 'adb kill-server' if that seems wrong.\n";
*error_out += "Otherwise check for a confirmation dialog on your device.";
result = nullptr;
break;
}
case kCsOffline: