blob: 0dfad0e1e7b4b9c61ac449ae79010bdac74c3202 [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>
Dan Albertecce5032015-05-18 16:46:31 -070032#include <list>
Pirama Arumuga Nainar5231aff2018-08-08 10:33:24 -070033#include <memory>
Josh Gaoe7daf572016-09-21 12:37:10 -070034#include <mutex>
Josh Gaod2ea0652018-08-10 14:28:24 -070035#include <set>
Josh Gao0f3312a2017-04-12 17:00:49 -070036#include <thread>
Dan Albertecce5032015-05-18 16:46:31 -070037
Joshua Duong64fab752020-01-21 13:19:42 -080038#include <adb/crypto/rsa_2048_key.h>
39#include <adb/crypto/x509_generator.h>
40#include <adb/tls/tls_connection.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080041#include <android-base/logging.h>
Yurii Zubrytskyi816c2d22020-03-26 18:19:28 -070042#include <android-base/no_destructor.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>
Josh Gao361148b2018-01-02 12:01:43 -080047#include <diagnose_usb.h>
48
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080049#include "adb.h"
Elliott Hughes801066a2016-06-29 17:42:01 -070050#include "adb_auth.h"
Josh Gao395b86a2018-01-28 20:32:46 -080051#include "adb_io.h"
Josh Gao9e09a972016-11-29 09:40:29 -080052#include "adb_trace.h"
Elliott Hughes88b4c852015-04-30 17:32:03 -070053#include "adb_utils.h"
Josh Gaob51193a2019-06-28 13:50:37 -070054#include "fdevent/fdevent.h"
Josh Gaob0182892018-07-31 14:12:59 -070055#include "sysdeps/chrono.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080056
Josh Gao8e7c9722021-06-17 04:19:45 -070057#if ADB_HOST
58#include "client/usb.h"
59#endif
60
Joshua Duong64fab752020-01-21 13:19:42 -080061using namespace adb::crypto;
62using namespace adb::tls;
Josh Gao8aa57d22019-02-12 13:59:03 -080063using android::base::ScopedLockAssertion;
Joshua Duong64fab752020-01-21 13:19:42 -080064using TlsError = TlsConnection::TlsError;
Josh Gao8aa57d22019-02-12 13:59:03 -080065
Luis Hector Chavez0aeda102018-04-20 10:31:29 -070066static void remove_transport(atransport* transport);
Josh Gao14ed9f92019-12-09 13:45:31 -080067static void transport_destroy(atransport* transport);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080068
Josh Gaob39e4152017-08-16 16:57:01 -070069// TODO: unordered_map<TransportId, atransport*>
Josh Gaoe3a87d02015-11-11 17:56:12 -080070static auto& transport_list = *new std::list<atransport*>();
71static auto& pending_list = *new std::list<atransport*>();
Benoit Goby3f9f9ce2013-03-29 18:22:36 -070072
Josh Gaoaaa82f72017-08-17 13:50:51 -070073static auto& transport_lock = *new std::recursive_mutex();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080074
Todd Kennedyaff9c672015-11-10 00:03:25 +000075const char* const kFeatureShell2 = "shell_v2";
76const char* const kFeatureCmd = "cmd";
Josh Gaoa2cf3752016-12-05 17:11:34 -080077const char* const kFeatureStat2 = "stat_v2";
Josh Gao7b083072019-08-07 14:23:17 -070078const char* const kFeatureLs2 = "ls_v2";
Josh Gao210b63f2017-02-22 17:07:01 -080079const char* const kFeatureLibusb = "libusb";
Dan Albert27983bc2017-05-23 14:30:00 -070080const char* const kFeaturePushSync = "push_sync";
Dario Frenidcb4c362018-10-04 16:26:40 +010081const char* const kFeatureApex = "apex";
Josh Gao281aab72018-10-22 13:00:05 -070082const char* const kFeatureFixedPushMkdir = "fixed_push_mkdir";
Alex Buynytskyye1fa8142019-01-17 13:13:56 -080083const char* const kFeatureAbb = "abb";
Josh Gao9eeb9f72019-02-20 13:01:40 -080084const char* const kFeatureFixedPushSymlinkTimestamp = "fixed_push_symlink_timestamp";
Alex Buynytskyy4f3fa052019-02-21 14:22:51 -080085const char* const kFeatureAbbExec = "abb_exec";
Josh Gaof764d572019-07-11 14:15:32 -070086const char* const kFeatureRemountShell = "remount_shell";
Shukang Zhou420ad552020-02-13 17:01:39 -080087const char* const kFeatureTrackApp = "track_app";
Josh Gao2f0f9eb2020-03-04 19:34:08 -080088const char* const kFeatureSendRecv2 = "sendrecv_v2";
89const char* const kFeatureSendRecv2Brotli = "sendrecv_v2_brotli";
Josh Gaofb386cc2020-03-26 22:02:03 -070090const char* const kFeatureSendRecv2LZ4 = "sendrecv_v2_lz4";
Josh Gaobdebc9b2020-05-27 17:52:52 -070091const char* const kFeatureSendRecv2Zstd = "sendrecv_v2_zstd";
Josh Gao8a410a02020-03-30 23:25:16 -070092const char* const kFeatureSendRecv2DryRunSend = "sendrecv_v2_dry_run_send";
Joshua Duongf4ba8d72021-01-13 12:18:15 -080093// TODO(joshuaduong): Bump to v2 when openscreen discovery is enabled by default
94const char* const kFeatureOpenscreenMdns = "openscreen_mdns";
Todd Kennedyaff9c672015-11-10 00:03:25 +000095
Luis Hector Chavezda74b902018-04-17 14:25:04 -070096namespace {
97
Josh Gao5c47e9f2018-07-31 18:28:32 -070098#if ADB_HOST
Vince Harron5703eb32021-11-12 12:40:58 -080099
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700100// Tracks and handles atransport*s that are attempting reconnection.
101class ReconnectHandler {
102 public:
103 ReconnectHandler() = default;
104 ~ReconnectHandler() = default;
105
106 // Starts the ReconnectHandler thread.
107 void Start();
108
109 // Requests the ReconnectHandler thread to stop.
110 void Stop();
111
112 // Adds the atransport* to the queue of reconnect attempts.
113 void TrackTransport(atransport* transport);
114
Josh Gao13cb8c02018-08-10 14:44:54 -0700115 // Wake up the ReconnectHandler thread to have it check for kicked transports.
116 void CheckForKicked();
117
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700118 private:
119 // The main thread loop.
120 void Run();
121
122 // Tracks a reconnection attempt.
123 struct ReconnectAttempt {
124 atransport* transport;
Josh Gaoc4deb392018-07-30 18:51:55 -0700125 std::chrono::steady_clock::time_point reconnect_time;
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700126 size_t attempts_left;
Josh Gaob0182892018-07-31 14:12:59 -0700127
128 bool operator<(const ReconnectAttempt& rhs) const {
Josh Gaod2ea0652018-08-10 14:28:24 -0700129 if (reconnect_time == rhs.reconnect_time) {
130 return reinterpret_cast<uintptr_t>(transport) <
131 reinterpret_cast<uintptr_t>(rhs.transport);
132 }
133 return reconnect_time < rhs.reconnect_time;
Josh Gaob0182892018-07-31 14:12:59 -0700134 }
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700135 };
136
137 // Only retry for up to one minute.
Josh Gao04ef6962020-10-15 18:32:55 -0700138 static constexpr const std::chrono::seconds kDefaultTimeout = 3s;
139 static constexpr const size_t kMaxAttempts = 20;
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700140
141 // Protects all members.
142 std::mutex reconnect_mutex_;
143 bool running_ GUARDED_BY(reconnect_mutex_) = true;
144 std::thread handler_thread_;
145 std::condition_variable reconnect_cv_;
Josh Gaod2ea0652018-08-10 14:28:24 -0700146 std::set<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700147
148 DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
149};
150
151void ReconnectHandler::Start() {
152 check_main_thread();
153 handler_thread_ = std::thread(&ReconnectHandler::Run, this);
154}
155
156void ReconnectHandler::Stop() {
157 check_main_thread();
158 {
159 std::lock_guard<std::mutex> lock(reconnect_mutex_);
160 running_ = false;
161 }
162 reconnect_cv_.notify_one();
163 handler_thread_.join();
164
165 // Drain the queue to free all resources.
166 std::lock_guard<std::mutex> lock(reconnect_mutex_);
167 while (!reconnect_queue_.empty()) {
Josh Gaod2ea0652018-08-10 14:28:24 -0700168 ReconnectAttempt attempt = *reconnect_queue_.begin();
169 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700170 remove_transport(attempt.transport);
171 }
172}
173
174void ReconnectHandler::TrackTransport(atransport* transport) {
175 check_main_thread();
176 {
177 std::lock_guard<std::mutex> lock(reconnect_mutex_);
178 if (!running_) return;
Josh Gaob0182892018-07-31 14:12:59 -0700179 // Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
180 auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
181 reconnect_queue_.emplace(
182 ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700183 }
184 reconnect_cv_.notify_one();
185}
186
Josh Gao13cb8c02018-08-10 14:44:54 -0700187void ReconnectHandler::CheckForKicked() {
188 reconnect_cv_.notify_one();
189}
190
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700191void ReconnectHandler::Run() {
192 while (true) {
193 ReconnectAttempt attempt;
194 {
195 std::unique_lock<std::mutex> lock(reconnect_mutex_);
Josh Gao8aa57d22019-02-12 13:59:03 -0800196 ScopedLockAssertion assume_lock(reconnect_mutex_);
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700197
Josh Gaoc4deb392018-07-30 18:51:55 -0700198 if (!reconnect_queue_.empty()) {
199 // FIXME: libstdc++ (used on Windows) implements condition_variable with
200 // system_clock as its clock, so we're probably hosed if the clock changes,
201 // even if we use steady_clock throughout. This problem goes away once we
202 // switch to libc++.
Josh Gaod2ea0652018-08-10 14:28:24 -0700203 reconnect_cv_.wait_until(lock, reconnect_queue_.begin()->reconnect_time);
Josh Gaoc4deb392018-07-30 18:51:55 -0700204 } else {
205 reconnect_cv_.wait(lock);
206 }
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700207
208 if (!running_) return;
Josh Gao13cb8c02018-08-10 14:44:54 -0700209
210 // Scan the whole list for kicked transports, so that we immediately handle an explicit
211 // disconnect request.
Josh Gao13cb8c02018-08-10 14:44:54 -0700212 for (auto it = reconnect_queue_.begin(); it != reconnect_queue_.end();) {
213 if (it->transport->kicked()) {
214 D("transport %s was kicked. giving up on it.", it->transport->serial.c_str());
215 remove_transport(it->transport);
216 it = reconnect_queue_.erase(it);
217 } else {
218 ++it;
219 }
Josh Gao13cb8c02018-08-10 14:44:54 -0700220 }
221
Josh Gaoc4deb392018-07-30 18:51:55 -0700222 if (reconnect_queue_.empty()) continue;
223
Josh Gao13cb8c02018-08-10 14:44:54 -0700224 // Go back to sleep if we either woke up spuriously, or we were woken up to remove
225 // a kicked transport, and the first transport isn't ready for reconnection yet.
Josh Gaoc4deb392018-07-30 18:51:55 -0700226 auto now = std::chrono::steady_clock::now();
Josh Gaod2ea0652018-08-10 14:28:24 -0700227 if (reconnect_queue_.begin()->reconnect_time > now) {
Josh Gaoc4deb392018-07-30 18:51:55 -0700228 continue;
229 }
230
Josh Gaod2ea0652018-08-10 14:28:24 -0700231 attempt = *reconnect_queue_.begin();
232 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700233 }
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700234 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700235
Josh Gaod24580d2018-08-30 11:37:00 -0700236 switch (attempt.transport->Reconnect()) {
237 case ReconnectResult::Retry: {
238 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
239 if (attempt.attempts_left == 0) {
240 D("transport %s exceeded the number of retry attempts. giving up on it.",
241 attempt.transport->serial.c_str());
242 remove_transport(attempt.transport);
243 continue;
244 }
245
246 std::lock_guard<std::mutex> lock(reconnect_mutex_);
247 reconnect_queue_.emplace(ReconnectAttempt{
248 attempt.transport,
249 std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
250 attempt.attempts_left - 1});
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700251 continue;
252 }
253
Josh Gaod24580d2018-08-30 11:37:00 -0700254 case ReconnectResult::Success:
255 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
256 register_transport(attempt.transport);
257 continue;
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700258
Josh Gaod24580d2018-08-30 11:37:00 -0700259 case ReconnectResult::Abort:
260 D("cancelling reconnection attempt to %s.", attempt.transport->serial.c_str());
261 remove_transport(attempt.transport);
262 continue;
263 }
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700264 }
265}
266
267static auto& reconnect_handler = *new ReconnectHandler();
268
Josh Gao5c47e9f2018-07-31 18:28:32 -0700269#endif
270
Luis Hector Chavezda74b902018-04-17 14:25:04 -0700271} // namespace
272
Josh Gaob39e4152017-08-16 16:57:01 -0700273TransportId NextTransportId() {
274 static std::atomic<TransportId> next(1);
275 return next++;
276}
277
Josh Gao3a2172b2019-03-28 15:47:44 -0700278void Connection::Reset() {
279 LOG(INFO) << "Connection::Reset(): stopping";
280 Stop();
281}
282
Josh Gao7852ca42021-06-17 04:17:25 -0700283std::string Connection::Serial() const {
284 return transport_ ? transport_->serial_name() : "<unknown>";
285}
286
Josh Gao715fe602018-02-16 13:24:58 -0800287BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
288 : underlying_(std::move(connection)) {}
289
290BlockingConnectionAdapter::~BlockingConnectionAdapter() {
Josh Gao7852ca42021-06-17 04:17:25 -0700291 LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): destructing";
Josh Gao715fe602018-02-16 13:24:58 -0800292 Stop();
293}
294
295void BlockingConnectionAdapter::Start() {
Josh Gao13781e82018-04-03 12:55:18 -0700296 std::lock_guard<std::mutex> lock(mutex_);
297 if (started_) {
Josh Gao7852ca42021-06-17 04:17:25 -0700298 LOG(FATAL) << "BlockingConnectionAdapter(" << Serial() << "): started multiple times";
Josh Gao13781e82018-04-03 12:55:18 -0700299 }
300
Joshua Duong64fab752020-01-21 13:19:42 -0800301 StartReadThread();
Josh Gao715fe602018-02-16 13:24:58 -0800302
303 write_thread_ = std::thread([this]() {
Josh Gao7852ca42021-06-17 04:17:25 -0700304 LOG(INFO) << Serial() << ": write thread spawning";
Josh Gao715fe602018-02-16 13:24:58 -0800305 while (true) {
306 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao8aa57d22019-02-12 13:59:03 -0800307 ScopedLockAssertion assume_locked(mutex_);
Josh Gao13781e82018-04-03 12:55:18 -0700308 cv_.wait(lock, [this]() REQUIRES(mutex_) {
309 return this->stopped_ || !this->write_queue_.empty();
310 });
311
Josh Gao715fe602018-02-16 13:24:58 -0800312 if (this->stopped_) {
313 return;
314 }
315
316 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
317 this->write_queue_.pop_front();
318 lock.unlock();
319
320 if (!this->underlying_->Write(packet.get())) {
321 break;
322 }
323 }
Josh Gao7852ca42021-06-17 04:17:25 -0700324 std::call_once(this->error_flag_, [this]() { transport_->HandleError("write failed"); });
Josh Gao715fe602018-02-16 13:24:58 -0800325 });
Josh Gao13781e82018-04-03 12:55:18 -0700326
327 started_ = true;
Josh Gao715fe602018-02-16 13:24:58 -0800328}
329
Joshua Duong64fab752020-01-21 13:19:42 -0800330void BlockingConnectionAdapter::StartReadThread() {
331 read_thread_ = std::thread([this]() {
Josh Gao7852ca42021-06-17 04:17:25 -0700332 LOG(INFO) << Serial() << ": read thread spawning";
Joshua Duong64fab752020-01-21 13:19:42 -0800333 while (true) {
334 auto packet = std::make_unique<apacket>();
335 if (!underlying_->Read(packet.get())) {
Josh Gao7852ca42021-06-17 04:17:25 -0700336 PLOG(INFO) << Serial() << ": read failed";
Joshua Duong64fab752020-01-21 13:19:42 -0800337 break;
338 }
339
340 bool got_stls_cmd = false;
341 if (packet->msg.command == A_STLS) {
342 got_stls_cmd = true;
343 }
344
Josh Gao7852ca42021-06-17 04:17:25 -0700345 transport_->HandleRead(std::move(packet));
Joshua Duong64fab752020-01-21 13:19:42 -0800346
347 // If we received the STLS packet, we are about to perform the TLS
348 // handshake. So this read thread must stop and resume after the
349 // handshake completes otherwise this will interfere in the process.
350 if (got_stls_cmd) {
Josh Gao7852ca42021-06-17 04:17:25 -0700351 LOG(INFO) << Serial() << ": Received STLS packet. Stopping read thread.";
Joshua Duong64fab752020-01-21 13:19:42 -0800352 return;
353 }
354 }
Josh Gao7852ca42021-06-17 04:17:25 -0700355 std::call_once(this->error_flag_, [this]() { transport_->HandleError("read failed"); });
Joshua Duong64fab752020-01-21 13:19:42 -0800356 });
357}
358
359bool BlockingConnectionAdapter::DoTlsHandshake(RSA* key, std::string* auth_key) {
360 std::lock_guard<std::mutex> lock(mutex_);
361 if (read_thread_.joinable()) {
362 read_thread_.join();
363 }
364 bool success = this->underlying_->DoTlsHandshake(key, auth_key);
365 StartReadThread();
366 return success;
367}
368
Josh Gao3a2172b2019-03-28 15:47:44 -0700369void BlockingConnectionAdapter::Reset() {
370 {
371 std::lock_guard<std::mutex> lock(mutex_);
372 if (!started_) {
Josh Gao7852ca42021-06-17 04:17:25 -0700373 LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): not started";
Josh Gao3a2172b2019-03-28 15:47:44 -0700374 return;
375 }
376
377 if (stopped_) {
Josh Gao7852ca42021-06-17 04:17:25 -0700378 LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): already stopped";
Josh Gao3a2172b2019-03-28 15:47:44 -0700379 return;
380 }
381 }
382
Josh Gao7852ca42021-06-17 04:17:25 -0700383 LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): resetting";
Josh Gao3a2172b2019-03-28 15:47:44 -0700384 this->underlying_->Reset();
385 Stop();
386}
387
Josh Gao715fe602018-02-16 13:24:58 -0800388void BlockingConnectionAdapter::Stop() {
Josh Gao13781e82018-04-03 12:55:18 -0700389 {
390 std::lock_guard<std::mutex> lock(mutex_);
391 if (!started_) {
Josh Gao7852ca42021-06-17 04:17:25 -0700392 LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): not started";
Josh Gao13781e82018-04-03 12:55:18 -0700393 return;
394 }
Josh Gao715fe602018-02-16 13:24:58 -0800395
Josh Gao13781e82018-04-03 12:55:18 -0700396 if (stopped_) {
Josh Gao7852ca42021-06-17 04:17:25 -0700397 LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): already stopped";
Josh Gao13781e82018-04-03 12:55:18 -0700398 return;
399 }
400
401 stopped_ = true;
402 }
Josh Gao715fe602018-02-16 13:24:58 -0800403
Josh Gao7852ca42021-06-17 04:17:25 -0700404 LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): stopping";
Josh Gao715fe602018-02-16 13:24:58 -0800405
406 this->underlying_->Close();
Josh Gao715fe602018-02-16 13:24:58 -0800407 this->cv_.notify_one();
Josh Gao13781e82018-04-03 12:55:18 -0700408
409 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
410 std::thread read_thread;
411 std::thread write_thread;
412
413 {
414 std::lock_guard<std::mutex> lock(mutex_);
415 read_thread = std::move(read_thread_);
416 write_thread = std::move(write_thread_);
417 }
418
419 read_thread.join();
420 write_thread.join();
Josh Gao715fe602018-02-16 13:24:58 -0800421
Josh Gao7852ca42021-06-17 04:17:25 -0700422 LOG(INFO) << "BlockingConnectionAdapter(" << Serial() << "): stopped";
423 std::call_once(this->error_flag_, [this]() { transport_->HandleError("requested stop"); });
Josh Gao715fe602018-02-16 13:24:58 -0800424}
425
426bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
427 {
Josh Gao13781e82018-04-03 12:55:18 -0700428 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao715fe602018-02-16 13:24:58 -0800429 write_queue_.emplace_back(std::move(packet));
430 }
431
432 cv_.notify_one();
433 return true;
434}
435
Joshua Duong64fab752020-01-21 13:19:42 -0800436FdConnection::FdConnection(unique_fd fd) : fd_(std::move(fd)) {}
437
438FdConnection::~FdConnection() {}
439
440bool FdConnection::DispatchRead(void* buf, size_t len) {
441 if (tls_ != nullptr) {
442 // The TlsConnection doesn't allow 0 byte reads
443 if (len == 0) {
444 return true;
445 }
446 return tls_->ReadFully(buf, len);
447 }
448
449 return ReadFdExactly(fd_.get(), buf, len);
450}
451
452bool FdConnection::DispatchWrite(void* buf, size_t len) {
453 if (tls_ != nullptr) {
454 // The TlsConnection doesn't allow 0 byte writes
455 if (len == 0) {
456 return true;
457 }
458 return tls_->WriteFully(std::string_view(reinterpret_cast<const char*>(buf), len));
459 }
460
461 return WriteFdExactly(fd_.get(), buf, len);
462}
463
Josh Gao395b86a2018-01-28 20:32:46 -0800464bool FdConnection::Read(apacket* packet) {
Joshua Duong64fab752020-01-21 13:19:42 -0800465 if (!DispatchRead(&packet->msg, sizeof(amessage))) {
Josh Gao395b86a2018-01-28 20:32:46 -0800466 D("remote local: read terminated (message)");
467 return false;
468 }
469
Josh Gao839b9322018-02-05 18:49:10 -0800470 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gaob14756a2018-02-02 14:38:04 -0800471 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
472 return false;
473 }
474
Josh Gao839b9322018-02-05 18:49:10 -0800475 packet->payload.resize(packet->msg.data_length);
476
Joshua Duong64fab752020-01-21 13:19:42 -0800477 if (!DispatchRead(&packet->payload[0], packet->payload.size())) {
Josh Gao395b86a2018-01-28 20:32:46 -0800478 D("remote local: terminated (data)");
479 return false;
480 }
481
482 return true;
483}
484
485bool FdConnection::Write(apacket* packet) {
Joshua Duong64fab752020-01-21 13:19:42 -0800486 if (!DispatchWrite(&packet->msg, sizeof(packet->msg))) {
Josh Gao395b86a2018-01-28 20:32:46 -0800487 D("remote local: write terminated");
488 return false;
489 }
490
Josh Gao839b9322018-02-05 18:49:10 -0800491 if (packet->msg.data_length) {
Joshua Duong64fab752020-01-21 13:19:42 -0800492 if (!DispatchWrite(&packet->payload[0], packet->msg.data_length)) {
Josh Gao839b9322018-02-05 18:49:10 -0800493 D("remote local: write terminated");
494 return false;
495 }
496 }
497
Josh Gao395b86a2018-01-28 20:32:46 -0800498 return true;
499}
500
Joshua Duong64fab752020-01-21 13:19:42 -0800501bool FdConnection::DoTlsHandshake(RSA* key, std::string* auth_key) {
502 bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
503 if (!EVP_PKEY_set1_RSA(evp_pkey.get(), key)) {
504 LOG(ERROR) << "EVP_PKEY_set1_RSA failed";
505 return false;
506 }
507 auto x509 = GenerateX509Certificate(evp_pkey.get());
508 auto x509_str = X509ToPEMString(x509.get());
509 auto evp_str = Key::ToPEMString(evp_pkey.get());
Joshua Duongdd19e862020-03-24 09:50:59 -0700510
Yurii Zubrytskyi3c0574f2020-03-26 18:16:36 -0700511 int osh = cast_handle_to_int(adb_get_os_handle(fd_));
Joshua Duong64fab752020-01-21 13:19:42 -0800512#if ADB_HOST
Joshua Duong77b8ff32020-04-16 15:58:19 -0700513 tls_ = TlsConnection::Create(TlsConnection::Role::Client, x509_str, evp_str, osh);
Joshua Duong64fab752020-01-21 13:19:42 -0800514#else
Joshua Duong77b8ff32020-04-16 15:58:19 -0700515 tls_ = TlsConnection::Create(TlsConnection::Role::Server, x509_str, evp_str, osh);
Joshua Duong64fab752020-01-21 13:19:42 -0800516#endif
Joshua Duong64fab752020-01-21 13:19:42 -0800517 CHECK(tls_);
518#if ADB_HOST
519 // TLS 1.3 gives the client no message if the server rejected the
520 // certificate. This will enable a check in the tls connection to check
521 // whether the client certificate got rejected. Note that this assumes
522 // that, on handshake success, the server speaks first.
523 tls_->EnableClientPostHandshakeCheck(true);
524 // Add callback to set the certificate when server issues the
525 // CertificateRequest.
526 tls_->SetCertificateCallback(adb_tls_set_certificate);
527 // Allow any server certificate
528 tls_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
529#else
530 // Add callback to check certificate against a list of known public keys
531 tls_->SetCertVerifyCallback(
532 [auth_key](X509_STORE_CTX* ctx) { return adbd_tls_verify_cert(ctx, auth_key); });
533 // Add the list of allowed client CA issuers
534 auto ca_list = adbd_tls_client_ca_list();
535 tls_->SetClientCAList(ca_list.get());
536#endif
537
538 auto err = tls_->DoHandshake();
539 if (err == TlsError::Success) {
540 return true;
541 }
542
543 tls_.reset();
544 return false;
545}
546
Josh Gao395b86a2018-01-28 20:32:46 -0800547void FdConnection::Close() {
548 adb_shutdown(fd_.get());
549 fd_.reset();
550}
551
Josh Gao67ac3792016-10-06 13:31:44 -0700552void send_packet(apacket* p, atransport* t) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800553 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayee7b44d2017-12-07 11:40:00 -0800554 // compute a checksum for connection/auth packets for compatibility reasons
555 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
556 p->msg.data_check = 0;
557 } else {
558 p->msg.data_check = calculate_apacket_checksum(p);
559 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800560
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700561 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800562
Yi Kong86e67182018-07-13 18:15:16 -0700563 if (t == nullptr) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700564 LOG(FATAL) << "Transport is null";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800565 }
566
Josh Gao715fe602018-02-16 13:24:58 -0800567 if (t->Write(p) != 0) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700568 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao715fe602018-02-16 13:24:58 -0800569 t->Kick();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800570 }
571}
572
Josh Gao3a2172b2019-03-28 15:47:44 -0700573void kick_transport(atransport* t, bool reset) {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700574 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuid78ed222016-04-05 13:50:44 -0700575 // As kick_transport() can be called from threads without guarantee that t is valid,
576 // check if the transport is in transport_list first.
Josh Gaob39e4152017-08-16 16:57:01 -0700577 //
578 // TODO(jmgao): WTF? Is this actually true?
Yabin Cuid78ed222016-04-05 13:50:44 -0700579 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Josh Gao3a2172b2019-03-28 15:47:44 -0700580 if (reset) {
581 t->Reset();
582 } else {
583 t->Kick();
584 }
Yabin Cuid78ed222016-04-05 13:50:44 -0700585 }
Josh Gao13cb8c02018-08-10 14:44:54 -0700586
587#if ADB_HOST
588 reconnect_handler.CheckForKicked();
589#endif
Yabin Cui4d64fd82015-08-27 12:03:11 -0700590}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800591
592static int transport_registration_send = -1;
593static int transport_registration_recv = -1;
Josh Gao9528df22018-05-14 11:14:33 -0700594static fdevent* transport_registration_fde;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800595
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800596#if ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800597
598/* this adds support required by the 'track-devices' service.
599 * this is used to send the content of "list_transport" to any
600 * number of client connections that want it through a single
601 * live TCP connection
602 */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800603struct device_tracker {
Josh Gao0d6aa992016-11-22 14:32:34 -0800604 asocket socket;
Josh Gao5cb76ce2018-02-12 17:24:00 -0800605 bool update_needed = false;
606 bool long_output = false;
607 device_tracker* next = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800608};
609
610/* linked list of all device trackers */
Josh Gao0d6aa992016-11-22 14:32:34 -0800611static device_tracker* device_tracker_list;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800612
Josh Gao0d6aa992016-11-22 14:32:34 -0800613static void device_tracker_remove(device_tracker* tracker) {
614 device_tracker** pnode = &device_tracker_list;
615 device_tracker* node = *pnode;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800616
Josh Gaoaaa82f72017-08-17 13:50:51 -0700617 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800618 while (node) {
619 if (node == tracker) {
620 *pnode = node->next;
621 break;
622 }
623 pnode = &node->next;
Josh Gao0d6aa992016-11-22 14:32:34 -0800624 node = *pnode;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800625 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800626}
627
Josh Gao0d6aa992016-11-22 14:32:34 -0800628static void device_tracker_close(asocket* socket) {
629 device_tracker* tracker = (device_tracker*)socket;
630 asocket* peer = socket->peer;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800631
Josh Gao0d6aa992016-11-22 14:32:34 -0800632 D("device tracker %p removed", tracker);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800633 if (peer) {
Yi Kong86e67182018-07-13 18:15:16 -0700634 peer->peer = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800635 peer->close(peer);
636 }
637 device_tracker_remove(tracker);
Josh Gao5cb76ce2018-02-12 17:24:00 -0800638 delete tracker;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800639}
640
Josh Gaocd2a5292018-03-07 16:52:28 -0800641static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800642 /* you can't read from a device tracker, close immediately */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800643 device_tracker_close(socket);
644 return -1;
645}
646
Elliott Hughes88b4c852015-04-30 17:32:03 -0700647static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughes88b4c852015-04-30 17:32:03 -0700648 asocket* peer = tracker->socket.peer;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800649
Josh Gaocd2a5292018-03-07 16:52:28 -0800650 apacket::payload_type data;
Josh Gaoa7d9d712018-02-01 13:17:50 -0800651 data.resize(4 + string.size());
652 char buf[5];
653 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
654 memcpy(&data[0], buf, 4);
655 memcpy(&data[4], string.data(), string.size());
656 return peer->enqueue(peer, std::move(data));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800657}
658
Elliott Hughes88b4c852015-04-30 17:32:03 -0700659static void device_tracker_ready(asocket* socket) {
660 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800661
Elliott Hughes88b4c852015-04-30 17:32:03 -0700662 // We want to send the device list when the tracker connects
663 // for the first time, even if no update occurred.
Josh Gao32124632017-08-14 18:57:54 -0700664 if (tracker->update_needed) {
665 tracker->update_needed = false;
Elliott Hughes3d792f42019-07-31 14:13:57 -0700666 device_tracker_send(tracker, list_transports(tracker->long_output));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800667 }
668}
669
Josh Gao32124632017-08-14 18:57:54 -0700670asocket* create_device_tracker(bool long_output) {
Josh Gao5cb76ce2018-02-12 17:24:00 -0800671 device_tracker* tracker = new device_tracker();
Elliott Hughese64126b2018-10-19 13:59:44 -0700672 if (tracker == nullptr) LOG(FATAL) << "cannot allocate device tracker";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800673
Josh Gao0d6aa992016-11-22 14:32:34 -0800674 D("device tracker %p created", tracker);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800675
676 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao0d6aa992016-11-22 14:32:34 -0800677 tracker->socket.ready = device_tracker_ready;
678 tracker->socket.close = device_tracker_close;
Josh Gao32124632017-08-14 18:57:54 -0700679 tracker->update_needed = true;
680 tracker->long_output = long_output;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800681
Josh Gao0d6aa992016-11-22 14:32:34 -0800682 tracker->next = device_tracker_list;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800683 device_tracker_list = tracker;
684
685 return &tracker->socket;
686}
687
Josh Gao1e3bf732017-05-03 22:37:10 -0700688// Check if all of the USB transports are connected.
689bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700690 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao1e3bf732017-05-03 22:37:10 -0700691 for (const auto& t : transport_list) {
692 if (!fn(t)) {
693 return false;
694 }
695 }
696 for (const auto& t : pending_list) {
697 if (!fn(t)) {
698 return false;
699 }
700 }
701 return true;
702}
703
Elliott Hughes88b4c852015-04-30 17:32:03 -0700704// Call this function each time the transport list has changed.
705void update_transports() {
Josh Gao1e3bf732017-05-03 22:37:10 -0700706 update_transport_status();
707
708 // Notify `adb track-devices` clients.
Elliott Hughes88b4c852015-04-30 17:32:03 -0700709 device_tracker* tracker = device_tracker_list;
710 while (tracker != nullptr) {
711 device_tracker* next = tracker->next;
712 // This may destroy the tracker if the connection is closed.
Elliott Hughes3d792f42019-07-31 14:13:57 -0700713 device_tracker_send(tracker, list_transports(tracker->long_output));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800714 tracker = next;
715 }
716}
Elliott Hughes88b4c852015-04-30 17:32:03 -0700717
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800718#else
Elliott Hughes88b4c852015-04-30 17:32:03 -0700719
720void update_transports() {
721 // Nothing to do on the device side.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800722}
Elliott Hughes88b4c852015-04-30 17:32:03 -0700723
Josh Gao0d6aa992016-11-22 14:32:34 -0800724#endif // ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800725
Josh Gao0d6aa992016-11-22 14:32:34 -0800726struct tmsg {
727 atransport* transport;
728 int action;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800729};
730
Josh Gao0d6aa992016-11-22 14:32:34 -0800731static int transport_read_action(int fd, struct tmsg* m) {
732 char* p = (char*)m;
733 int len = sizeof(*m);
734 int r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800735
Josh Gao0d6aa992016-11-22 14:32:34 -0800736 while (len > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800737 r = adb_read(fd, p, len);
Josh Gao0d6aa992016-11-22 14:32:34 -0800738 if (r > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800739 len -= r;
Josh Gao0d6aa992016-11-22 14:32:34 -0800740 p += r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800741 } else {
Yabin Cui815ad882015-09-02 17:44:28 -0700742 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800743 return -1;
744 }
745 }
746 return 0;
747}
748
Josh Gao0d6aa992016-11-22 14:32:34 -0800749static int transport_write_action(int fd, struct tmsg* m) {
750 char* p = (char*)m;
751 int len = sizeof(*m);
752 int r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800753
Josh Gao0d6aa992016-11-22 14:32:34 -0800754 while (len > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800755 r = adb_write(fd, p, len);
Josh Gao0d6aa992016-11-22 14:32:34 -0800756 if (r > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800757 len -= r;
Josh Gao0d6aa992016-11-22 14:32:34 -0800758 p += r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800759 } else {
Yabin Cui815ad882015-09-02 17:44:28 -0700760 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800761 return -1;
762 }
763 }
764 return 0;
765}
766
Josh Gao8e7c9722021-06-17 04:19:45 -0700767static bool usb_devices_start_detached() {
768#if ADB_HOST
769 static const char* env = getenv("ADB_LIBUSB_START_DETACHED");
770 static bool result = env && strcmp("1", env) == 0;
771 return should_use_libusb() && result;
772#else
773 return false;
774#endif
775}
776
Josh Gao715fe602018-02-16 13:24:58 -0800777static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800778 tmsg m;
Josh Gao0d6aa992016-11-22 14:32:34 -0800779 atransport* t;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800780
Josh Gao0d6aa992016-11-22 14:32:34 -0800781 if (!(ev & FDE_READ)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800782 return;
783 }
784
Josh Gao0d6aa992016-11-22 14:32:34 -0800785 if (transport_read_action(_fd, &m)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700786 PLOG(FATAL) << "cannot read transport registration socket";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800787 }
788
789 t = m.transport;
790
Dan Albertbe8e54b2015-05-18 13:06:53 -0700791 if (m.action == 0) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700792 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800793
Josh Gaoe7daf572016-09-21 12:37:10 -0700794 {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700795 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaoe7daf572016-09-21 12:37:10 -0700796 transport_list.remove(t);
797 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800798
Dan Albertecce5032015-05-18 16:46:31 -0700799 delete t;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800800
801 update_transports();
802 return;
803 }
804
Mike Lockwoode45583f2009-08-08 12:37:44 -0400805 /* don't create transport threads for inaccessible devices */
Yabin Cui3cf1b362017-03-10 16:01:01 -0800806 if (t->GetConnectionState() != kCsNoPerm) {
Josh Gao7852ca42021-06-17 04:17:25 -0700807 t->connection()->SetTransport(t);
Josh Gao8e7c9722021-06-17 04:19:45 -0700808
809 if (t->type == kTransportUsb && usb_devices_start_detached()) {
810 t->SetConnectionState(kCsDetached);
811 } else {
812 t->connection()->Start();
Josh Gao715fe602018-02-16 13:24:58 -0800813#if ADB_HOST
Josh Gao8e7c9722021-06-17 04:19:45 -0700814 send_connect(t);
Josh Gao715fe602018-02-16 13:24:58 -0800815#endif
Josh Gao8e7c9722021-06-17 04:19:45 -0700816 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800817 }
818
Josh Gaoe7daf572016-09-21 12:37:10 -0700819 {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700820 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700821 auto it = std::find(pending_list.begin(), pending_list.end(), t);
822 if (it != pending_list.end()) {
823 pending_list.remove(t);
824 transport_list.push_front(t);
825 }
Josh Gaoe7daf572016-09-21 12:37:10 -0700826 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800827
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800828 update_transports();
829}
830
Josh Gao5c47e9f2018-07-31 18:28:32 -0700831#if ADB_HOST
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700832void init_reconnect_handler(void) {
833 reconnect_handler.Start();
834}
Josh Gao5c47e9f2018-07-31 18:28:32 -0700835#endif
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700836
Josh Gao0d6aa992016-11-22 14:32:34 -0800837void init_transport_registration(void) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800838 int s[2];
839
Josh Gao0d6aa992016-11-22 14:32:34 -0800840 if (adb_socketpair(s)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700841 PLOG(FATAL) << "cannot open transport registration socketpair";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800842 }
Yabin Cui815ad882015-09-02 17:44:28 -0700843 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800844
845 transport_registration_send = s[0];
846 transport_registration_recv = s[1];
847
Josh Gao9528df22018-05-14 11:14:33 -0700848 transport_registration_fde =
Josh Gao7852ca42021-06-17 04:17:25 -0700849 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao9528df22018-05-14 11:14:33 -0700850 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao165460f2017-05-09 13:43:35 -0700851}
852
853void kick_all_transports() {
Josh Gao5c47e9f2018-07-31 18:28:32 -0700854#if ADB_HOST
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700855 reconnect_handler.Stop();
Josh Gao5c47e9f2018-07-31 18:28:32 -0700856#endif
Josh Gao165460f2017-05-09 13:43:35 -0700857 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gaoaaa82f72017-08-17 13:50:51 -0700858 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao165460f2017-05-09 13:43:35 -0700859 for (auto t : transport_list) {
860 t->Kick();
861 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800862}
863
Joshua Duong64fab752020-01-21 13:19:42 -0800864void kick_all_tcp_tls_transports() {
865 std::lock_guard<std::recursive_mutex> lock(transport_lock);
866 for (auto t : transport_list) {
867 if (t->IsTcpDevice() && t->use_tls) {
868 t->Kick();
869 }
870 }
871}
872
873#if !ADB_HOST
874void kick_all_transports_by_auth_key(std::string_view auth_key) {
875 std::lock_guard<std::recursive_mutex> lock(transport_lock);
876 for (auto t : transport_list) {
877 if (auth_key == t->auth_key) {
878 t->Kick();
879 }
880 }
881}
882#endif
883
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800884/* the fdevent select pump is single threaded */
Josh Gao3a34bc52018-10-11 16:33:05 -0700885void register_transport(atransport* transport) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800886 tmsg m;
887 m.transport = transport;
888 m.action = 1;
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700889 D("transport: %s registered", transport->serial.c_str());
Josh Gao0d6aa992016-11-22 14:32:34 -0800890 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700891 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800892 }
893}
894
Josh Gao0d6aa992016-11-22 14:32:34 -0800895static void remove_transport(atransport* transport) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800896 tmsg m;
897 m.transport = transport;
898 m.action = 0;
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700899 D("transport: %s removed", transport->serial.c_str());
Josh Gao0d6aa992016-11-22 14:32:34 -0800900 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700901 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800902 }
903}
904
Josh Gao14ed9f92019-12-09 13:45:31 -0800905static void transport_destroy(atransport* t) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700906 check_main_thread();
Yabin Cui4d64fd82015-08-27 12:03:11 -0700907 CHECK(t != nullptr);
Josh Gaoe7daf572016-09-21 12:37:10 -0700908
Josh Gao4d299742017-09-13 13:40:57 -0700909 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao14ed9f92019-12-09 13:45:31 -0800910 LOG(INFO) << "destroying transport " << t->serial_name();
911 t->connection()->Stop();
Josh Gao5c47e9f2018-07-31 18:28:32 -0700912#if ADB_HOST
Josh Gao14ed9f92019-12-09 13:45:31 -0800913 if (t->IsTcpDevice() && !t->kicked()) {
914 D("transport: %s destroy (attempting reconnection)", t->serial.c_str());
Josh Gaoeb656522018-12-04 01:07:50 -0800915
Josh Gao14ed9f92019-12-09 13:45:31 -0800916 // We need to clear the transport's keys, so that on the next connection, it tries
917 // again from the beginning.
918 t->ResetKeys();
919 reconnect_handler.TrackTransport(t);
920 return;
921 }
Josh Gao5c47e9f2018-07-31 18:28:32 -0700922#endif
923
Josh Gao14ed9f92019-12-09 13:45:31 -0800924 D("transport: %s destroy (kicking and closing)", t->serial.c_str());
925 remove_transport(t);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800926}
927
Josh Gao65d18e22020-04-22 20:57:26 -0700928#if ADB_HOST
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700929static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao0d6aa992016-11-22 14:32:34 -0800930 bool sanitize_qual) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700931 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
932 return qual.empty();
Scott Anderson27042382012-05-30 18:11:27 -0700933
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700934 if (qual.empty()) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700935
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700936 const char* ptr = to_test.c_str();
Scott Anderson27042382012-05-30 18:11:27 -0700937 if (prefix) {
938 while (*prefix) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700939 if (*prefix++ != *ptr++) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700940 }
941 }
942
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700943 for (char ch : qual) {
Josh Gao0d6aa992016-11-22 14:32:34 -0800944 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700945 if (ch != *ptr++) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700946 }
947
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700948 /* Everything matched so far. Return true if *ptr is a NUL. */
949 return !*ptr;
Scott Anderson27042382012-05-30 18:11:27 -0700950}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800951
Vince Harron5703eb32021-11-12 12:40:58 -0800952// Contains either a device serial string or a USB device address like "usb:2-6"
953const char* __transport_server_one_device = nullptr;
954
955void transport_set_one_device(const char* adb_one_device) {
956 __transport_server_one_device = adb_one_device;
957}
958
959const char* transport_get_one_device() {
960 return __transport_server_one_device;
961}
962
963bool transport_server_owns_device(std::string_view serial) {
964 if (!__transport_server_one_device) {
965 // If the server doesn't own one device, server owns all devices.
966 return true;
967 }
968 return serial.compare(__transport_server_one_device) == 0;
969}
970
971bool transport_server_owns_device(std::string_view dev_path, std::string_view serial) {
972 if (!__transport_server_one_device) {
973 // If the server doesn't own one device, server owns all devices.
974 return true;
975 }
976 return serial.compare(__transport_server_one_device) == 0 ||
977 dev_path.compare(__transport_server_one_device) == 0;
978}
979
Josh Gaob39e4152017-08-16 16:57:01 -0700980atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
981 bool* is_ambiguous, std::string* error_out,
982 bool accept_any_state) {
Elliott Hughes67943d12015-10-07 14:55:10 -0700983 atransport* result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800984
Josh Gaob39e4152017-08-16 16:57:01 -0700985 if (transport_id != 0) {
Josh Gao7852ca42021-06-17 04:17:25 -0700986 *error_out = android::base::StringPrintf("no device with transport id '%" PRIu64 "'",
987 transport_id);
Josh Gaob39e4152017-08-16 16:57:01 -0700988 } else if (serial) {
Elliott Hughes67943d12015-10-07 14:55:10 -0700989 *error_out = android::base::StringPrintf("device '%s' not found", serial);
990 } else if (type == kTransportLocal) {
991 *error_out = "no emulators found";
992 } else if (type == kTransportAny) {
993 *error_out = "no devices/emulators found";
994 } else {
995 *error_out = "no devices found";
996 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800997
Josh Gaoaaa82f72017-08-17 13:50:51 -0700998 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes67943d12015-10-07 14:55:10 -0700999 for (const auto& t : transport_list) {
Yabin Cui3cf1b362017-03-10 16:01:01 -08001000 if (t->GetConnectionState() == kCsNoPerm) {
David Pursell6e5c7eb2015-12-02 15:14:31 -08001001 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwoodadc16b32009-08-08 13:53:16 -04001002 continue;
1003 }
Mike Lockwoode45583f2009-08-08 12:37:44 -04001004
Josh Gaob39e4152017-08-16 16:57:01 -07001005 if (transport_id) {
1006 if (t->id == transport_id) {
1007 result = t;
1008 break;
1009 }
1010 } else if (serial) {
David Pursellc929c6f2016-03-01 08:58:26 -08001011 if (t->MatchesTarget(serial)) {
Scott Anderson27042382012-05-30 18:11:27 -07001012 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -07001013 *error_out = "more than one device";
Elliott Hughes67943d12015-10-07 14:55:10 -07001014 if (is_ambiguous) *is_ambiguous = true;
1015 result = nullptr;
Scott Anderson27042382012-05-30 18:11:27 -07001016 break;
1017 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001018 result = t;
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001019 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001020 } else {
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001021 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001022 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -07001023 *error_out = "more than one device";
Elliott Hughes67943d12015-10-07 14:55:10 -07001024 if (is_ambiguous) *is_ambiguous = true;
1025 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001026 break;
1027 }
1028 result = t;
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001029 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001030 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -07001031 *error_out = "more than one emulator";
Elliott Hughes67943d12015-10-07 14:55:10 -07001032 if (is_ambiguous) *is_ambiguous = true;
1033 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001034 break;
1035 }
1036 result = t;
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001037 } else if (type == kTransportAny) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001038 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -07001039 *error_out = "more than one device/emulator";
Elliott Hughes67943d12015-10-07 14:55:10 -07001040 if (is_ambiguous) *is_ambiguous = true;
1041 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001042 break;
1043 }
1044 result = t;
1045 }
1046 }
1047 }
Josh Gaoe7daf572016-09-21 12:37:10 -07001048 lock.unlock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001049
Josh Gao7a7c5cb2018-05-04 16:04:49 -07001050 if (result && !accept_any_state) {
1051 // The caller requires an active transport.
1052 // Make sure that we're actually connected.
1053 ConnectionState state = result->GetConnectionState();
1054 switch (state) {
1055 case kCsConnecting:
1056 *error_out = "device still connecting";
1057 result = nullptr;
1058 break;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001059
Josh Gao7a7c5cb2018-05-04 16:04:49 -07001060 case kCsAuthorizing:
1061 *error_out = "device still authorizing";
1062 result = nullptr;
1063 break;
1064
1065 case kCsUnauthorized: {
1066 *error_out = "device unauthorized.\n";
1067 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
1068 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
1069 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
1070 *error_out += "\n";
1071 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
1072 *error_out += "Otherwise check for a confirmation dialog on your device.";
1073 result = nullptr;
1074 break;
1075 }
1076
1077 case kCsOffline:
1078 *error_out = "device offline";
1079 result = nullptr;
1080 break;
1081
1082 default:
1083 break;
1084 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001085 }
1086
1087 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -07001088 *error_out = "success";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001089 }
1090
1091 return result;
1092}
1093
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001094bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
1095 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao8aa57d22019-02-12 13:59:03 -08001096 ScopedLockAssertion assume_locked(mutex_);
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001097 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
1098 return connection_established_ready_;
1099 }) && connection_established_;
1100}
1101
1102void ConnectionWaitable::SetConnectionEstablished(bool success) {
1103 {
1104 std::lock_guard<std::mutex> lock(mutex_);
1105 if (connection_established_ready_) return;
1106 connection_established_ready_ = true;
1107 connection_established_ = success;
1108 D("connection established with %d", success);
1109 }
1110 cv_.notify_one();
1111}
Josh Gao65d18e22020-04-22 20:57:26 -07001112#endif
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001113
1114atransport::~atransport() {
Josh Gao65d18e22020-04-22 20:57:26 -07001115#if ADB_HOST
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001116 // If the connection callback had not been run before, run it now.
1117 SetConnectionEstablished(false);
Josh Gao65d18e22020-04-22 20:57:26 -07001118#endif
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001119}
1120
Yabin Cui3cf1b362017-03-10 16:01:01 -08001121int atransport::Write(apacket* p) {
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -07001122 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cui3cf1b362017-03-10 16:01:01 -08001123}
1124
Josh Gao3a2172b2019-03-28 15:47:44 -07001125void atransport::Reset() {
1126 if (!kicked_.exchange(true)) {
1127 LOG(INFO) << "resetting transport " << this << " " << this->serial;
1128 this->connection()->Reset();
1129 }
1130}
1131
Yabin Cuif2a9f9b2016-04-18 11:22:34 -07001132void atransport::Kick() {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001133 if (!kicked_.exchange(true)) {
Josh Gao3a2172b2019-03-28 15:47:44 -07001134 LOG(INFO) << "kicking transport " << this << " " << this->serial;
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -07001135 this->connection()->Stop();
Yabin Cuif2a9f9b2016-04-18 11:22:34 -07001136 }
1137}
1138
Yabin Cui3cf1b362017-03-10 16:01:01 -08001139ConnectionState atransport::GetConnectionState() const {
1140 return connection_state_;
1141}
1142
1143void atransport::SetConnectionState(ConnectionState state) {
1144 check_main_thread();
1145 connection_state_ = state;
Joshua Duongccde5202021-03-08 15:01:48 -08001146 update_transports();
Yabin Cui3cf1b362017-03-10 16:01:01 -08001147}
1148
Josh Gao8e7c9722021-06-17 04:19:45 -07001149#if ADB_HOST
1150bool atransport::Attach(std::string* error) {
1151 D("%s: attach", serial.c_str());
1152 check_main_thread();
1153
1154 if (!should_use_libusb()) {
1155 *error = "attach/detach only implemented for libusb backend";
1156 return false;
1157 }
1158
1159 if (GetConnectionState() != ConnectionState::kCsDetached) {
1160 *error = android::base::StringPrintf("transport %s is not detached", serial.c_str());
1161 return false;
1162 }
1163
1164 ResetKeys();
1165
1166 {
1167 std::lock_guard<std::mutex> lock(mutex_);
1168 if (!connection_->Attach(error)) {
1169 return false;
1170 }
1171 }
1172
1173 send_connect(this);
1174 return true;
1175}
1176
1177bool atransport::Detach(std::string* error) {
1178 D("%s: detach", serial.c_str());
1179 check_main_thread();
1180
1181 if (!should_use_libusb()) {
1182 *error = "attach/detach only implemented for libusb backend";
1183 return false;
1184 }
1185
1186 if (GetConnectionState() == ConnectionState::kCsDetached) {
1187 *error = android::base::StringPrintf("transport %s is already detached", serial.c_str());
1188 return false;
1189 }
1190
1191 handle_offline(this);
1192
1193 {
1194 std::lock_guard<std::mutex> lock(mutex_);
1195 if (!connection_->Detach(error)) {
1196 return false;
1197 }
1198 }
1199
1200 this->SetConnectionState(kCsDetached);
1201 return true;
1202}
1203#endif
1204
Josh Gaof2d6af52021-04-27 20:32:02 -07001205void atransport::SetConnection(std::shared_ptr<Connection> connection) {
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -07001206 std::lock_guard<std::mutex> lock(mutex_);
1207 connection_ = std::shared_ptr<Connection>(std::move(connection));
1208}
1209
Josh Gao7852ca42021-06-17 04:17:25 -07001210bool atransport::HandleRead(std::unique_ptr<apacket> p) {
1211 if (!check_header(p.get(), this)) {
1212 D("%s: remote read: bad header", serial.c_str());
1213 return false;
1214 }
1215
1216 VLOG(TRANSPORT) << dump_packet(serial.c_str(), "from remote", p.get());
1217 apacket* packet = p.release();
1218
1219 // TODO: Does this need to run on the main thread?
1220 fdevent_run_on_main_thread([packet, this]() { handle_packet(packet, this); });
1221 return true;
1222}
1223
1224void atransport::HandleError(const std::string& error) {
1225 LOG(INFO) << serial_name() << ": connection terminated: " << error;
1226 fdevent_run_on_main_thread([this]() {
1227 handle_offline(this);
1228 transport_destroy(this);
1229 });
1230}
1231
Tamas Berghammera1c60c02015-07-13 19:12:28 +01001232void atransport::update_version(int version, size_t payload) {
1233 protocol_version = std::min(version, A_VERSION);
1234 max_payload = std::min(payload, MAX_PAYLOAD);
1235}
1236
1237int atransport::get_protocol_version() const {
1238 return protocol_version;
1239}
1240
Joshua Duong64fab752020-01-21 13:19:42 -08001241int atransport::get_tls_version() const {
1242 return tls_version;
1243}
1244
Tamas Berghammera1c60c02015-07-13 19:12:28 +01001245size_t atransport::get_max_payload() const {
1246 return max_payload;
1247}
1248
Dan Albertbe8e54b2015-05-18 13:06:53 -07001249const FeatureSet& supported_features() {
Yurii Zubrytskyi816c2d22020-03-26 18:19:28 -07001250 static const android::base::NoDestructor<FeatureSet> features([] {
1251 return FeatureSet{
1252 kFeatureShell2,
1253 kFeatureCmd,
1254 kFeatureStat2,
1255 kFeatureLs2,
1256 kFeatureFixedPushMkdir,
1257 kFeatureApex,
1258 kFeatureAbb,
1259 kFeatureFixedPushSymlinkTimestamp,
1260 kFeatureAbbExec,
1261 kFeatureRemountShell,
1262 kFeatureTrackApp,
1263 kFeatureSendRecv2,
1264 kFeatureSendRecv2Brotli,
1265 kFeatureSendRecv2LZ4,
Josh Gaobdebc9b2020-05-27 17:52:52 -07001266 kFeatureSendRecv2Zstd,
Yurii Zubrytskyi816c2d22020-03-26 18:19:28 -07001267 kFeatureSendRecv2DryRunSend,
Joshua Duongf4ba8d72021-01-13 12:18:15 -08001268 kFeatureOpenscreenMdns,
Yurii Zubrytskyi816c2d22020-03-26 18:19:28 -07001269 // Increment ADB_SERVER_VERSION when adding a feature that adbd needs
1270 // to know about. Otherwise, the client can be stuck running an old
1271 // version of the server even after upgrading their copy of adb.
1272 // (http://b/24370690)
1273 };
1274 }());
David Pursella07dbad2015-09-22 10:43:08 -07001275
1276 return *features;
1277}
1278
1279std::string FeatureSetToString(const FeatureSet& features) {
Elliott Hughesc3462f42018-09-05 12:13:11 -07001280 return android::base::Join(features, ',');
David Pursella07dbad2015-09-22 10:43:08 -07001281}
1282
1283FeatureSet StringToFeatureSet(const std::string& features_string) {
David Pursell3d9072b2015-09-25 13:04:21 -07001284 if (features_string.empty()) {
1285 return FeatureSet();
1286 }
1287
Yurii Zubrytskyi816c2d22020-03-26 18:19:28 -07001288 return android::base::Split(features_string, ",");
1289}
1290
1291template <class Range, class Value>
1292static bool contains(const Range& r, const Value& v) {
1293 return std::find(std::begin(r), std::end(r), v) != std::end(r);
Dan Albertbe8e54b2015-05-18 13:06:53 -07001294}
1295
David Pursell22fc5e92015-09-30 13:35:42 -07001296bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Yurii Zubrytskyi816c2d22020-03-26 18:19:28 -07001297 return contains(feature_set, feature) && contains(supported_features(), feature);
David Pursell22fc5e92015-09-30 13:35:42 -07001298}
1299
Dan Albertbe8e54b2015-05-18 13:06:53 -07001300bool atransport::has_feature(const std::string& feature) const {
Yurii Zubrytskyi816c2d22020-03-26 18:19:28 -07001301 return contains(features_, feature);
Dan Albertbe8e54b2015-05-18 13:06:53 -07001302}
1303
David Pursella07dbad2015-09-22 10:43:08 -07001304void atransport::SetFeatures(const std::string& features_string) {
1305 features_ = StringToFeatureSet(features_string);
Dan Albertbe8e54b2015-05-18 13:06:53 -07001306}
1307
Yabin Cui2d4c1982015-08-28 15:09:44 -07001308void atransport::AddDisconnect(adisconnect* disconnect) {
1309 disconnects_.push_back(disconnect);
1310}
1311
1312void atransport::RemoveDisconnect(adisconnect* disconnect) {
1313 disconnects_.remove(disconnect);
1314}
1315
1316void atransport::RunDisconnects() {
Elliott Hughes85952832015-10-07 15:59:35 -07001317 for (const auto& disconnect : disconnects_) {
Yabin Cui2d4c1982015-08-28 15:09:44 -07001318 disconnect->func(disconnect->opaque, this);
1319 }
1320 disconnects_.clear();
1321}
1322
Josh Gao65d18e22020-04-22 20:57:26 -07001323#if ADB_HOST
David Pursellc929c6f2016-03-01 08:58:26 -08001324bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001325 if (!serial.empty()) {
David Pursellc929c6f2016-03-01 08:58:26 -08001326 if (target == serial) {
1327 return true;
1328 } else if (type == kTransportLocal) {
1329 // Local transports can match [tcp:|udp:]<hostname>[:port].
1330 const char* local_target_ptr = target.c_str();
1331
1332 // For fastboot compatibility, ignore protocol prefixes.
1333 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao0d6aa992016-11-22 14:32:34 -08001334 android::base::StartsWith(target, "udp:")) {
David Pursellc929c6f2016-03-01 08:58:26 -08001335 local_target_ptr += 4;
1336 }
1337
1338 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1339 std::string serial_host, error;
1340 int serial_port = -1;
Josh Gao7852ca42021-06-17 04:17:25 -07001341 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr,
1342 &error)) {
David Pursellc929c6f2016-03-01 08:58:26 -08001343 // |target| may omit the port to default to ours.
1344 std::string target_host;
1345 int target_port = serial_port;
1346 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1347 nullptr, &error) &&
Josh Gao0d6aa992016-11-22 14:32:34 -08001348 serial_host == target_host && serial_port == target_port) {
David Pursellc929c6f2016-03-01 08:58:26 -08001349 return true;
1350 }
1351 }
1352 }
1353 }
1354
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001355 return (target == devpath) || qual_match(target, "product:", product, false) ||
1356 qual_match(target, "model:", model, true) ||
1357 qual_match(target, "device:", device, false);
David Pursellc929c6f2016-03-01 08:58:26 -08001358}
1359
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001360void atransport::SetConnectionEstablished(bool success) {
1361 connection_waitable_->SetConnectionEstablished(success);
1362}
1363
Josh Gaod24580d2018-08-30 11:37:00 -07001364ReconnectResult atransport::Reconnect() {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001365 return reconnect_(this);
1366}
1367
Josh Gaob39e4152017-08-16 16:57:01 -07001368// We use newline as our delimiter, make sure to never output it.
1369static std::string sanitize(std::string str, bool alphanumeric) {
1370 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1371 : [](const char c) { return c == '\n'; };
1372 std::replace_if(str.begin(), str.end(), pred, '_');
1373 return str;
1374}
1375
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001376static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob39e4152017-08-16 16:57:01 -07001377 bool alphanumeric) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001378 if (value.empty()) {
Scott Anderson27042382012-05-30 18:11:27 -07001379 return;
Scott Anderson27042382012-05-30 18:11:27 -07001380 }
1381
Elliott Hughes88b4c852015-04-30 17:32:03 -07001382 *result += ' ';
1383 *result += key;
Josh Gaob39e4152017-08-16 16:57:01 -07001384 *result += sanitize(value, alphanumeric);
Scott Anderson27042382012-05-30 18:11:27 -07001385}
1386
Josh Gao0d6aa992016-11-22 14:32:34 -08001387static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001388 std::string serial = t->serial;
1389 if (serial.empty()) {
Dan Alberta8c34142015-05-06 16:48:52 -07001390 serial = "(no serial number)";
Elliott Hughes88b4c852015-04-30 17:32:03 -07001391 }
Scott Anderson27042382012-05-30 18:11:27 -07001392
1393 if (!long_listing) {
Elliott Hughes88b4c852015-04-30 17:32:03 -07001394 *result += serial;
1395 *result += '\t';
Josh Gao6256d992021-05-20 18:28:13 -07001396 *result += to_string(t->GetConnectionState());
Scott Anderson27042382012-05-30 18:11:27 -07001397 } else {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001398 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
Josh Gao6256d992021-05-20 18:28:13 -07001399 to_string(t->GetConnectionState()).c_str());
Scott Anderson27042382012-05-30 18:11:27 -07001400
Elliott Hughes88b4c852015-04-30 17:32:03 -07001401 append_transport_info(result, "", t->devpath, false);
1402 append_transport_info(result, "product:", t->product, false);
1403 append_transport_info(result, "model:", t->model, true);
1404 append_transport_info(result, "device:", t->device, false);
Josh Gaob39e4152017-08-16 16:57:01 -07001405
1406 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1407 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1408 *result += " transport_id:";
1409 *result += std::to_string(t->id);
Scott Anderson27042382012-05-30 18:11:27 -07001410 }
Elliott Hughes88b4c852015-04-30 17:32:03 -07001411 *result += '\n';
Scott Anderson27042382012-05-30 18:11:27 -07001412}
1413
Elliott Hughes88b4c852015-04-30 17:32:03 -07001414std::string list_transports(bool long_listing) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001415 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov4dd35012017-12-17 10:56:07 +00001416
1417 auto sorted_transport_list = transport_list;
1418 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1419 if (x->type != y->type) {
1420 return x->type < y->type;
1421 }
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001422 return x->serial < y->serial;
Artem Iglikov4dd35012017-12-17 10:56:07 +00001423 });
1424
1425 std::string result;
1426 for (const auto& t : sorted_transport_list) {
Elliott Hughes88b4c852015-04-30 17:32:03 -07001427 append_transport(t, &result, long_listing);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001428 }
Elliott Hughes88b4c852015-04-30 17:32:03 -07001429 return result;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001430}
1431
Josh Gao3a2172b2019-03-28 15:47:44 -07001432void close_usb_devices(std::function<bool(const atransport*)> predicate, bool reset) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001433 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao4e562502016-10-27 14:01:08 -07001434 for (auto& t : transport_list) {
1435 if (predicate(t)) {
Josh Gao3a2172b2019-03-28 15:47:44 -07001436 if (reset) {
1437 t->Reset();
1438 } else {
1439 t->Kick();
1440 }
Josh Gao4e562502016-10-27 14:01:08 -07001441 }
1442 }
1443}
1444
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001445/* hack for osx */
Josh Gao3a2172b2019-03-28 15:47:44 -07001446void close_usb_devices(bool reset) {
1447 close_usb_devices([](const atransport*) { return true; }, reset);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001448}
Josh Gao65d18e22020-04-22 20:57:26 -07001449#endif
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001450
Josh Gao597044d2018-08-08 16:20:14 -07001451bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
Joshua Duong64fab752020-01-21 13:19:42 -08001452 atransport::ReconnectCallback reconnect, bool use_tls, int* error) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001453 atransport* t = new atransport(std::move(reconnect), kCsOffline);
Joshua Duong64fab752020-01-21 13:19:42 -08001454 t->use_tls = use_tls;
David 'Digit' Turner58f59682011-01-06 14:11:07 +01001455
Josh Gaoa3a71472018-08-02 13:58:24 -07001456 D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
Josh Gaofa3107e2018-07-25 17:21:49 -07001457 if (init_socket_transport(t, std::move(s), port, local) < 0) {
Dan Albertecce5032015-05-18 16:46:31 -07001458 delete t;
Josh Gao597044d2018-08-08 16:20:14 -07001459 if (error) *error = errno;
1460 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001461 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001462
Josh Gaoaaa82f72017-08-17 13:50:51 -07001463 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes85952832015-10-07 15:59:35 -07001464 for (const auto& transport : pending_list) {
Josh Gaoa3a71472018-08-02 13:58:24 -07001465 if (serial == transport->serial) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001466 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao0d6aa992016-11-22 14:32:34 -08001467 << " is already in pending_list and fails to register";
Dan Albertecce5032015-05-18 16:46:31 -07001468 delete t;
Josh Gao597044d2018-08-08 16:20:14 -07001469 if (error) *error = EALREADY;
1470 return false;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001471 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001472 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001473
Elliott Hughes85952832015-10-07 15:59:35 -07001474 for (const auto& transport : transport_list) {
Josh Gaoa3a71472018-08-02 13:58:24 -07001475 if (serial == transport->serial) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001476 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao0d6aa992016-11-22 14:32:34 -08001477 << " is already in transport_list and fails to register";
Dan Albertecce5032015-05-18 16:46:31 -07001478 delete t;
Josh Gao597044d2018-08-08 16:20:14 -07001479 if (error) *error = EALREADY;
1480 return false;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001481 }
1482 }
1483
Josh Gaoa3a71472018-08-02 13:58:24 -07001484 t->serial = std::move(serial);
Dan Albertecce5032015-05-18 16:46:31 -07001485 pending_list.push_front(t);
Josh Gaoe7daf572016-09-21 12:37:10 -07001486
1487 lock.unlock();
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001488
Josh Gao65d18e22020-04-22 20:57:26 -07001489#if ADB_HOST
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001490 auto waitable = t->connection_waitable();
Josh Gao65d18e22020-04-22 20:57:26 -07001491#endif
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001492 register_transport(t);
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001493
Luis Hector Chavez25bc41c2018-05-01 17:12:16 -07001494 if (local == 1) {
1495 // Do not wait for emulator transports.
Josh Gao597044d2018-08-08 16:20:14 -07001496 return true;
Luis Hector Chavez25bc41c2018-05-01 17:12:16 -07001497 }
1498
Josh Gao65d18e22020-04-22 20:57:26 -07001499#if ADB_HOST
Josh Gao597044d2018-08-08 16:20:14 -07001500 if (!waitable->WaitForConnection(std::chrono::seconds(10))) {
1501 if (error) *error = ETIMEDOUT;
1502 return false;
1503 }
1504
1505 if (t->GetConnectionState() == kCsUnauthorized) {
1506 if (error) *error = EPERM;
1507 return false;
1508 }
Josh Gao65d18e22020-04-22 20:57:26 -07001509#endif
Josh Gao597044d2018-08-08 16:20:14 -07001510
1511 return true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001512}
1513
Mike Lockwood81ffe172009-10-11 23:04:18 -04001514#if ADB_HOST
Josh Gao0d6aa992016-11-22 14:32:34 -08001515atransport* find_transport(const char* serial) {
Dan Albertecce5032015-05-18 16:46:31 -07001516 atransport* result = nullptr;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001517
Josh Gaoaaa82f72017-08-17 13:50:51 -07001518 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui4d64fd82015-08-27 12:03:11 -07001519 for (auto& t : transport_list) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001520 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertecce5032015-05-18 16:46:31 -07001521 result = t;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001522 break;
1523 }
Dan Albertecce5032015-05-18 16:46:31 -07001524 }
Mike Lockwood81ffe172009-10-11 23:04:18 -04001525
Dan Albertecce5032015-05-18 16:46:31 -07001526 return result;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001527}
1528
Yabin Cui4d64fd82015-08-27 12:03:11 -07001529void kick_all_tcp_devices() {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001530 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui4d64fd82015-08-27 12:03:11 -07001531 for (auto& t : transport_list) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001532 if (t->IsTcpDevice()) {
Yabin Cui4e222292015-08-31 11:50:24 -07001533 // Kicking breaks the read_transport thread of this transport out of any read, then
1534 // the read_transport thread will notify the main thread to make this transport
1535 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cui4d64fd82015-08-27 12:03:11 -07001536 // Finally, this transport will be closed and freed in the main thread.
Yabin Cuif2a9f9b2016-04-18 11:22:34 -07001537 t->Kick();
Mike Lockwood01c2c302010-05-24 10:44:35 -04001538 }
Dan Albertecce5032015-05-18 16:46:31 -07001539 }
Josh Gao13cb8c02018-08-10 14:44:54 -07001540 reconnect_handler.CheckForKicked();
Mike Lockwood01c2c302010-05-24 10:44:35 -04001541}
1542
Josh Gaof2d6af52021-04-27 20:32:02 -07001543void register_usb_transport(std::shared_ptr<Connection> connection, const char* serial,
1544 const char* devpath, unsigned writeable) {
1545 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
1546 if (serial) {
1547 t->serial = serial;
1548 }
1549 if (devpath) {
1550 t->devpath = devpath;
1551 }
1552
1553 t->SetConnection(std::move(connection));
1554 t->type = kTransportUsb;
1555
1556 {
1557 std::lock_guard<std::recursive_mutex> lock(transport_lock);
1558 pending_list.push_front(t);
1559 }
1560
1561 register_transport(t);
1562}
1563
Josh Gao0d6aa992016-11-22 14:32:34 -08001564void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1565 unsigned writeable) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001566 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertecce5032015-05-18 16:46:31 -07001567
Josh Gao0d6aa992016-11-22 14:32:34 -08001568 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cui3cf1b362017-03-10 16:01:01 -08001569 init_usb_transport(t, usb);
Josh Gao0d6aa992016-11-22 14:32:34 -08001570 if (serial) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001571 t->serial = serial;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001572 }
Dan Albertecce5032015-05-18 16:46:31 -07001573
1574 if (devpath) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001575 t->devpath = devpath;
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001576 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001577
Josh Gaoe7daf572016-09-21 12:37:10 -07001578 {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001579 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaoe7daf572016-09-21 12:37:10 -07001580 pending_list.push_front(t);
1581 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001582
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001583 register_transport(t);
1584}
1585
Dan Albert9a50f4c2015-05-18 16:43:57 -07001586// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao0d6aa992016-11-22 14:32:34 -08001587void unregister_usb_transport(usb_handle* usb) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001588 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao395b86a2018-01-28 20:32:46 -08001589 transport_list.remove_if([usb](atransport* t) {
Josh Gao68f2c382018-12-11 13:11:52 -08001590 return t->GetUsbHandle() == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gao395b86a2018-01-28 20:32:46 -08001591 });
Mike Lockwoode45583f2009-08-08 12:37:44 -04001592}
Josh Gao3a34bc52018-10-11 16:33:05 -07001593#endif
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001594
Josh Gao67b683a2017-05-16 15:02:45 -07001595bool check_header(apacket* p, atransport* t) {
Josh Gao0d6aa992016-11-22 14:32:34 -08001596 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cui3cf1b362017-03-10 16:01:01 -08001597 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1598 << ", magic = " << p->msg.magic;
Josh Gao67b683a2017-05-16 15:02:45 -07001599 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001600 }
1601
Josh Gao0d6aa992016-11-22 14:32:34 -08001602 if (p->msg.data_length > t->get_max_payload()) {
1603 VLOG(RWX) << "check_header(): " << p->msg.data_length
1604 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao67b683a2017-05-16 15:02:45 -07001605 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001606 }
1607
Josh Gao67b683a2017-05-16 15:02:45 -07001608 return true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001609}
1610
Josh Gaoeac20582016-10-05 19:02:29 -07001611#if ADB_HOST
Joshua Duong64fab752020-01-21 13:19:42 -08001612std::shared_ptr<RSA> atransport::Key() {
1613 if (keys_.empty()) {
1614 return nullptr;
1615 }
1616
1617 std::shared_ptr<RSA> result = keys_[0];
1618 return result;
1619}
1620
Josh Gao22cb70b2016-08-18 22:00:12 -07001621std::shared_ptr<RSA> atransport::NextKey() {
Josh Gaoeb656522018-12-04 01:07:50 -08001622 if (keys_.empty()) {
1623 LOG(INFO) << "fetching keys for transport " << this->serial_name();
1624 keys_ = adb_auth_get_private_keys();
1625
1626 // We should have gotten at least one key: the one that's automatically generated.
1627 CHECK(!keys_.empty());
Joshua Duong64fab752020-01-21 13:19:42 -08001628 } else {
1629 keys_.pop_front();
Josh Gaoeb656522018-12-04 01:07:50 -08001630 }
Elliott Hughes801066a2016-06-29 17:42:01 -07001631
Josh Gaod60bafd2020-06-11 21:07:27 -07001632 return Key();
Elliott Hughes801066a2016-06-29 17:42:01 -07001633}
Josh Gaoeb656522018-12-04 01:07:50 -08001634
1635void atransport::ResetKeys() {
1636 keys_.clear();
1637}
Josh Gaoeac20582016-10-05 19:02:29 -07001638#endif