blob: 447a8fedf7ed2f4e7ee2da3e44161b11ebcd4991 [file] [log] [blame]
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001/*
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
Yabin Cui19bec5b2015-09-22 15:52:57 -070017#define TRACE_TAG TRANSPORT
Dan Albertb302d122015-02-24 15:51:19 -080018
Dan Albertdb6fe642015-03-19 15:21:08 -070019#include "sysdeps.h"
Josh Gaof2a988c2018-03-07 16:51:08 -080020
Dan Albertb302d122015-02-24 15:51:19 -080021#include "transport.h"
22
Dan Albert4895c522015-02-20 17:24:58 -080023#include <ctype.h>
Dan Albertb302d122015-02-24 15:51:19 -080024#include <errno.h>
Josh Gaob39e4152017-08-16 16:57:01 -070025#include <inttypes.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080026#include <stdio.h>
27#include <stdlib.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080028#include <string.h>
Dan Albertb302d122015-02-24 15:51:19 -080029#include <unistd.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080030
Spencer Low28bc2cb2015-11-07 18:51:54 -080031#include <algorithm>
Josh Gao715fe602018-02-16 13:24:58 -080032#include <deque>
Dan Albertecce5032015-05-18 16:46:31 -070033#include <list>
Pirama Arumuga Nainar5231aff2018-08-08 10:33:24 -070034#include <memory>
Josh Gaoe7daf572016-09-21 12:37:10 -070035#include <mutex>
Josh Gaod2ea0652018-08-10 14:28:24 -070036#include <set>
Josh Gao0f3312a2017-04-12 17:00:49 -070037#include <thread>
Dan Albertecce5032015-05-18 16:46:31 -070038
Joshua Duong64fab752020-01-21 13:19:42 -080039#include <adb/crypto/rsa_2048_key.h>
40#include <adb/crypto/x509_generator.h>
41#include <adb/tls/tls_connection.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080042#include <android-base/logging.h>
David Pursellc929c6f2016-03-01 08:58:26 -080043#include <android-base/parsenetaddress.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080044#include <android-base/stringprintf.h>
45#include <android-base/strings.h>
Josh Gaob39e4152017-08-16 16:57:01 -070046#include <android-base/thread_annotations.h>
Elliott Hughes88b4c852015-04-30 17:32:03 -070047
Josh Gao361148b2018-01-02 12:01:43 -080048#include <diagnose_usb.h>
49
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080050#include "adb.h"
Elliott Hughes801066a2016-06-29 17:42:01 -070051#include "adb_auth.h"
Josh Gao395b86a2018-01-28 20:32:46 -080052#include "adb_io.h"
Josh Gao9e09a972016-11-29 09:40:29 -080053#include "adb_trace.h"
Elliott Hughes88b4c852015-04-30 17:32:03 -070054#include "adb_utils.h"
Josh Gaob51193a2019-06-28 13:50:37 -070055#include "fdevent/fdevent.h"
Josh Gaob0182892018-07-31 14:12:59 -070056#include "sysdeps/chrono.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080057
Joshua Duong64fab752020-01-21 13:19:42 -080058using namespace adb::crypto;
59using namespace adb::tls;
Josh Gao8aa57d22019-02-12 13:59:03 -080060using android::base::ScopedLockAssertion;
Joshua Duong64fab752020-01-21 13:19:42 -080061using TlsError = TlsConnection::TlsError;
Josh Gao8aa57d22019-02-12 13:59:03 -080062
Luis Hector Chavez0aeda102018-04-20 10:31:29 -070063static void remove_transport(atransport* transport);
Josh Gao14ed9f92019-12-09 13:45:31 -080064static void transport_destroy(atransport* transport);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080065
Josh Gaob39e4152017-08-16 16:57:01 -070066// TODO: unordered_map<TransportId, atransport*>
Josh Gaoe3a87d02015-11-11 17:56:12 -080067static auto& transport_list = *new std::list<atransport*>();
68static auto& pending_list = *new std::list<atransport*>();
Benoit Goby3f9f9ce2013-03-29 18:22:36 -070069
Josh Gaoaaa82f72017-08-17 13:50:51 -070070static auto& transport_lock = *new std::recursive_mutex();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080071
Todd Kennedyaff9c672015-11-10 00:03:25 +000072const char* const kFeatureShell2 = "shell_v2";
73const char* const kFeatureCmd = "cmd";
Josh Gaoa2cf3752016-12-05 17:11:34 -080074const char* const kFeatureStat2 = "stat_v2";
Josh Gao7b083072019-08-07 14:23:17 -070075const char* const kFeatureLs2 = "ls_v2";
Josh Gao210b63f2017-02-22 17:07:01 -080076const char* const kFeatureLibusb = "libusb";
Dan Albert27983bc2017-05-23 14:30:00 -070077const char* const kFeaturePushSync = "push_sync";
Dario Frenidcb4c362018-10-04 16:26:40 +010078const char* const kFeatureApex = "apex";
Josh Gao281aab72018-10-22 13:00:05 -070079const char* const kFeatureFixedPushMkdir = "fixed_push_mkdir";
Alex Buynytskyye1fa8142019-01-17 13:13:56 -080080const char* const kFeatureAbb = "abb";
Josh Gao9eeb9f72019-02-20 13:01:40 -080081const char* const kFeatureFixedPushSymlinkTimestamp = "fixed_push_symlink_timestamp";
Alex Buynytskyy4f3fa052019-02-21 14:22:51 -080082const char* const kFeatureAbbExec = "abb_exec";
Josh Gaof764d572019-07-11 14:15:32 -070083const char* const kFeatureRemountShell = "remount_shell";
Shukang Zhou420ad552020-02-13 17:01:39 -080084const char* const kFeatureTrackApp = "track_app";
Todd Kennedyaff9c672015-11-10 00:03:25 +000085
Luis Hector Chavezda74b902018-04-17 14:25:04 -070086namespace {
87
Josh Gao5c47e9f2018-07-31 18:28:32 -070088#if ADB_HOST
Luis Hector Chavez0aeda102018-04-20 10:31:29 -070089// Tracks and handles atransport*s that are attempting reconnection.
90class ReconnectHandler {
91 public:
92 ReconnectHandler() = default;
93 ~ReconnectHandler() = default;
94
95 // Starts the ReconnectHandler thread.
96 void Start();
97
98 // Requests the ReconnectHandler thread to stop.
99 void Stop();
100
101 // Adds the atransport* to the queue of reconnect attempts.
102 void TrackTransport(atransport* transport);
103
Josh Gao13cb8c02018-08-10 14:44:54 -0700104 // Wake up the ReconnectHandler thread to have it check for kicked transports.
105 void CheckForKicked();
106
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700107 private:
108 // The main thread loop.
109 void Run();
110
111 // Tracks a reconnection attempt.
112 struct ReconnectAttempt {
113 atransport* transport;
Josh Gaoc4deb392018-07-30 18:51:55 -0700114 std::chrono::steady_clock::time_point reconnect_time;
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700115 size_t attempts_left;
Josh Gaob0182892018-07-31 14:12:59 -0700116
117 bool operator<(const ReconnectAttempt& rhs) const {
Josh Gaod2ea0652018-08-10 14:28:24 -0700118 if (reconnect_time == rhs.reconnect_time) {
119 return reinterpret_cast<uintptr_t>(transport) <
120 reinterpret_cast<uintptr_t>(rhs.transport);
121 }
122 return reconnect_time < rhs.reconnect_time;
Josh Gaob0182892018-07-31 14:12:59 -0700123 }
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700124 };
125
126 // Only retry for up to one minute.
Josh Gaob0182892018-07-31 14:12:59 -0700127 static constexpr const std::chrono::seconds kDefaultTimeout = 10s;
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700128 static constexpr const size_t kMaxAttempts = 6;
129
130 // Protects all members.
131 std::mutex reconnect_mutex_;
132 bool running_ GUARDED_BY(reconnect_mutex_) = true;
133 std::thread handler_thread_;
134 std::condition_variable reconnect_cv_;
Josh Gaod2ea0652018-08-10 14:28:24 -0700135 std::set<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700136
137 DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
138};
139
140void ReconnectHandler::Start() {
141 check_main_thread();
142 handler_thread_ = std::thread(&ReconnectHandler::Run, this);
143}
144
145void ReconnectHandler::Stop() {
146 check_main_thread();
147 {
148 std::lock_guard<std::mutex> lock(reconnect_mutex_);
149 running_ = false;
150 }
151 reconnect_cv_.notify_one();
152 handler_thread_.join();
153
154 // Drain the queue to free all resources.
155 std::lock_guard<std::mutex> lock(reconnect_mutex_);
156 while (!reconnect_queue_.empty()) {
Josh Gaod2ea0652018-08-10 14:28:24 -0700157 ReconnectAttempt attempt = *reconnect_queue_.begin();
158 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700159 remove_transport(attempt.transport);
160 }
161}
162
163void ReconnectHandler::TrackTransport(atransport* transport) {
164 check_main_thread();
165 {
166 std::lock_guard<std::mutex> lock(reconnect_mutex_);
167 if (!running_) return;
Josh Gaob0182892018-07-31 14:12:59 -0700168 // Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
169 auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
170 reconnect_queue_.emplace(
171 ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700172 }
173 reconnect_cv_.notify_one();
174}
175
Josh Gao13cb8c02018-08-10 14:44:54 -0700176void ReconnectHandler::CheckForKicked() {
177 reconnect_cv_.notify_one();
178}
179
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700180void ReconnectHandler::Run() {
181 while (true) {
182 ReconnectAttempt attempt;
183 {
184 std::unique_lock<std::mutex> lock(reconnect_mutex_);
Josh Gao8aa57d22019-02-12 13:59:03 -0800185 ScopedLockAssertion assume_lock(reconnect_mutex_);
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700186
Josh Gaoc4deb392018-07-30 18:51:55 -0700187 if (!reconnect_queue_.empty()) {
188 // FIXME: libstdc++ (used on Windows) implements condition_variable with
189 // system_clock as its clock, so we're probably hosed if the clock changes,
190 // even if we use steady_clock throughout. This problem goes away once we
191 // switch to libc++.
Josh Gaod2ea0652018-08-10 14:28:24 -0700192 reconnect_cv_.wait_until(lock, reconnect_queue_.begin()->reconnect_time);
Josh Gaoc4deb392018-07-30 18:51:55 -0700193 } else {
194 reconnect_cv_.wait(lock);
195 }
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700196
197 if (!running_) return;
Josh Gao13cb8c02018-08-10 14:44:54 -0700198
199 // Scan the whole list for kicked transports, so that we immediately handle an explicit
200 // disconnect request.
201 bool kicked = false;
202 for (auto it = reconnect_queue_.begin(); it != reconnect_queue_.end();) {
203 if (it->transport->kicked()) {
204 D("transport %s was kicked. giving up on it.", it->transport->serial.c_str());
205 remove_transport(it->transport);
206 it = reconnect_queue_.erase(it);
207 } else {
208 ++it;
209 }
210 kicked = true;
211 }
212
Josh Gaoc4deb392018-07-30 18:51:55 -0700213 if (reconnect_queue_.empty()) continue;
214
Josh Gao13cb8c02018-08-10 14:44:54 -0700215 // Go back to sleep if we either woke up spuriously, or we were woken up to remove
216 // a kicked transport, and the first transport isn't ready for reconnection yet.
Josh Gaoc4deb392018-07-30 18:51:55 -0700217 auto now = std::chrono::steady_clock::now();
Josh Gaod2ea0652018-08-10 14:28:24 -0700218 if (reconnect_queue_.begin()->reconnect_time > now) {
Josh Gaoc4deb392018-07-30 18:51:55 -0700219 continue;
220 }
221
Josh Gaod2ea0652018-08-10 14:28:24 -0700222 attempt = *reconnect_queue_.begin();
223 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700224 }
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700225 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700226
Josh Gaod24580d2018-08-30 11:37:00 -0700227 switch (attempt.transport->Reconnect()) {
228 case ReconnectResult::Retry: {
229 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
230 if (attempt.attempts_left == 0) {
231 D("transport %s exceeded the number of retry attempts. giving up on it.",
232 attempt.transport->serial.c_str());
233 remove_transport(attempt.transport);
234 continue;
235 }
236
237 std::lock_guard<std::mutex> lock(reconnect_mutex_);
238 reconnect_queue_.emplace(ReconnectAttempt{
239 attempt.transport,
240 std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
241 attempt.attempts_left - 1});
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700242 continue;
243 }
244
Josh Gaod24580d2018-08-30 11:37:00 -0700245 case ReconnectResult::Success:
246 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
247 register_transport(attempt.transport);
248 continue;
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700249
Josh Gaod24580d2018-08-30 11:37:00 -0700250 case ReconnectResult::Abort:
251 D("cancelling reconnection attempt to %s.", attempt.transport->serial.c_str());
252 remove_transport(attempt.transport);
253 continue;
254 }
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700255 }
256}
257
258static auto& reconnect_handler = *new ReconnectHandler();
259
Josh Gao5c47e9f2018-07-31 18:28:32 -0700260#endif
261
Luis Hector Chavezda74b902018-04-17 14:25:04 -0700262} // namespace
263
Josh Gaob39e4152017-08-16 16:57:01 -0700264TransportId NextTransportId() {
265 static std::atomic<TransportId> next(1);
266 return next++;
267}
268
Josh Gao3a2172b2019-03-28 15:47:44 -0700269void Connection::Reset() {
270 LOG(INFO) << "Connection::Reset(): stopping";
271 Stop();
272}
273
Josh Gao715fe602018-02-16 13:24:58 -0800274BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
275 : underlying_(std::move(connection)) {}
276
277BlockingConnectionAdapter::~BlockingConnectionAdapter() {
278 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
279 Stop();
280}
281
282void BlockingConnectionAdapter::Start() {
Josh Gao13781e82018-04-03 12:55:18 -0700283 std::lock_guard<std::mutex> lock(mutex_);
284 if (started_) {
285 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
286 << "): started multiple times";
287 }
288
Joshua Duong64fab752020-01-21 13:19:42 -0800289 StartReadThread();
Josh Gao715fe602018-02-16 13:24:58 -0800290
291 write_thread_ = std::thread([this]() {
292 LOG(INFO) << this->transport_name_ << ": write thread spawning";
293 while (true) {
294 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao8aa57d22019-02-12 13:59:03 -0800295 ScopedLockAssertion assume_locked(mutex_);
Josh Gao13781e82018-04-03 12:55:18 -0700296 cv_.wait(lock, [this]() REQUIRES(mutex_) {
297 return this->stopped_ || !this->write_queue_.empty();
298 });
299
Josh Gao715fe602018-02-16 13:24:58 -0800300 if (this->stopped_) {
301 return;
302 }
303
304 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
305 this->write_queue_.pop_front();
306 lock.unlock();
307
308 if (!this->underlying_->Write(packet.get())) {
309 break;
310 }
311 }
312 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
313 });
Josh Gao13781e82018-04-03 12:55:18 -0700314
315 started_ = true;
Josh Gao715fe602018-02-16 13:24:58 -0800316}
317
Joshua Duong64fab752020-01-21 13:19:42 -0800318void BlockingConnectionAdapter::StartReadThread() {
319 read_thread_ = std::thread([this]() {
320 LOG(INFO) << this->transport_name_ << ": read thread spawning";
321 while (true) {
322 auto packet = std::make_unique<apacket>();
323 if (!underlying_->Read(packet.get())) {
324 PLOG(INFO) << this->transport_name_ << ": read failed";
325 break;
326 }
327
328 bool got_stls_cmd = false;
329 if (packet->msg.command == A_STLS) {
330 got_stls_cmd = true;
331 }
332
333 read_callback_(this, std::move(packet));
334
335 // If we received the STLS packet, we are about to perform the TLS
336 // handshake. So this read thread must stop and resume after the
337 // handshake completes otherwise this will interfere in the process.
338 if (got_stls_cmd) {
339 LOG(INFO) << this->transport_name_
340 << ": Received STLS packet. Stopping read thread.";
341 return;
342 }
343 }
344 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
345 });
346}
347
348bool BlockingConnectionAdapter::DoTlsHandshake(RSA* key, std::string* auth_key) {
349 std::lock_guard<std::mutex> lock(mutex_);
350 if (read_thread_.joinable()) {
351 read_thread_.join();
352 }
353 bool success = this->underlying_->DoTlsHandshake(key, auth_key);
354 StartReadThread();
355 return success;
356}
357
Josh Gao3a2172b2019-03-28 15:47:44 -0700358void BlockingConnectionAdapter::Reset() {
359 {
360 std::lock_guard<std::mutex> lock(mutex_);
361 if (!started_) {
362 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
363 return;
364 }
365
366 if (stopped_) {
367 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
368 << "): already stopped";
369 return;
370 }
371 }
372
373 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): resetting";
374 this->underlying_->Reset();
375 Stop();
376}
377
Josh Gao715fe602018-02-16 13:24:58 -0800378void BlockingConnectionAdapter::Stop() {
Josh Gao13781e82018-04-03 12:55:18 -0700379 {
380 std::lock_guard<std::mutex> lock(mutex_);
381 if (!started_) {
382 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
383 return;
384 }
Josh Gao715fe602018-02-16 13:24:58 -0800385
Josh Gao13781e82018-04-03 12:55:18 -0700386 if (stopped_) {
387 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
388 << "): already stopped";
389 return;
390 }
391
392 stopped_ = true;
393 }
Josh Gao715fe602018-02-16 13:24:58 -0800394
395 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
396
397 this->underlying_->Close();
Josh Gao715fe602018-02-16 13:24:58 -0800398 this->cv_.notify_one();
Josh Gao13781e82018-04-03 12:55:18 -0700399
400 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
401 std::thread read_thread;
402 std::thread write_thread;
403
404 {
405 std::lock_guard<std::mutex> lock(mutex_);
406 read_thread = std::move(read_thread_);
407 write_thread = std::move(write_thread_);
408 }
409
410 read_thread.join();
411 write_thread.join();
Josh Gao715fe602018-02-16 13:24:58 -0800412
413 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
414 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
415}
416
417bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
418 {
Josh Gao13781e82018-04-03 12:55:18 -0700419 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao715fe602018-02-16 13:24:58 -0800420 write_queue_.emplace_back(std::move(packet));
421 }
422
423 cv_.notify_one();
424 return true;
425}
426
Joshua Duong64fab752020-01-21 13:19:42 -0800427FdConnection::FdConnection(unique_fd fd) : fd_(std::move(fd)) {}
428
429FdConnection::~FdConnection() {}
430
431bool FdConnection::DispatchRead(void* buf, size_t len) {
432 if (tls_ != nullptr) {
433 // The TlsConnection doesn't allow 0 byte reads
434 if (len == 0) {
435 return true;
436 }
437 return tls_->ReadFully(buf, len);
438 }
439
440 return ReadFdExactly(fd_.get(), buf, len);
441}
442
443bool FdConnection::DispatchWrite(void* buf, size_t len) {
444 if (tls_ != nullptr) {
445 // The TlsConnection doesn't allow 0 byte writes
446 if (len == 0) {
447 return true;
448 }
449 return tls_->WriteFully(std::string_view(reinterpret_cast<const char*>(buf), len));
450 }
451
452 return WriteFdExactly(fd_.get(), buf, len);
453}
454
Josh Gao395b86a2018-01-28 20:32:46 -0800455bool FdConnection::Read(apacket* packet) {
Joshua Duong64fab752020-01-21 13:19:42 -0800456 if (!DispatchRead(&packet->msg, sizeof(amessage))) {
Josh Gao395b86a2018-01-28 20:32:46 -0800457 D("remote local: read terminated (message)");
458 return false;
459 }
460
Josh Gao839b9322018-02-05 18:49:10 -0800461 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gaob14756a2018-02-02 14:38:04 -0800462 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
463 return false;
464 }
465
Josh Gao839b9322018-02-05 18:49:10 -0800466 packet->payload.resize(packet->msg.data_length);
467
Joshua Duong64fab752020-01-21 13:19:42 -0800468 if (!DispatchRead(&packet->payload[0], packet->payload.size())) {
Josh Gao395b86a2018-01-28 20:32:46 -0800469 D("remote local: terminated (data)");
470 return false;
471 }
472
473 return true;
474}
475
476bool FdConnection::Write(apacket* packet) {
Joshua Duong64fab752020-01-21 13:19:42 -0800477 if (!DispatchWrite(&packet->msg, sizeof(packet->msg))) {
Josh Gao395b86a2018-01-28 20:32:46 -0800478 D("remote local: write terminated");
479 return false;
480 }
481
Josh Gao839b9322018-02-05 18:49:10 -0800482 if (packet->msg.data_length) {
Joshua Duong64fab752020-01-21 13:19:42 -0800483 if (!DispatchWrite(&packet->payload[0], packet->msg.data_length)) {
Josh Gao839b9322018-02-05 18:49:10 -0800484 D("remote local: write terminated");
485 return false;
486 }
487 }
488
Josh Gao395b86a2018-01-28 20:32:46 -0800489 return true;
490}
491
Joshua Duong64fab752020-01-21 13:19:42 -0800492bool FdConnection::DoTlsHandshake(RSA* key, std::string* auth_key) {
493 bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
494 if (!EVP_PKEY_set1_RSA(evp_pkey.get(), key)) {
495 LOG(ERROR) << "EVP_PKEY_set1_RSA failed";
496 return false;
497 }
498 auto x509 = GenerateX509Certificate(evp_pkey.get());
499 auto x509_str = X509ToPEMString(x509.get());
500 auto evp_str = Key::ToPEMString(evp_pkey.get());
501#if ADB_HOST
502 tls_ = TlsConnection::Create(TlsConnection::Role::Client,
503#else
504 tls_ = TlsConnection::Create(TlsConnection::Role::Server,
505#endif
506 x509_str, evp_str, fd_);
507 CHECK(tls_);
508#if ADB_HOST
509 // TLS 1.3 gives the client no message if the server rejected the
510 // certificate. This will enable a check in the tls connection to check
511 // whether the client certificate got rejected. Note that this assumes
512 // that, on handshake success, the server speaks first.
513 tls_->EnableClientPostHandshakeCheck(true);
514 // Add callback to set the certificate when server issues the
515 // CertificateRequest.
516 tls_->SetCertificateCallback(adb_tls_set_certificate);
517 // Allow any server certificate
518 tls_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
519#else
520 // Add callback to check certificate against a list of known public keys
521 tls_->SetCertVerifyCallback(
522 [auth_key](X509_STORE_CTX* ctx) { return adbd_tls_verify_cert(ctx, auth_key); });
523 // Add the list of allowed client CA issuers
524 auto ca_list = adbd_tls_client_ca_list();
525 tls_->SetClientCAList(ca_list.get());
526#endif
527
528 auto err = tls_->DoHandshake();
529 if (err == TlsError::Success) {
530 return true;
531 }
532
533 tls_.reset();
534 return false;
535}
536
Josh Gao395b86a2018-01-28 20:32:46 -0800537void FdConnection::Close() {
538 adb_shutdown(fd_.get());
539 fd_.reset();
540}
541
Josh Gao67ac3792016-10-06 13:31:44 -0700542void send_packet(apacket* p, atransport* t) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800543 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayee7b44d2017-12-07 11:40:00 -0800544 // compute a checksum for connection/auth packets for compatibility reasons
545 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
546 p->msg.data_check = 0;
547 } else {
548 p->msg.data_check = calculate_apacket_checksum(p);
549 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800550
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700551 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800552
Yi Kong86e67182018-07-13 18:15:16 -0700553 if (t == nullptr) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700554 LOG(FATAL) << "Transport is null";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800555 }
556
Josh Gao715fe602018-02-16 13:24:58 -0800557 if (t->Write(p) != 0) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700558 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao715fe602018-02-16 13:24:58 -0800559 t->Kick();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800560 }
561}
562
Josh Gao3a2172b2019-03-28 15:47:44 -0700563void kick_transport(atransport* t, bool reset) {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700564 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuid78ed222016-04-05 13:50:44 -0700565 // As kick_transport() can be called from threads without guarantee that t is valid,
566 // check if the transport is in transport_list first.
Josh Gaob39e4152017-08-16 16:57:01 -0700567 //
568 // TODO(jmgao): WTF? Is this actually true?
Yabin Cuid78ed222016-04-05 13:50:44 -0700569 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Josh Gao3a2172b2019-03-28 15:47:44 -0700570 if (reset) {
571 t->Reset();
572 } else {
573 t->Kick();
574 }
Yabin Cuid78ed222016-04-05 13:50:44 -0700575 }
Josh Gao13cb8c02018-08-10 14:44:54 -0700576
577#if ADB_HOST
578 reconnect_handler.CheckForKicked();
579#endif
Yabin Cui4d64fd82015-08-27 12:03:11 -0700580}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800581
582static int transport_registration_send = -1;
583static int transport_registration_recv = -1;
Josh Gao9528df22018-05-14 11:14:33 -0700584static fdevent* transport_registration_fde;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800585
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800586#if ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800587
588/* this adds support required by the 'track-devices' service.
589 * this is used to send the content of "list_transport" to any
590 * number of client connections that want it through a single
591 * live TCP connection
592 */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800593struct device_tracker {
Josh Gao0d6aa992016-11-22 14:32:34 -0800594 asocket socket;
Josh Gao5cb76ce2018-02-12 17:24:00 -0800595 bool update_needed = false;
596 bool long_output = false;
597 device_tracker* next = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800598};
599
600/* linked list of all device trackers */
Josh Gao0d6aa992016-11-22 14:32:34 -0800601static device_tracker* device_tracker_list;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800602
Josh Gao0d6aa992016-11-22 14:32:34 -0800603static void device_tracker_remove(device_tracker* tracker) {
604 device_tracker** pnode = &device_tracker_list;
605 device_tracker* node = *pnode;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800606
Josh Gaoaaa82f72017-08-17 13:50:51 -0700607 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800608 while (node) {
609 if (node == tracker) {
610 *pnode = node->next;
611 break;
612 }
613 pnode = &node->next;
Josh Gao0d6aa992016-11-22 14:32:34 -0800614 node = *pnode;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800615 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800616}
617
Josh Gao0d6aa992016-11-22 14:32:34 -0800618static void device_tracker_close(asocket* socket) {
619 device_tracker* tracker = (device_tracker*)socket;
620 asocket* peer = socket->peer;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800621
Josh Gao0d6aa992016-11-22 14:32:34 -0800622 D("device tracker %p removed", tracker);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800623 if (peer) {
Yi Kong86e67182018-07-13 18:15:16 -0700624 peer->peer = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800625 peer->close(peer);
626 }
627 device_tracker_remove(tracker);
Josh Gao5cb76ce2018-02-12 17:24:00 -0800628 delete tracker;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800629}
630
Josh Gaocd2a5292018-03-07 16:52:28 -0800631static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800632 /* you can't read from a device tracker, close immediately */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800633 device_tracker_close(socket);
634 return -1;
635}
636
Elliott Hughes88b4c852015-04-30 17:32:03 -0700637static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughes88b4c852015-04-30 17:32:03 -0700638 asocket* peer = tracker->socket.peer;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800639
Josh Gaocd2a5292018-03-07 16:52:28 -0800640 apacket::payload_type data;
Josh Gaoa7d9d712018-02-01 13:17:50 -0800641 data.resize(4 + string.size());
642 char buf[5];
643 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
644 memcpy(&data[0], buf, 4);
645 memcpy(&data[4], string.data(), string.size());
646 return peer->enqueue(peer, std::move(data));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800647}
648
Elliott Hughes88b4c852015-04-30 17:32:03 -0700649static void device_tracker_ready(asocket* socket) {
650 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800651
Elliott Hughes88b4c852015-04-30 17:32:03 -0700652 // We want to send the device list when the tracker connects
653 // for the first time, even if no update occurred.
Josh Gao32124632017-08-14 18:57:54 -0700654 if (tracker->update_needed) {
655 tracker->update_needed = false;
Elliott Hughes3d792f42019-07-31 14:13:57 -0700656 device_tracker_send(tracker, list_transports(tracker->long_output));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800657 }
658}
659
Josh Gao32124632017-08-14 18:57:54 -0700660asocket* create_device_tracker(bool long_output) {
Josh Gao5cb76ce2018-02-12 17:24:00 -0800661 device_tracker* tracker = new device_tracker();
Elliott Hughese64126b2018-10-19 13:59:44 -0700662 if (tracker == nullptr) LOG(FATAL) << "cannot allocate device tracker";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800663
Josh Gao0d6aa992016-11-22 14:32:34 -0800664 D("device tracker %p created", tracker);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800665
666 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao0d6aa992016-11-22 14:32:34 -0800667 tracker->socket.ready = device_tracker_ready;
668 tracker->socket.close = device_tracker_close;
Josh Gao32124632017-08-14 18:57:54 -0700669 tracker->update_needed = true;
670 tracker->long_output = long_output;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800671
Josh Gao0d6aa992016-11-22 14:32:34 -0800672 tracker->next = device_tracker_list;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800673 device_tracker_list = tracker;
674
675 return &tracker->socket;
676}
677
Josh Gao1e3bf732017-05-03 22:37:10 -0700678// Check if all of the USB transports are connected.
679bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700680 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao1e3bf732017-05-03 22:37:10 -0700681 for (const auto& t : transport_list) {
682 if (!fn(t)) {
683 return false;
684 }
685 }
686 for (const auto& t : pending_list) {
687 if (!fn(t)) {
688 return false;
689 }
690 }
691 return true;
692}
693
Elliott Hughes88b4c852015-04-30 17:32:03 -0700694// Call this function each time the transport list has changed.
695void update_transports() {
Josh Gao1e3bf732017-05-03 22:37:10 -0700696 update_transport_status();
697
698 // Notify `adb track-devices` clients.
Elliott Hughes88b4c852015-04-30 17:32:03 -0700699 device_tracker* tracker = device_tracker_list;
700 while (tracker != nullptr) {
701 device_tracker* next = tracker->next;
702 // This may destroy the tracker if the connection is closed.
Elliott Hughes3d792f42019-07-31 14:13:57 -0700703 device_tracker_send(tracker, list_transports(tracker->long_output));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800704 tracker = next;
705 }
706}
Elliott Hughes88b4c852015-04-30 17:32:03 -0700707
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800708#else
Elliott Hughes88b4c852015-04-30 17:32:03 -0700709
710void update_transports() {
711 // Nothing to do on the device side.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800712}
Elliott Hughes88b4c852015-04-30 17:32:03 -0700713
Josh Gao0d6aa992016-11-22 14:32:34 -0800714#endif // ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800715
Josh Gao0d6aa992016-11-22 14:32:34 -0800716struct tmsg {
717 atransport* transport;
718 int action;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800719};
720
Josh Gao0d6aa992016-11-22 14:32:34 -0800721static int transport_read_action(int fd, struct tmsg* m) {
722 char* p = (char*)m;
723 int len = sizeof(*m);
724 int r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800725
Josh Gao0d6aa992016-11-22 14:32:34 -0800726 while (len > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800727 r = adb_read(fd, p, len);
Josh Gao0d6aa992016-11-22 14:32:34 -0800728 if (r > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800729 len -= r;
Josh Gao0d6aa992016-11-22 14:32:34 -0800730 p += r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800731 } else {
Yabin Cui815ad882015-09-02 17:44:28 -0700732 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800733 return -1;
734 }
735 }
736 return 0;
737}
738
Josh Gao0d6aa992016-11-22 14:32:34 -0800739static int transport_write_action(int fd, struct tmsg* m) {
740 char* p = (char*)m;
741 int len = sizeof(*m);
742 int r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800743
Josh Gao0d6aa992016-11-22 14:32:34 -0800744 while (len > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800745 r = adb_write(fd, p, len);
Josh Gao0d6aa992016-11-22 14:32:34 -0800746 if (r > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800747 len -= r;
Josh Gao0d6aa992016-11-22 14:32:34 -0800748 p += r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800749 } else {
Yabin Cui815ad882015-09-02 17:44:28 -0700750 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800751 return -1;
752 }
753 }
754 return 0;
755}
756
Josh Gao715fe602018-02-16 13:24:58 -0800757static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800758 tmsg m;
Josh Gao0d6aa992016-11-22 14:32:34 -0800759 atransport* t;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800760
Josh Gao0d6aa992016-11-22 14:32:34 -0800761 if (!(ev & FDE_READ)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800762 return;
763 }
764
Josh Gao0d6aa992016-11-22 14:32:34 -0800765 if (transport_read_action(_fd, &m)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700766 PLOG(FATAL) << "cannot read transport registration socket";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800767 }
768
769 t = m.transport;
770
Dan Albertbe8e54b2015-05-18 13:06:53 -0700771 if (m.action == 0) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700772 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800773
Josh Gaoe7daf572016-09-21 12:37:10 -0700774 {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700775 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaoe7daf572016-09-21 12:37:10 -0700776 transport_list.remove(t);
777 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800778
Dan Albertecce5032015-05-18 16:46:31 -0700779 delete t;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800780
781 update_transports();
782 return;
783 }
784
Mike Lockwoode45583f2009-08-08 12:37:44 -0400785 /* don't create transport threads for inaccessible devices */
Yabin Cui3cf1b362017-03-10 16:01:01 -0800786 if (t->GetConnectionState() != kCsNoPerm) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700787 // The connection gets a reference to the atransport. It will release it
788 // upon a read/write error.
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700789 t->connection()->SetTransportName(t->serial_name());
790 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao715fe602018-02-16 13:24:58 -0800791 if (!check_header(p.get(), t)) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700792 D("%s: remote read: bad header", t->serial.c_str());
Josh Gao715fe602018-02-16 13:24:58 -0800793 return false;
794 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800795
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700796 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "from remote", p.get());
Josh Gao715fe602018-02-16 13:24:58 -0800797 apacket* packet = p.release();
Mike Lockwoode45583f2009-08-08 12:37:44 -0400798
Josh Gao715fe602018-02-16 13:24:58 -0800799 // TODO: Does this need to run on the main thread?
800 fdevent_run_on_main_thread([packet, t]() { handle_packet(packet, t); });
801 return true;
802 });
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700803 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Josh Gao3a34bc52018-10-11 16:33:05 -0700804 LOG(INFO) << t->serial_name() << ": connection terminated: " << error;
Josh Gao715fe602018-02-16 13:24:58 -0800805 fdevent_run_on_main_thread([t]() {
806 handle_offline(t);
Josh Gao14ed9f92019-12-09 13:45:31 -0800807 transport_destroy(t);
Josh Gao715fe602018-02-16 13:24:58 -0800808 });
809 });
Mike Lockwoode45583f2009-08-08 12:37:44 -0400810
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700811 t->connection()->Start();
Josh Gao715fe602018-02-16 13:24:58 -0800812#if ADB_HOST
813 send_connect(t);
814#endif
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800815 }
816
Josh Gaoe7daf572016-09-21 12:37:10 -0700817 {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700818 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700819 auto it = std::find(pending_list.begin(), pending_list.end(), t);
820 if (it != pending_list.end()) {
821 pending_list.remove(t);
822 transport_list.push_front(t);
823 }
Josh Gaoe7daf572016-09-21 12:37:10 -0700824 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800825
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800826 update_transports();
827}
828
Josh Gao5c47e9f2018-07-31 18:28:32 -0700829#if ADB_HOST
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700830void init_reconnect_handler(void) {
831 reconnect_handler.Start();
832}
Josh Gao5c47e9f2018-07-31 18:28:32 -0700833#endif
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700834
Josh Gao0d6aa992016-11-22 14:32:34 -0800835void init_transport_registration(void) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800836 int s[2];
837
Josh Gao0d6aa992016-11-22 14:32:34 -0800838 if (adb_socketpair(s)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700839 PLOG(FATAL) << "cannot open transport registration socketpair";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800840 }
Yabin Cui815ad882015-09-02 17:44:28 -0700841 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800842
843 transport_registration_send = s[0];
844 transport_registration_recv = s[1];
845
Josh Gao9528df22018-05-14 11:14:33 -0700846 transport_registration_fde =
Yi Kong86e67182018-07-13 18:15:16 -0700847 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao9528df22018-05-14 11:14:33 -0700848 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao165460f2017-05-09 13:43:35 -0700849}
850
851void kick_all_transports() {
Josh Gao5c47e9f2018-07-31 18:28:32 -0700852#if ADB_HOST
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700853 reconnect_handler.Stop();
Josh Gao5c47e9f2018-07-31 18:28:32 -0700854#endif
Josh Gao165460f2017-05-09 13:43:35 -0700855 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gaoaaa82f72017-08-17 13:50:51 -0700856 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao165460f2017-05-09 13:43:35 -0700857 for (auto t : transport_list) {
858 t->Kick();
859 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800860}
861
Joshua Duong64fab752020-01-21 13:19:42 -0800862void kick_all_tcp_tls_transports() {
863 std::lock_guard<std::recursive_mutex> lock(transport_lock);
864 for (auto t : transport_list) {
865 if (t->IsTcpDevice() && t->use_tls) {
866 t->Kick();
867 }
868 }
869}
870
871#if !ADB_HOST
872void kick_all_transports_by_auth_key(std::string_view auth_key) {
873 std::lock_guard<std::recursive_mutex> lock(transport_lock);
874 for (auto t : transport_list) {
875 if (auth_key == t->auth_key) {
876 t->Kick();
877 }
878 }
879}
880#endif
881
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800882/* the fdevent select pump is single threaded */
Josh Gao3a34bc52018-10-11 16:33:05 -0700883void register_transport(atransport* transport) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800884 tmsg m;
885 m.transport = transport;
886 m.action = 1;
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700887 D("transport: %s registered", transport->serial.c_str());
Josh Gao0d6aa992016-11-22 14:32:34 -0800888 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700889 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800890 }
891}
892
Josh Gao0d6aa992016-11-22 14:32:34 -0800893static void remove_transport(atransport* transport) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800894 tmsg m;
895 m.transport = transport;
896 m.action = 0;
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700897 D("transport: %s removed", transport->serial.c_str());
Josh Gao0d6aa992016-11-22 14:32:34 -0800898 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700899 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800900 }
901}
902
Josh Gao14ed9f92019-12-09 13:45:31 -0800903static void transport_destroy(atransport* t) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700904 check_main_thread();
Yabin Cui4d64fd82015-08-27 12:03:11 -0700905 CHECK(t != nullptr);
Josh Gaoe7daf572016-09-21 12:37:10 -0700906
Josh Gao4d299742017-09-13 13:40:57 -0700907 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao14ed9f92019-12-09 13:45:31 -0800908 LOG(INFO) << "destroying transport " << t->serial_name();
909 t->connection()->Stop();
Josh Gao5c47e9f2018-07-31 18:28:32 -0700910#if ADB_HOST
Josh Gao14ed9f92019-12-09 13:45:31 -0800911 if (t->IsTcpDevice() && !t->kicked()) {
912 D("transport: %s destroy (attempting reconnection)", t->serial.c_str());
Josh Gaoeb656522018-12-04 01:07:50 -0800913
Josh Gao14ed9f92019-12-09 13:45:31 -0800914 // We need to clear the transport's keys, so that on the next connection, it tries
915 // again from the beginning.
916 t->ResetKeys();
917 reconnect_handler.TrackTransport(t);
918 return;
919 }
Josh Gao5c47e9f2018-07-31 18:28:32 -0700920#endif
921
Josh Gao14ed9f92019-12-09 13:45:31 -0800922 D("transport: %s destroy (kicking and closing)", t->serial.c_str());
923 remove_transport(t);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800924}
925
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700926static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao0d6aa992016-11-22 14:32:34 -0800927 bool sanitize_qual) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700928 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
929 return qual.empty();
Scott Anderson27042382012-05-30 18:11:27 -0700930
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700931 if (qual.empty()) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700932
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700933 const char* ptr = to_test.c_str();
Scott Anderson27042382012-05-30 18:11:27 -0700934 if (prefix) {
935 while (*prefix) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700936 if (*prefix++ != *ptr++) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700937 }
938 }
939
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700940 for (char ch : qual) {
Josh Gao0d6aa992016-11-22 14:32:34 -0800941 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700942 if (ch != *ptr++) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700943 }
944
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700945 /* Everything matched so far. Return true if *ptr is a NUL. */
946 return !*ptr;
Scott Anderson27042382012-05-30 18:11:27 -0700947}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800948
Josh Gaob39e4152017-08-16 16:57:01 -0700949atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
950 bool* is_ambiguous, std::string* error_out,
951 bool accept_any_state) {
Elliott Hughes67943d12015-10-07 14:55:10 -0700952 atransport* result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800953
Josh Gaob39e4152017-08-16 16:57:01 -0700954 if (transport_id != 0) {
955 *error_out =
956 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
957 } else if (serial) {
Elliott Hughes67943d12015-10-07 14:55:10 -0700958 *error_out = android::base::StringPrintf("device '%s' not found", serial);
959 } else if (type == kTransportLocal) {
960 *error_out = "no emulators found";
961 } else if (type == kTransportAny) {
962 *error_out = "no devices/emulators found";
963 } else {
964 *error_out = "no devices found";
965 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800966
Josh Gaoaaa82f72017-08-17 13:50:51 -0700967 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes67943d12015-10-07 14:55:10 -0700968 for (const auto& t : transport_list) {
Yabin Cui3cf1b362017-03-10 16:01:01 -0800969 if (t->GetConnectionState() == kCsNoPerm) {
David Pursell6e5c7eb2015-12-02 15:14:31 -0800970 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwoodadc16b32009-08-08 13:53:16 -0400971 continue;
972 }
Mike Lockwoode45583f2009-08-08 12:37:44 -0400973
Josh Gaob39e4152017-08-16 16:57:01 -0700974 if (transport_id) {
975 if (t->id == transport_id) {
976 result = t;
977 break;
978 }
979 } else if (serial) {
David Pursellc929c6f2016-03-01 08:58:26 -0800980 if (t->MatchesTarget(serial)) {
Scott Anderson27042382012-05-30 18:11:27 -0700981 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700982 *error_out = "more than one device";
Elliott Hughes67943d12015-10-07 14:55:10 -0700983 if (is_ambiguous) *is_ambiguous = true;
984 result = nullptr;
Scott Anderson27042382012-05-30 18:11:27 -0700985 break;
986 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800987 result = t;
Scott Anderson6dfaf4b2012-04-20 11:21:14 -0700988 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800989 } else {
Elliott Hughes3aec2ba2015-05-05 13:10:43 -0700990 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800991 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700992 *error_out = "more than one device";
Elliott Hughes67943d12015-10-07 14:55:10 -0700993 if (is_ambiguous) *is_ambiguous = true;
994 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800995 break;
996 }
997 result = t;
Elliott Hughes3aec2ba2015-05-05 13:10:43 -0700998 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800999 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -07001000 *error_out = "more than one emulator";
Elliott Hughes67943d12015-10-07 14:55:10 -07001001 if (is_ambiguous) *is_ambiguous = true;
1002 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001003 break;
1004 }
1005 result = t;
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001006 } else if (type == kTransportAny) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001007 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -07001008 *error_out = "more than one device/emulator";
Elliott Hughes67943d12015-10-07 14:55:10 -07001009 if (is_ambiguous) *is_ambiguous = true;
1010 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001011 break;
1012 }
1013 result = t;
1014 }
1015 }
1016 }
Josh Gaoe7daf572016-09-21 12:37:10 -07001017 lock.unlock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001018
Josh Gao7a7c5cb2018-05-04 16:04:49 -07001019 if (result && !accept_any_state) {
1020 // The caller requires an active transport.
1021 // Make sure that we're actually connected.
1022 ConnectionState state = result->GetConnectionState();
1023 switch (state) {
1024 case kCsConnecting:
1025 *error_out = "device still connecting";
1026 result = nullptr;
1027 break;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001028
Josh Gao7a7c5cb2018-05-04 16:04:49 -07001029 case kCsAuthorizing:
1030 *error_out = "device still authorizing";
1031 result = nullptr;
1032 break;
1033
1034 case kCsUnauthorized: {
1035 *error_out = "device unauthorized.\n";
1036 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
1037 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
1038 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
1039 *error_out += "\n";
1040 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
1041 *error_out += "Otherwise check for a confirmation dialog on your device.";
1042 result = nullptr;
1043 break;
1044 }
1045
1046 case kCsOffline:
1047 *error_out = "device offline";
1048 result = nullptr;
1049 break;
1050
1051 default:
1052 break;
1053 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001054 }
1055
1056 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -07001057 *error_out = "success";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001058 }
1059
1060 return result;
1061}
1062
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001063bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
1064 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao8aa57d22019-02-12 13:59:03 -08001065 ScopedLockAssertion assume_locked(mutex_);
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001066 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
1067 return connection_established_ready_;
1068 }) && connection_established_;
1069}
1070
1071void ConnectionWaitable::SetConnectionEstablished(bool success) {
1072 {
1073 std::lock_guard<std::mutex> lock(mutex_);
1074 if (connection_established_ready_) return;
1075 connection_established_ready_ = true;
1076 connection_established_ = success;
1077 D("connection established with %d", success);
1078 }
1079 cv_.notify_one();
1080}
1081
1082atransport::~atransport() {
1083 // If the connection callback had not been run before, run it now.
1084 SetConnectionEstablished(false);
1085}
1086
Yabin Cui3cf1b362017-03-10 16:01:01 -08001087int atransport::Write(apacket* p) {
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -07001088 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cui3cf1b362017-03-10 16:01:01 -08001089}
1090
Josh Gao3a2172b2019-03-28 15:47:44 -07001091void atransport::Reset() {
1092 if (!kicked_.exchange(true)) {
1093 LOG(INFO) << "resetting transport " << this << " " << this->serial;
1094 this->connection()->Reset();
1095 }
1096}
1097
Yabin Cuif2a9f9b2016-04-18 11:22:34 -07001098void atransport::Kick() {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001099 if (!kicked_.exchange(true)) {
Josh Gao3a2172b2019-03-28 15:47:44 -07001100 LOG(INFO) << "kicking transport " << this << " " << this->serial;
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -07001101 this->connection()->Stop();
Yabin Cuif2a9f9b2016-04-18 11:22:34 -07001102 }
1103}
1104
Yabin Cui3cf1b362017-03-10 16:01:01 -08001105ConnectionState atransport::GetConnectionState() const {
1106 return connection_state_;
1107}
1108
1109void atransport::SetConnectionState(ConnectionState state) {
1110 check_main_thread();
1111 connection_state_ = state;
1112}
1113
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -07001114void atransport::SetConnection(std::unique_ptr<Connection> connection) {
1115 std::lock_guard<std::mutex> lock(mutex_);
1116 connection_ = std::shared_ptr<Connection>(std::move(connection));
1117}
1118
Josh Gao3cd03be2018-02-28 14:44:23 -08001119std::string atransport::connection_state_name() const {
Yabin Cui3cf1b362017-03-10 16:01:01 -08001120 ConnectionState state = GetConnectionState();
1121 switch (state) {
Josh Gao0d6aa992016-11-22 14:32:34 -08001122 case kCsOffline:
1123 return "offline";
1124 case kCsBootloader:
1125 return "bootloader";
1126 case kCsDevice:
1127 return "device";
1128 case kCsHost:
1129 return "host";
1130 case kCsRecovery:
1131 return "recovery";
Tao Bao9d6eca52019-04-07 23:24:03 -07001132 case kCsRescue:
1133 return "rescue";
Josh Gao0d6aa992016-11-22 14:32:34 -08001134 case kCsNoPerm:
1135 return UsbNoPermissionsShortHelpText();
1136 case kCsSideload:
1137 return "sideload";
1138 case kCsUnauthorized:
1139 return "unauthorized";
Josh Gao7a7c5cb2018-05-04 16:04:49 -07001140 case kCsAuthorizing:
1141 return "authorizing";
1142 case kCsConnecting:
1143 return "connecting";
Josh Gao0d6aa992016-11-22 14:32:34 -08001144 default:
1145 return "unknown";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001146 }
1147}
1148
Tamas Berghammera1c60c02015-07-13 19:12:28 +01001149void atransport::update_version(int version, size_t payload) {
1150 protocol_version = std::min(version, A_VERSION);
1151 max_payload = std::min(payload, MAX_PAYLOAD);
1152}
1153
1154int atransport::get_protocol_version() const {
1155 return protocol_version;
1156}
1157
Joshua Duong64fab752020-01-21 13:19:42 -08001158int atransport::get_tls_version() const {
1159 return tls_version;
1160}
1161
Tamas Berghammera1c60c02015-07-13 19:12:28 +01001162size_t atransport::get_max_payload() const {
1163 return max_payload;
1164}
1165
Dan Albertbe8e54b2015-05-18 13:06:53 -07001166const FeatureSet& supported_features() {
David Pursella07dbad2015-09-22 10:43:08 -07001167 // Local static allocation to avoid global non-POD variables.
1168 static const FeatureSet* features = new FeatureSet{
Josh Gao9eeb9f72019-02-20 13:01:40 -08001169 kFeatureShell2,
1170 kFeatureCmd,
1171 kFeatureStat2,
Josh Gao7b083072019-08-07 14:23:17 -07001172 kFeatureLs2,
Josh Gao9eeb9f72019-02-20 13:01:40 -08001173 kFeatureFixedPushMkdir,
1174 kFeatureApex,
1175 kFeatureAbb,
1176 kFeatureFixedPushSymlinkTimestamp,
Alex Buynytskyy4f3fa052019-02-21 14:22:51 -08001177 kFeatureAbbExec,
Josh Gaof764d572019-07-11 14:15:32 -07001178 kFeatureRemountShell,
Shukang Zhou420ad552020-02-13 17:01:39 -08001179 kFeatureTrackApp,
Josh Gao62add5b2018-11-08 22:39:43 -08001180 // Increment ADB_SERVER_VERSION when adding a feature that adbd needs
1181 // to know about. Otherwise, the client can be stuck running an old
1182 // version of the server even after upgrading their copy of adb.
1183 // (http://b/24370690)
David Pursella07dbad2015-09-22 10:43:08 -07001184 };
1185
1186 return *features;
1187}
1188
1189std::string FeatureSetToString(const FeatureSet& features) {
Elliott Hughesc3462f42018-09-05 12:13:11 -07001190 return android::base::Join(features, ',');
David Pursella07dbad2015-09-22 10:43:08 -07001191}
1192
1193FeatureSet StringToFeatureSet(const std::string& features_string) {
David Pursell3d9072b2015-09-25 13:04:21 -07001194 if (features_string.empty()) {
1195 return FeatureSet();
1196 }
1197
Elliott Hughesc3462f42018-09-05 12:13:11 -07001198 auto names = android::base::Split(features_string, ",");
David Pursella07dbad2015-09-22 10:43:08 -07001199 return FeatureSet(names.begin(), names.end());
Dan Albertbe8e54b2015-05-18 13:06:53 -07001200}
1201
David Pursell22fc5e92015-09-30 13:35:42 -07001202bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao0d6aa992016-11-22 14:32:34 -08001203 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell22fc5e92015-09-30 13:35:42 -07001204}
1205
Dan Albertbe8e54b2015-05-18 13:06:53 -07001206bool atransport::has_feature(const std::string& feature) const {
1207 return features_.count(feature) > 0;
1208}
1209
David Pursella07dbad2015-09-22 10:43:08 -07001210void atransport::SetFeatures(const std::string& features_string) {
1211 features_ = StringToFeatureSet(features_string);
Dan Albertbe8e54b2015-05-18 13:06:53 -07001212}
1213
Yabin Cui2d4c1982015-08-28 15:09:44 -07001214void atransport::AddDisconnect(adisconnect* disconnect) {
1215 disconnects_.push_back(disconnect);
1216}
1217
1218void atransport::RemoveDisconnect(adisconnect* disconnect) {
1219 disconnects_.remove(disconnect);
1220}
1221
1222void atransport::RunDisconnects() {
Elliott Hughes85952832015-10-07 15:59:35 -07001223 for (const auto& disconnect : disconnects_) {
Yabin Cui2d4c1982015-08-28 15:09:44 -07001224 disconnect->func(disconnect->opaque, this);
1225 }
1226 disconnects_.clear();
1227}
1228
David Pursellc929c6f2016-03-01 08:58:26 -08001229bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001230 if (!serial.empty()) {
David Pursellc929c6f2016-03-01 08:58:26 -08001231 if (target == serial) {
1232 return true;
1233 } else if (type == kTransportLocal) {
1234 // Local transports can match [tcp:|udp:]<hostname>[:port].
1235 const char* local_target_ptr = target.c_str();
1236
1237 // For fastboot compatibility, ignore protocol prefixes.
1238 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao0d6aa992016-11-22 14:32:34 -08001239 android::base::StartsWith(target, "udp:")) {
David Pursellc929c6f2016-03-01 08:58:26 -08001240 local_target_ptr += 4;
1241 }
1242
1243 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1244 std::string serial_host, error;
1245 int serial_port = -1;
Josh Gao0d6aa992016-11-22 14:32:34 -08001246 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursellc929c6f2016-03-01 08:58:26 -08001247 // |target| may omit the port to default to ours.
1248 std::string target_host;
1249 int target_port = serial_port;
1250 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1251 nullptr, &error) &&
Josh Gao0d6aa992016-11-22 14:32:34 -08001252 serial_host == target_host && serial_port == target_port) {
David Pursellc929c6f2016-03-01 08:58:26 -08001253 return true;
1254 }
1255 }
1256 }
1257 }
1258
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001259 return (target == devpath) || qual_match(target, "product:", product, false) ||
1260 qual_match(target, "model:", model, true) ||
1261 qual_match(target, "device:", device, false);
David Pursellc929c6f2016-03-01 08:58:26 -08001262}
1263
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001264void atransport::SetConnectionEstablished(bool success) {
1265 connection_waitable_->SetConnectionEstablished(success);
1266}
1267
Josh Gaod24580d2018-08-30 11:37:00 -07001268ReconnectResult atransport::Reconnect() {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001269 return reconnect_(this);
1270}
1271
Elliott Hughes88b4c852015-04-30 17:32:03 -07001272#if ADB_HOST
1273
Josh Gaob39e4152017-08-16 16:57:01 -07001274// We use newline as our delimiter, make sure to never output it.
1275static std::string sanitize(std::string str, bool alphanumeric) {
1276 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1277 : [](const char c) { return c == '\n'; };
1278 std::replace_if(str.begin(), str.end(), pred, '_');
1279 return str;
1280}
1281
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001282static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob39e4152017-08-16 16:57:01 -07001283 bool alphanumeric) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001284 if (value.empty()) {
Scott Anderson27042382012-05-30 18:11:27 -07001285 return;
Scott Anderson27042382012-05-30 18:11:27 -07001286 }
1287
Elliott Hughes88b4c852015-04-30 17:32:03 -07001288 *result += ' ';
1289 *result += key;
Josh Gaob39e4152017-08-16 16:57:01 -07001290 *result += sanitize(value, alphanumeric);
Scott Anderson27042382012-05-30 18:11:27 -07001291}
1292
Josh Gao0d6aa992016-11-22 14:32:34 -08001293static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001294 std::string serial = t->serial;
1295 if (serial.empty()) {
Dan Alberta8c34142015-05-06 16:48:52 -07001296 serial = "(no serial number)";
Elliott Hughes88b4c852015-04-30 17:32:03 -07001297 }
Scott Anderson27042382012-05-30 18:11:27 -07001298
1299 if (!long_listing) {
Elliott Hughes88b4c852015-04-30 17:32:03 -07001300 *result += serial;
1301 *result += '\t';
1302 *result += t->connection_state_name();
Scott Anderson27042382012-05-30 18:11:27 -07001303 } else {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001304 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1305 t->connection_state_name().c_str());
Scott Anderson27042382012-05-30 18:11:27 -07001306
Elliott Hughes88b4c852015-04-30 17:32:03 -07001307 append_transport_info(result, "", t->devpath, false);
1308 append_transport_info(result, "product:", t->product, false);
1309 append_transport_info(result, "model:", t->model, true);
1310 append_transport_info(result, "device:", t->device, false);
Josh Gaob39e4152017-08-16 16:57:01 -07001311
1312 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1313 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1314 *result += " transport_id:";
1315 *result += std::to_string(t->id);
Scott Anderson27042382012-05-30 18:11:27 -07001316 }
Elliott Hughes88b4c852015-04-30 17:32:03 -07001317 *result += '\n';
Scott Anderson27042382012-05-30 18:11:27 -07001318}
1319
Elliott Hughes88b4c852015-04-30 17:32:03 -07001320std::string list_transports(bool long_listing) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001321 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov4dd35012017-12-17 10:56:07 +00001322
1323 auto sorted_transport_list = transport_list;
1324 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1325 if (x->type != y->type) {
1326 return x->type < y->type;
1327 }
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001328 return x->serial < y->serial;
Artem Iglikov4dd35012017-12-17 10:56:07 +00001329 });
1330
1331 std::string result;
1332 for (const auto& t : sorted_transport_list) {
Elliott Hughes88b4c852015-04-30 17:32:03 -07001333 append_transport(t, &result, long_listing);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001334 }
Elliott Hughes88b4c852015-04-30 17:32:03 -07001335 return result;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001336}
1337
Josh Gao3a2172b2019-03-28 15:47:44 -07001338void close_usb_devices(std::function<bool(const atransport*)> predicate, bool reset) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001339 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao4e562502016-10-27 14:01:08 -07001340 for (auto& t : transport_list) {
1341 if (predicate(t)) {
Josh Gao3a2172b2019-03-28 15:47:44 -07001342 if (reset) {
1343 t->Reset();
1344 } else {
1345 t->Kick();
1346 }
Josh Gao4e562502016-10-27 14:01:08 -07001347 }
1348 }
1349}
1350
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001351/* hack for osx */
Josh Gao3a2172b2019-03-28 15:47:44 -07001352void close_usb_devices(bool reset) {
1353 close_usb_devices([](const atransport*) { return true; }, reset);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001354}
Josh Gao0d6aa992016-11-22 14:32:34 -08001355#endif // ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001356
Josh Gao597044d2018-08-08 16:20:14 -07001357bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
Joshua Duong64fab752020-01-21 13:19:42 -08001358 atransport::ReconnectCallback reconnect, bool use_tls, int* error) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001359 atransport* t = new atransport(std::move(reconnect), kCsOffline);
Joshua Duong64fab752020-01-21 13:19:42 -08001360 t->use_tls = use_tls;
David 'Digit' Turner58f59682011-01-06 14:11:07 +01001361
Josh Gaoa3a71472018-08-02 13:58:24 -07001362 D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
Josh Gaofa3107e2018-07-25 17:21:49 -07001363 if (init_socket_transport(t, std::move(s), port, local) < 0) {
Dan Albertecce5032015-05-18 16:46:31 -07001364 delete t;
Josh Gao597044d2018-08-08 16:20:14 -07001365 if (error) *error = errno;
1366 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001367 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001368
Josh Gaoaaa82f72017-08-17 13:50:51 -07001369 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes85952832015-10-07 15:59:35 -07001370 for (const auto& transport : pending_list) {
Josh Gaoa3a71472018-08-02 13:58:24 -07001371 if (serial == transport->serial) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001372 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao0d6aa992016-11-22 14:32:34 -08001373 << " is already in pending_list and fails to register";
Dan Albertecce5032015-05-18 16:46:31 -07001374 delete t;
Josh Gao597044d2018-08-08 16:20:14 -07001375 if (error) *error = EALREADY;
1376 return false;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001377 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001378 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001379
Elliott Hughes85952832015-10-07 15:59:35 -07001380 for (const auto& transport : transport_list) {
Josh Gaoa3a71472018-08-02 13:58:24 -07001381 if (serial == transport->serial) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001382 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao0d6aa992016-11-22 14:32:34 -08001383 << " is already in transport_list and fails to register";
Dan Albertecce5032015-05-18 16:46:31 -07001384 delete t;
Josh Gao597044d2018-08-08 16:20:14 -07001385 if (error) *error = EALREADY;
1386 return false;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001387 }
1388 }
1389
Josh Gaoa3a71472018-08-02 13:58:24 -07001390 t->serial = std::move(serial);
Dan Albertecce5032015-05-18 16:46:31 -07001391 pending_list.push_front(t);
Josh Gaoe7daf572016-09-21 12:37:10 -07001392
1393 lock.unlock();
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001394
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001395 auto waitable = t->connection_waitable();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001396 register_transport(t);
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001397
Luis Hector Chavez25bc41c2018-05-01 17:12:16 -07001398 if (local == 1) {
1399 // Do not wait for emulator transports.
Josh Gao597044d2018-08-08 16:20:14 -07001400 return true;
Luis Hector Chavez25bc41c2018-05-01 17:12:16 -07001401 }
1402
Josh Gao597044d2018-08-08 16:20:14 -07001403 if (!waitable->WaitForConnection(std::chrono::seconds(10))) {
1404 if (error) *error = ETIMEDOUT;
1405 return false;
1406 }
1407
1408 if (t->GetConnectionState() == kCsUnauthorized) {
1409 if (error) *error = EPERM;
1410 return false;
1411 }
1412
1413 return true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001414}
1415
Mike Lockwood81ffe172009-10-11 23:04:18 -04001416#if ADB_HOST
Josh Gao0d6aa992016-11-22 14:32:34 -08001417atransport* find_transport(const char* serial) {
Dan Albertecce5032015-05-18 16:46:31 -07001418 atransport* result = nullptr;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001419
Josh Gaoaaa82f72017-08-17 13:50:51 -07001420 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui4d64fd82015-08-27 12:03:11 -07001421 for (auto& t : transport_list) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001422 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertecce5032015-05-18 16:46:31 -07001423 result = t;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001424 break;
1425 }
Dan Albertecce5032015-05-18 16:46:31 -07001426 }
Mike Lockwood81ffe172009-10-11 23:04:18 -04001427
Dan Albertecce5032015-05-18 16:46:31 -07001428 return result;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001429}
1430
Yabin Cui4d64fd82015-08-27 12:03:11 -07001431void kick_all_tcp_devices() {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001432 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui4d64fd82015-08-27 12:03:11 -07001433 for (auto& t : transport_list) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001434 if (t->IsTcpDevice()) {
Yabin Cui4e222292015-08-31 11:50:24 -07001435 // Kicking breaks the read_transport thread of this transport out of any read, then
1436 // the read_transport thread will notify the main thread to make this transport
1437 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cui4d64fd82015-08-27 12:03:11 -07001438 // Finally, this transport will be closed and freed in the main thread.
Yabin Cuif2a9f9b2016-04-18 11:22:34 -07001439 t->Kick();
Mike Lockwood01c2c302010-05-24 10:44:35 -04001440 }
Dan Albertecce5032015-05-18 16:46:31 -07001441 }
Josh Gao13cb8c02018-08-10 14:44:54 -07001442#if ADB_HOST
1443 reconnect_handler.CheckForKicked();
1444#endif
Mike Lockwood01c2c302010-05-24 10:44:35 -04001445}
1446
Mike Lockwood81ffe172009-10-11 23:04:18 -04001447#endif
1448
Josh Gao0d6aa992016-11-22 14:32:34 -08001449void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1450 unsigned writeable) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001451 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertecce5032015-05-18 16:46:31 -07001452
Josh Gao0d6aa992016-11-22 14:32:34 -08001453 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cui3cf1b362017-03-10 16:01:01 -08001454 init_usb_transport(t, usb);
Josh Gao0d6aa992016-11-22 14:32:34 -08001455 if (serial) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001456 t->serial = serial;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001457 }
Dan Albertecce5032015-05-18 16:46:31 -07001458
1459 if (devpath) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001460 t->devpath = devpath;
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001461 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001462
Josh Gaoe7daf572016-09-21 12:37:10 -07001463 {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001464 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaoe7daf572016-09-21 12:37:10 -07001465 pending_list.push_front(t);
1466 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001467
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001468 register_transport(t);
1469}
1470
Josh Gao3a34bc52018-10-11 16:33:05 -07001471#if ADB_HOST
Dan Albert9a50f4c2015-05-18 16:43:57 -07001472// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao0d6aa992016-11-22 14:32:34 -08001473void unregister_usb_transport(usb_handle* usb) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001474 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao395b86a2018-01-28 20:32:46 -08001475 transport_list.remove_if([usb](atransport* t) {
Josh Gao68f2c382018-12-11 13:11:52 -08001476 return t->GetUsbHandle() == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gao395b86a2018-01-28 20:32:46 -08001477 });
Mike Lockwoode45583f2009-08-08 12:37:44 -04001478}
Josh Gao3a34bc52018-10-11 16:33:05 -07001479#endif
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001480
Josh Gao67b683a2017-05-16 15:02:45 -07001481bool check_header(apacket* p, atransport* t) {
Josh Gao0d6aa992016-11-22 14:32:34 -08001482 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cui3cf1b362017-03-10 16:01:01 -08001483 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1484 << ", magic = " << p->msg.magic;
Josh Gao67b683a2017-05-16 15:02:45 -07001485 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001486 }
1487
Josh Gao0d6aa992016-11-22 14:32:34 -08001488 if (p->msg.data_length > t->get_max_payload()) {
1489 VLOG(RWX) << "check_header(): " << p->msg.data_length
1490 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao67b683a2017-05-16 15:02:45 -07001491 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001492 }
1493
Josh Gao67b683a2017-05-16 15:02:45 -07001494 return true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001495}
1496
Josh Gaoeac20582016-10-05 19:02:29 -07001497#if ADB_HOST
Joshua Duong64fab752020-01-21 13:19:42 -08001498std::shared_ptr<RSA> atransport::Key() {
1499 if (keys_.empty()) {
1500 return nullptr;
1501 }
1502
1503 std::shared_ptr<RSA> result = keys_[0];
1504 return result;
1505}
1506
Josh Gao22cb70b2016-08-18 22:00:12 -07001507std::shared_ptr<RSA> atransport::NextKey() {
Josh Gaoeb656522018-12-04 01:07:50 -08001508 if (keys_.empty()) {
1509 LOG(INFO) << "fetching keys for transport " << this->serial_name();
1510 keys_ = adb_auth_get_private_keys();
1511
1512 // We should have gotten at least one key: the one that's automatically generated.
1513 CHECK(!keys_.empty());
Joshua Duong64fab752020-01-21 13:19:42 -08001514 } else {
1515 keys_.pop_front();
Josh Gaoeb656522018-12-04 01:07:50 -08001516 }
Elliott Hughes801066a2016-06-29 17:42:01 -07001517
Josh Gao22cb70b2016-08-18 22:00:12 -07001518 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes801066a2016-06-29 17:42:01 -07001519 return result;
1520}
Josh Gaoeb656522018-12-04 01:07:50 -08001521
1522void atransport::ResetKeys() {
1523 keys_.clear();
1524}
Josh Gaoeac20582016-10-05 19:02:29 -07001525#endif