blob: fbcf79b408525819f7961e7b1920d7fe0c0b0e46 [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>
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";
Josh Gao2f0f9eb2020-03-04 19:34:08 -080085const char* const kFeatureSendRecv2 = "sendrecv_v2";
86const char* const kFeatureSendRecv2Brotli = "sendrecv_v2_brotli";
Josh Gaofb386cc2020-03-26 22:02:03 -070087const char* const kFeatureSendRecv2LZ4 = "sendrecv_v2_lz4";
Josh Gaobdebc9b2020-05-27 17:52:52 -070088const char* const kFeatureSendRecv2Zstd = "sendrecv_v2_zstd";
Josh Gao8a410a02020-03-30 23:25:16 -070089const char* const kFeatureSendRecv2DryRunSend = "sendrecv_v2_dry_run_send";
Joshua Duongf4ba8d72021-01-13 12:18:15 -080090// TODO(joshuaduong): Bump to v2 when openscreen discovery is enabled by default
91const char* const kFeatureOpenscreenMdns = "openscreen_mdns";
Todd Kennedyaff9c672015-11-10 00:03:25 +000092
Luis Hector Chavezda74b902018-04-17 14:25:04 -070093namespace {
94
Josh Gao5c47e9f2018-07-31 18:28:32 -070095#if ADB_HOST
Luis Hector Chavez0aeda102018-04-20 10:31:29 -070096// Tracks and handles atransport*s that are attempting reconnection.
97class ReconnectHandler {
98 public:
99 ReconnectHandler() = default;
100 ~ReconnectHandler() = default;
101
102 // Starts the ReconnectHandler thread.
103 void Start();
104
105 // Requests the ReconnectHandler thread to stop.
106 void Stop();
107
108 // Adds the atransport* to the queue of reconnect attempts.
109 void TrackTransport(atransport* transport);
110
Josh Gao13cb8c02018-08-10 14:44:54 -0700111 // Wake up the ReconnectHandler thread to have it check for kicked transports.
112 void CheckForKicked();
113
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700114 private:
115 // The main thread loop.
116 void Run();
117
118 // Tracks a reconnection attempt.
119 struct ReconnectAttempt {
120 atransport* transport;
Josh Gaoc4deb392018-07-30 18:51:55 -0700121 std::chrono::steady_clock::time_point reconnect_time;
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700122 size_t attempts_left;
Josh Gaob0182892018-07-31 14:12:59 -0700123
124 bool operator<(const ReconnectAttempt& rhs) const {
Josh Gaod2ea0652018-08-10 14:28:24 -0700125 if (reconnect_time == rhs.reconnect_time) {
126 return reinterpret_cast<uintptr_t>(transport) <
127 reinterpret_cast<uintptr_t>(rhs.transport);
128 }
129 return reconnect_time < rhs.reconnect_time;
Josh Gaob0182892018-07-31 14:12:59 -0700130 }
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700131 };
132
133 // Only retry for up to one minute.
Josh Gao04ef6962020-10-15 18:32:55 -0700134 static constexpr const std::chrono::seconds kDefaultTimeout = 3s;
135 static constexpr const size_t kMaxAttempts = 20;
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700136
137 // Protects all members.
138 std::mutex reconnect_mutex_;
139 bool running_ GUARDED_BY(reconnect_mutex_) = true;
140 std::thread handler_thread_;
141 std::condition_variable reconnect_cv_;
Josh Gaod2ea0652018-08-10 14:28:24 -0700142 std::set<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700143
144 DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
145};
146
147void ReconnectHandler::Start() {
148 check_main_thread();
149 handler_thread_ = std::thread(&ReconnectHandler::Run, this);
150}
151
152void ReconnectHandler::Stop() {
153 check_main_thread();
154 {
155 std::lock_guard<std::mutex> lock(reconnect_mutex_);
156 running_ = false;
157 }
158 reconnect_cv_.notify_one();
159 handler_thread_.join();
160
161 // Drain the queue to free all resources.
162 std::lock_guard<std::mutex> lock(reconnect_mutex_);
163 while (!reconnect_queue_.empty()) {
Josh Gaod2ea0652018-08-10 14:28:24 -0700164 ReconnectAttempt attempt = *reconnect_queue_.begin();
165 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700166 remove_transport(attempt.transport);
167 }
168}
169
170void ReconnectHandler::TrackTransport(atransport* transport) {
171 check_main_thread();
172 {
173 std::lock_guard<std::mutex> lock(reconnect_mutex_);
174 if (!running_) return;
Josh Gaob0182892018-07-31 14:12:59 -0700175 // Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
176 auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
177 reconnect_queue_.emplace(
178 ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700179 }
180 reconnect_cv_.notify_one();
181}
182
Josh Gao13cb8c02018-08-10 14:44:54 -0700183void ReconnectHandler::CheckForKicked() {
184 reconnect_cv_.notify_one();
185}
186
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700187void ReconnectHandler::Run() {
188 while (true) {
189 ReconnectAttempt attempt;
190 {
191 std::unique_lock<std::mutex> lock(reconnect_mutex_);
Josh Gao8aa57d22019-02-12 13:59:03 -0800192 ScopedLockAssertion assume_lock(reconnect_mutex_);
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700193
Josh Gaoc4deb392018-07-30 18:51:55 -0700194 if (!reconnect_queue_.empty()) {
195 // FIXME: libstdc++ (used on Windows) implements condition_variable with
196 // system_clock as its clock, so we're probably hosed if the clock changes,
197 // even if we use steady_clock throughout. This problem goes away once we
198 // switch to libc++.
Josh Gaod2ea0652018-08-10 14:28:24 -0700199 reconnect_cv_.wait_until(lock, reconnect_queue_.begin()->reconnect_time);
Josh Gaoc4deb392018-07-30 18:51:55 -0700200 } else {
201 reconnect_cv_.wait(lock);
202 }
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700203
204 if (!running_) return;
Josh Gao13cb8c02018-08-10 14:44:54 -0700205
206 // Scan the whole list for kicked transports, so that we immediately handle an explicit
207 // disconnect request.
208 bool kicked = false;
209 for (auto it = reconnect_queue_.begin(); it != reconnect_queue_.end();) {
210 if (it->transport->kicked()) {
211 D("transport %s was kicked. giving up on it.", it->transport->serial.c_str());
212 remove_transport(it->transport);
213 it = reconnect_queue_.erase(it);
214 } else {
215 ++it;
216 }
217 kicked = true;
218 }
219
Josh Gaoc4deb392018-07-30 18:51:55 -0700220 if (reconnect_queue_.empty()) continue;
221
Josh Gao13cb8c02018-08-10 14:44:54 -0700222 // Go back to sleep if we either woke up spuriously, or we were woken up to remove
223 // a kicked transport, and the first transport isn't ready for reconnection yet.
Josh Gaoc4deb392018-07-30 18:51:55 -0700224 auto now = std::chrono::steady_clock::now();
Josh Gaod2ea0652018-08-10 14:28:24 -0700225 if (reconnect_queue_.begin()->reconnect_time > now) {
Josh Gaoc4deb392018-07-30 18:51:55 -0700226 continue;
227 }
228
Josh Gaod2ea0652018-08-10 14:28:24 -0700229 attempt = *reconnect_queue_.begin();
230 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700231 }
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700232 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700233
Josh Gaod24580d2018-08-30 11:37:00 -0700234 switch (attempt.transport->Reconnect()) {
235 case ReconnectResult::Retry: {
236 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
237 if (attempt.attempts_left == 0) {
238 D("transport %s exceeded the number of retry attempts. giving up on it.",
239 attempt.transport->serial.c_str());
240 remove_transport(attempt.transport);
241 continue;
242 }
243
244 std::lock_guard<std::mutex> lock(reconnect_mutex_);
245 reconnect_queue_.emplace(ReconnectAttempt{
246 attempt.transport,
247 std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
248 attempt.attempts_left - 1});
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700249 continue;
250 }
251
Josh Gaod24580d2018-08-30 11:37:00 -0700252 case ReconnectResult::Success:
253 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
254 register_transport(attempt.transport);
255 continue;
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700256
Josh Gaod24580d2018-08-30 11:37:00 -0700257 case ReconnectResult::Abort:
258 D("cancelling reconnection attempt to %s.", attempt.transport->serial.c_str());
259 remove_transport(attempt.transport);
260 continue;
261 }
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700262 }
263}
264
265static auto& reconnect_handler = *new ReconnectHandler();
266
Josh Gao5c47e9f2018-07-31 18:28:32 -0700267#endif
268
Luis Hector Chavezda74b902018-04-17 14:25:04 -0700269} // namespace
270
Josh Gaob39e4152017-08-16 16:57:01 -0700271TransportId NextTransportId() {
272 static std::atomic<TransportId> next(1);
273 return next++;
274}
275
Josh Gao3a2172b2019-03-28 15:47:44 -0700276void Connection::Reset() {
277 LOG(INFO) << "Connection::Reset(): stopping";
278 Stop();
279}
280
Josh Gao715fe602018-02-16 13:24:58 -0800281BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
282 : underlying_(std::move(connection)) {}
283
284BlockingConnectionAdapter::~BlockingConnectionAdapter() {
285 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
286 Stop();
287}
288
289void BlockingConnectionAdapter::Start() {
Josh Gao13781e82018-04-03 12:55:18 -0700290 std::lock_guard<std::mutex> lock(mutex_);
291 if (started_) {
292 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
293 << "): started multiple times";
294 }
295
Joshua Duong64fab752020-01-21 13:19:42 -0800296 StartReadThread();
Josh Gao715fe602018-02-16 13:24:58 -0800297
298 write_thread_ = std::thread([this]() {
299 LOG(INFO) << this->transport_name_ << ": write thread spawning";
300 while (true) {
301 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao8aa57d22019-02-12 13:59:03 -0800302 ScopedLockAssertion assume_locked(mutex_);
Josh Gao13781e82018-04-03 12:55:18 -0700303 cv_.wait(lock, [this]() REQUIRES(mutex_) {
304 return this->stopped_ || !this->write_queue_.empty();
305 });
306
Josh Gao715fe602018-02-16 13:24:58 -0800307 if (this->stopped_) {
308 return;
309 }
310
311 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
312 this->write_queue_.pop_front();
313 lock.unlock();
314
315 if (!this->underlying_->Write(packet.get())) {
316 break;
317 }
318 }
319 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
320 });
Josh Gao13781e82018-04-03 12:55:18 -0700321
322 started_ = true;
Josh Gao715fe602018-02-16 13:24:58 -0800323}
324
Joshua Duong64fab752020-01-21 13:19:42 -0800325void BlockingConnectionAdapter::StartReadThread() {
326 read_thread_ = std::thread([this]() {
327 LOG(INFO) << this->transport_name_ << ": read thread spawning";
328 while (true) {
329 auto packet = std::make_unique<apacket>();
330 if (!underlying_->Read(packet.get())) {
331 PLOG(INFO) << this->transport_name_ << ": read failed";
332 break;
333 }
334
335 bool got_stls_cmd = false;
336 if (packet->msg.command == A_STLS) {
337 got_stls_cmd = true;
338 }
339
340 read_callback_(this, std::move(packet));
341
342 // If we received the STLS packet, we are about to perform the TLS
343 // handshake. So this read thread must stop and resume after the
344 // handshake completes otherwise this will interfere in the process.
345 if (got_stls_cmd) {
346 LOG(INFO) << this->transport_name_
347 << ": Received STLS packet. Stopping read thread.";
348 return;
349 }
350 }
351 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
352 });
353}
354
355bool BlockingConnectionAdapter::DoTlsHandshake(RSA* key, std::string* auth_key) {
356 std::lock_guard<std::mutex> lock(mutex_);
357 if (read_thread_.joinable()) {
358 read_thread_.join();
359 }
360 bool success = this->underlying_->DoTlsHandshake(key, auth_key);
361 StartReadThread();
362 return success;
363}
364
Josh Gao3a2172b2019-03-28 15:47:44 -0700365void BlockingConnectionAdapter::Reset() {
366 {
367 std::lock_guard<std::mutex> lock(mutex_);
368 if (!started_) {
369 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
370 return;
371 }
372
373 if (stopped_) {
374 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
375 << "): already stopped";
376 return;
377 }
378 }
379
380 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): resetting";
381 this->underlying_->Reset();
382 Stop();
383}
384
Josh Gao715fe602018-02-16 13:24:58 -0800385void BlockingConnectionAdapter::Stop() {
Josh Gao13781e82018-04-03 12:55:18 -0700386 {
387 std::lock_guard<std::mutex> lock(mutex_);
388 if (!started_) {
389 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
390 return;
391 }
Josh Gao715fe602018-02-16 13:24:58 -0800392
Josh Gao13781e82018-04-03 12:55:18 -0700393 if (stopped_) {
394 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
395 << "): already stopped";
396 return;
397 }
398
399 stopped_ = true;
400 }
Josh Gao715fe602018-02-16 13:24:58 -0800401
402 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
403
404 this->underlying_->Close();
Josh Gao715fe602018-02-16 13:24:58 -0800405 this->cv_.notify_one();
Josh Gao13781e82018-04-03 12:55:18 -0700406
407 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
408 std::thread read_thread;
409 std::thread write_thread;
410
411 {
412 std::lock_guard<std::mutex> lock(mutex_);
413 read_thread = std::move(read_thread_);
414 write_thread = std::move(write_thread_);
415 }
416
417 read_thread.join();
418 write_thread.join();
Josh Gao715fe602018-02-16 13:24:58 -0800419
420 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
421 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
422}
423
424bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
425 {
Josh Gao13781e82018-04-03 12:55:18 -0700426 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao715fe602018-02-16 13:24:58 -0800427 write_queue_.emplace_back(std::move(packet));
428 }
429
430 cv_.notify_one();
431 return true;
432}
433
Joshua Duong64fab752020-01-21 13:19:42 -0800434FdConnection::FdConnection(unique_fd fd) : fd_(std::move(fd)) {}
435
436FdConnection::~FdConnection() {}
437
438bool FdConnection::DispatchRead(void* buf, size_t len) {
439 if (tls_ != nullptr) {
440 // The TlsConnection doesn't allow 0 byte reads
441 if (len == 0) {
442 return true;
443 }
444 return tls_->ReadFully(buf, len);
445 }
446
447 return ReadFdExactly(fd_.get(), buf, len);
448}
449
450bool FdConnection::DispatchWrite(void* buf, size_t len) {
451 if (tls_ != nullptr) {
452 // The TlsConnection doesn't allow 0 byte writes
453 if (len == 0) {
454 return true;
455 }
456 return tls_->WriteFully(std::string_view(reinterpret_cast<const char*>(buf), len));
457 }
458
459 return WriteFdExactly(fd_.get(), buf, len);
460}
461
Josh Gao395b86a2018-01-28 20:32:46 -0800462bool FdConnection::Read(apacket* packet) {
Joshua Duong64fab752020-01-21 13:19:42 -0800463 if (!DispatchRead(&packet->msg, sizeof(amessage))) {
Josh Gao395b86a2018-01-28 20:32:46 -0800464 D("remote local: read terminated (message)");
465 return false;
466 }
467
Josh Gao839b9322018-02-05 18:49:10 -0800468 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gaob14756a2018-02-02 14:38:04 -0800469 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
470 return false;
471 }
472
Josh Gao839b9322018-02-05 18:49:10 -0800473 packet->payload.resize(packet->msg.data_length);
474
Joshua Duong64fab752020-01-21 13:19:42 -0800475 if (!DispatchRead(&packet->payload[0], packet->payload.size())) {
Josh Gao395b86a2018-01-28 20:32:46 -0800476 D("remote local: terminated (data)");
477 return false;
478 }
479
480 return true;
481}
482
483bool FdConnection::Write(apacket* packet) {
Joshua Duong64fab752020-01-21 13:19:42 -0800484 if (!DispatchWrite(&packet->msg, sizeof(packet->msg))) {
Josh Gao395b86a2018-01-28 20:32:46 -0800485 D("remote local: write terminated");
486 return false;
487 }
488
Josh Gao839b9322018-02-05 18:49:10 -0800489 if (packet->msg.data_length) {
Joshua Duong64fab752020-01-21 13:19:42 -0800490 if (!DispatchWrite(&packet->payload[0], packet->msg.data_length)) {
Josh Gao839b9322018-02-05 18:49:10 -0800491 D("remote local: write terminated");
492 return false;
493 }
494 }
495
Josh Gao395b86a2018-01-28 20:32:46 -0800496 return true;
497}
498
Joshua Duong64fab752020-01-21 13:19:42 -0800499bool FdConnection::DoTlsHandshake(RSA* key, std::string* auth_key) {
500 bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
501 if (!EVP_PKEY_set1_RSA(evp_pkey.get(), key)) {
502 LOG(ERROR) << "EVP_PKEY_set1_RSA failed";
503 return false;
504 }
505 auto x509 = GenerateX509Certificate(evp_pkey.get());
506 auto x509_str = X509ToPEMString(x509.get());
507 auto evp_str = Key::ToPEMString(evp_pkey.get());
Joshua Duongdd19e862020-03-24 09:50:59 -0700508
Yurii Zubrytskyi3c0574f2020-03-26 18:16:36 -0700509 int osh = cast_handle_to_int(adb_get_os_handle(fd_));
Joshua Duong64fab752020-01-21 13:19:42 -0800510#if ADB_HOST
Joshua Duong77b8ff32020-04-16 15:58:19 -0700511 tls_ = TlsConnection::Create(TlsConnection::Role::Client, x509_str, evp_str, osh);
Joshua Duong64fab752020-01-21 13:19:42 -0800512#else
Joshua Duong77b8ff32020-04-16 15:58:19 -0700513 tls_ = TlsConnection::Create(TlsConnection::Role::Server, x509_str, evp_str, osh);
Joshua Duong64fab752020-01-21 13:19:42 -0800514#endif
Joshua Duong64fab752020-01-21 13:19:42 -0800515 CHECK(tls_);
516#if ADB_HOST
517 // TLS 1.3 gives the client no message if the server rejected the
518 // certificate. This will enable a check in the tls connection to check
519 // whether the client certificate got rejected. Note that this assumes
520 // that, on handshake success, the server speaks first.
521 tls_->EnableClientPostHandshakeCheck(true);
522 // Add callback to set the certificate when server issues the
523 // CertificateRequest.
524 tls_->SetCertificateCallback(adb_tls_set_certificate);
525 // Allow any server certificate
526 tls_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
527#else
528 // Add callback to check certificate against a list of known public keys
529 tls_->SetCertVerifyCallback(
530 [auth_key](X509_STORE_CTX* ctx) { return adbd_tls_verify_cert(ctx, auth_key); });
531 // Add the list of allowed client CA issuers
532 auto ca_list = adbd_tls_client_ca_list();
533 tls_->SetClientCAList(ca_list.get());
534#endif
535
536 auto err = tls_->DoHandshake();
537 if (err == TlsError::Success) {
538 return true;
539 }
540
541 tls_.reset();
542 return false;
543}
544
Josh Gao395b86a2018-01-28 20:32:46 -0800545void FdConnection::Close() {
546 adb_shutdown(fd_.get());
547 fd_.reset();
548}
549
Josh Gao67ac3792016-10-06 13:31:44 -0700550void send_packet(apacket* p, atransport* t) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800551 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayee7b44d2017-12-07 11:40:00 -0800552 // compute a checksum for connection/auth packets for compatibility reasons
553 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
554 p->msg.data_check = 0;
555 } else {
556 p->msg.data_check = calculate_apacket_checksum(p);
557 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800558
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700559 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800560
Yi Kong86e67182018-07-13 18:15:16 -0700561 if (t == nullptr) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700562 LOG(FATAL) << "Transport is null";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800563 }
564
Josh Gao715fe602018-02-16 13:24:58 -0800565 if (t->Write(p) != 0) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700566 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao715fe602018-02-16 13:24:58 -0800567 t->Kick();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800568 }
569}
570
Josh Gao3a2172b2019-03-28 15:47:44 -0700571void kick_transport(atransport* t, bool reset) {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700572 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuid78ed222016-04-05 13:50:44 -0700573 // As kick_transport() can be called from threads without guarantee that t is valid,
574 // check if the transport is in transport_list first.
Josh Gaob39e4152017-08-16 16:57:01 -0700575 //
576 // TODO(jmgao): WTF? Is this actually true?
Yabin Cuid78ed222016-04-05 13:50:44 -0700577 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Josh Gao3a2172b2019-03-28 15:47:44 -0700578 if (reset) {
579 t->Reset();
580 } else {
581 t->Kick();
582 }
Yabin Cuid78ed222016-04-05 13:50:44 -0700583 }
Josh Gao13cb8c02018-08-10 14:44:54 -0700584
585#if ADB_HOST
586 reconnect_handler.CheckForKicked();
587#endif
Yabin Cui4d64fd82015-08-27 12:03:11 -0700588}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800589
590static int transport_registration_send = -1;
591static int transport_registration_recv = -1;
Josh Gao9528df22018-05-14 11:14:33 -0700592static fdevent* transport_registration_fde;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800593
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800594#if ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800595
596/* this adds support required by the 'track-devices' service.
597 * this is used to send the content of "list_transport" to any
598 * number of client connections that want it through a single
599 * live TCP connection
600 */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800601struct device_tracker {
Josh Gao0d6aa992016-11-22 14:32:34 -0800602 asocket socket;
Josh Gao5cb76ce2018-02-12 17:24:00 -0800603 bool update_needed = false;
604 bool long_output = false;
605 device_tracker* next = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800606};
607
608/* linked list of all device trackers */
Josh Gao0d6aa992016-11-22 14:32:34 -0800609static device_tracker* device_tracker_list;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800610
Josh Gao0d6aa992016-11-22 14:32:34 -0800611static void device_tracker_remove(device_tracker* tracker) {
612 device_tracker** pnode = &device_tracker_list;
613 device_tracker* node = *pnode;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800614
Josh Gaoaaa82f72017-08-17 13:50:51 -0700615 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800616 while (node) {
617 if (node == tracker) {
618 *pnode = node->next;
619 break;
620 }
621 pnode = &node->next;
Josh Gao0d6aa992016-11-22 14:32:34 -0800622 node = *pnode;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800623 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800624}
625
Josh Gao0d6aa992016-11-22 14:32:34 -0800626static void device_tracker_close(asocket* socket) {
627 device_tracker* tracker = (device_tracker*)socket;
628 asocket* peer = socket->peer;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800629
Josh Gao0d6aa992016-11-22 14:32:34 -0800630 D("device tracker %p removed", tracker);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800631 if (peer) {
Yi Kong86e67182018-07-13 18:15:16 -0700632 peer->peer = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800633 peer->close(peer);
634 }
635 device_tracker_remove(tracker);
Josh Gao5cb76ce2018-02-12 17:24:00 -0800636 delete tracker;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800637}
638
Josh Gaocd2a5292018-03-07 16:52:28 -0800639static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800640 /* you can't read from a device tracker, close immediately */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800641 device_tracker_close(socket);
642 return -1;
643}
644
Elliott Hughes88b4c852015-04-30 17:32:03 -0700645static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughes88b4c852015-04-30 17:32:03 -0700646 asocket* peer = tracker->socket.peer;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800647
Josh Gaocd2a5292018-03-07 16:52:28 -0800648 apacket::payload_type data;
Josh Gaoa7d9d712018-02-01 13:17:50 -0800649 data.resize(4 + string.size());
650 char buf[5];
651 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
652 memcpy(&data[0], buf, 4);
653 memcpy(&data[4], string.data(), string.size());
654 return peer->enqueue(peer, std::move(data));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800655}
656
Elliott Hughes88b4c852015-04-30 17:32:03 -0700657static void device_tracker_ready(asocket* socket) {
658 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800659
Elliott Hughes88b4c852015-04-30 17:32:03 -0700660 // We want to send the device list when the tracker connects
661 // for the first time, even if no update occurred.
Josh Gao32124632017-08-14 18:57:54 -0700662 if (tracker->update_needed) {
663 tracker->update_needed = false;
Elliott Hughes3d792f42019-07-31 14:13:57 -0700664 device_tracker_send(tracker, list_transports(tracker->long_output));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800665 }
666}
667
Josh Gao32124632017-08-14 18:57:54 -0700668asocket* create_device_tracker(bool long_output) {
Josh Gao5cb76ce2018-02-12 17:24:00 -0800669 device_tracker* tracker = new device_tracker();
Elliott Hughese64126b2018-10-19 13:59:44 -0700670 if (tracker == nullptr) LOG(FATAL) << "cannot allocate device tracker";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800671
Josh Gao0d6aa992016-11-22 14:32:34 -0800672 D("device tracker %p created", tracker);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800673
674 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao0d6aa992016-11-22 14:32:34 -0800675 tracker->socket.ready = device_tracker_ready;
676 tracker->socket.close = device_tracker_close;
Josh Gao32124632017-08-14 18:57:54 -0700677 tracker->update_needed = true;
678 tracker->long_output = long_output;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800679
Josh Gao0d6aa992016-11-22 14:32:34 -0800680 tracker->next = device_tracker_list;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800681 device_tracker_list = tracker;
682
683 return &tracker->socket;
684}
685
Josh Gao1e3bf732017-05-03 22:37:10 -0700686// Check if all of the USB transports are connected.
687bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700688 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao1e3bf732017-05-03 22:37:10 -0700689 for (const auto& t : transport_list) {
690 if (!fn(t)) {
691 return false;
692 }
693 }
694 for (const auto& t : pending_list) {
695 if (!fn(t)) {
696 return false;
697 }
698 }
699 return true;
700}
701
Elliott Hughes88b4c852015-04-30 17:32:03 -0700702// Call this function each time the transport list has changed.
703void update_transports() {
Josh Gao1e3bf732017-05-03 22:37:10 -0700704 update_transport_status();
705
706 // Notify `adb track-devices` clients.
Elliott Hughes88b4c852015-04-30 17:32:03 -0700707 device_tracker* tracker = device_tracker_list;
708 while (tracker != nullptr) {
709 device_tracker* next = tracker->next;
710 // This may destroy the tracker if the connection is closed.
Elliott Hughes3d792f42019-07-31 14:13:57 -0700711 device_tracker_send(tracker, list_transports(tracker->long_output));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800712 tracker = next;
713 }
714}
Elliott Hughes88b4c852015-04-30 17:32:03 -0700715
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800716#else
Elliott Hughes88b4c852015-04-30 17:32:03 -0700717
718void update_transports() {
719 // Nothing to do on the device side.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800720}
Elliott Hughes88b4c852015-04-30 17:32:03 -0700721
Josh Gao0d6aa992016-11-22 14:32:34 -0800722#endif // ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800723
Josh Gao0d6aa992016-11-22 14:32:34 -0800724struct tmsg {
725 atransport* transport;
726 int action;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800727};
728
Josh Gao0d6aa992016-11-22 14:32:34 -0800729static int transport_read_action(int fd, struct tmsg* m) {
730 char* p = (char*)m;
731 int len = sizeof(*m);
732 int r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800733
Josh Gao0d6aa992016-11-22 14:32:34 -0800734 while (len > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800735 r = adb_read(fd, p, len);
Josh Gao0d6aa992016-11-22 14:32:34 -0800736 if (r > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800737 len -= r;
Josh Gao0d6aa992016-11-22 14:32:34 -0800738 p += r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800739 } else {
Yabin Cui815ad882015-09-02 17:44:28 -0700740 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800741 return -1;
742 }
743 }
744 return 0;
745}
746
Josh Gao0d6aa992016-11-22 14:32:34 -0800747static int transport_write_action(int fd, struct tmsg* m) {
748 char* p = (char*)m;
749 int len = sizeof(*m);
750 int r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800751
Josh Gao0d6aa992016-11-22 14:32:34 -0800752 while (len > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800753 r = adb_write(fd, p, len);
Josh Gao0d6aa992016-11-22 14:32:34 -0800754 if (r > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800755 len -= r;
Josh Gao0d6aa992016-11-22 14:32:34 -0800756 p += r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800757 } else {
Yabin Cui815ad882015-09-02 17:44:28 -0700758 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800759 return -1;
760 }
761 }
762 return 0;
763}
764
Josh Gao715fe602018-02-16 13:24:58 -0800765static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800766 tmsg m;
Josh Gao0d6aa992016-11-22 14:32:34 -0800767 atransport* t;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800768
Josh Gao0d6aa992016-11-22 14:32:34 -0800769 if (!(ev & FDE_READ)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800770 return;
771 }
772
Josh Gao0d6aa992016-11-22 14:32:34 -0800773 if (transport_read_action(_fd, &m)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700774 PLOG(FATAL) << "cannot read transport registration socket";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800775 }
776
777 t = m.transport;
778
Dan Albertbe8e54b2015-05-18 13:06:53 -0700779 if (m.action == 0) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700780 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800781
Josh Gaoe7daf572016-09-21 12:37:10 -0700782 {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700783 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaoe7daf572016-09-21 12:37:10 -0700784 transport_list.remove(t);
785 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800786
Dan Albertecce5032015-05-18 16:46:31 -0700787 delete t;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800788
789 update_transports();
790 return;
791 }
792
Mike Lockwoode45583f2009-08-08 12:37:44 -0400793 /* don't create transport threads for inaccessible devices */
Yabin Cui3cf1b362017-03-10 16:01:01 -0800794 if (t->GetConnectionState() != kCsNoPerm) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700795 // The connection gets a reference to the atransport. It will release it
796 // upon a read/write error.
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700797 t->connection()->SetTransportName(t->serial_name());
798 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao715fe602018-02-16 13:24:58 -0800799 if (!check_header(p.get(), t)) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700800 D("%s: remote read: bad header", t->serial.c_str());
Josh Gao715fe602018-02-16 13:24:58 -0800801 return false;
802 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800803
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700804 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "from remote", p.get());
Josh Gao715fe602018-02-16 13:24:58 -0800805 apacket* packet = p.release();
Mike Lockwoode45583f2009-08-08 12:37:44 -0400806
Josh Gao715fe602018-02-16 13:24:58 -0800807 // TODO: Does this need to run on the main thread?
808 fdevent_run_on_main_thread([packet, t]() { handle_packet(packet, t); });
809 return true;
810 });
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700811 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Josh Gao3a34bc52018-10-11 16:33:05 -0700812 LOG(INFO) << t->serial_name() << ": connection terminated: " << error;
Josh Gao715fe602018-02-16 13:24:58 -0800813 fdevent_run_on_main_thread([t]() {
814 handle_offline(t);
Josh Gao14ed9f92019-12-09 13:45:31 -0800815 transport_destroy(t);
Josh Gao715fe602018-02-16 13:24:58 -0800816 });
817 });
Mike Lockwoode45583f2009-08-08 12:37:44 -0400818
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700819 t->connection()->Start();
Josh Gao715fe602018-02-16 13:24:58 -0800820#if ADB_HOST
821 send_connect(t);
822#endif
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800823 }
824
Josh Gaoe7daf572016-09-21 12:37:10 -0700825 {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700826 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700827 auto it = std::find(pending_list.begin(), pending_list.end(), t);
828 if (it != pending_list.end()) {
829 pending_list.remove(t);
830 transport_list.push_front(t);
831 }
Josh Gaoe7daf572016-09-21 12:37:10 -0700832 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800833
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800834 update_transports();
835}
836
Josh Gao5c47e9f2018-07-31 18:28:32 -0700837#if ADB_HOST
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700838void init_reconnect_handler(void) {
839 reconnect_handler.Start();
840}
Josh Gao5c47e9f2018-07-31 18:28:32 -0700841#endif
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700842
Josh Gao0d6aa992016-11-22 14:32:34 -0800843void init_transport_registration(void) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800844 int s[2];
845
Josh Gao0d6aa992016-11-22 14:32:34 -0800846 if (adb_socketpair(s)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700847 PLOG(FATAL) << "cannot open transport registration socketpair";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800848 }
Yabin Cui815ad882015-09-02 17:44:28 -0700849 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800850
851 transport_registration_send = s[0];
852 transport_registration_recv = s[1];
853
Josh Gao9528df22018-05-14 11:14:33 -0700854 transport_registration_fde =
Yi Kong86e67182018-07-13 18:15:16 -0700855 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao9528df22018-05-14 11:14:33 -0700856 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao165460f2017-05-09 13:43:35 -0700857}
858
859void kick_all_transports() {
Josh Gao5c47e9f2018-07-31 18:28:32 -0700860#if ADB_HOST
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700861 reconnect_handler.Stop();
Josh Gao5c47e9f2018-07-31 18:28:32 -0700862#endif
Josh Gao165460f2017-05-09 13:43:35 -0700863 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gaoaaa82f72017-08-17 13:50:51 -0700864 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao165460f2017-05-09 13:43:35 -0700865 for (auto t : transport_list) {
866 t->Kick();
867 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800868}
869
Joshua Duong64fab752020-01-21 13:19:42 -0800870void kick_all_tcp_tls_transports() {
871 std::lock_guard<std::recursive_mutex> lock(transport_lock);
872 for (auto t : transport_list) {
873 if (t->IsTcpDevice() && t->use_tls) {
874 t->Kick();
875 }
876 }
877}
878
879#if !ADB_HOST
880void kick_all_transports_by_auth_key(std::string_view auth_key) {
881 std::lock_guard<std::recursive_mutex> lock(transport_lock);
882 for (auto t : transport_list) {
883 if (auth_key == t->auth_key) {
884 t->Kick();
885 }
886 }
887}
888#endif
889
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800890/* the fdevent select pump is single threaded */
Josh Gao3a34bc52018-10-11 16:33:05 -0700891void register_transport(atransport* transport) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800892 tmsg m;
893 m.transport = transport;
894 m.action = 1;
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700895 D("transport: %s registered", transport->serial.c_str());
Josh Gao0d6aa992016-11-22 14:32:34 -0800896 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700897 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800898 }
899}
900
Josh Gao0d6aa992016-11-22 14:32:34 -0800901static void remove_transport(atransport* transport) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800902 tmsg m;
903 m.transport = transport;
904 m.action = 0;
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700905 D("transport: %s removed", transport->serial.c_str());
Josh Gao0d6aa992016-11-22 14:32:34 -0800906 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700907 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800908 }
909}
910
Josh Gao14ed9f92019-12-09 13:45:31 -0800911static void transport_destroy(atransport* t) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700912 check_main_thread();
Yabin Cui4d64fd82015-08-27 12:03:11 -0700913 CHECK(t != nullptr);
Josh Gaoe7daf572016-09-21 12:37:10 -0700914
Josh Gao4d299742017-09-13 13:40:57 -0700915 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao14ed9f92019-12-09 13:45:31 -0800916 LOG(INFO) << "destroying transport " << t->serial_name();
917 t->connection()->Stop();
Josh Gao5c47e9f2018-07-31 18:28:32 -0700918#if ADB_HOST
Josh Gao14ed9f92019-12-09 13:45:31 -0800919 if (t->IsTcpDevice() && !t->kicked()) {
920 D("transport: %s destroy (attempting reconnection)", t->serial.c_str());
Josh Gaoeb656522018-12-04 01:07:50 -0800921
Josh Gao14ed9f92019-12-09 13:45:31 -0800922 // We need to clear the transport's keys, so that on the next connection, it tries
923 // again from the beginning.
924 t->ResetKeys();
925 reconnect_handler.TrackTransport(t);
926 return;
927 }
Josh Gao5c47e9f2018-07-31 18:28:32 -0700928#endif
929
Josh Gao14ed9f92019-12-09 13:45:31 -0800930 D("transport: %s destroy (kicking and closing)", t->serial.c_str());
931 remove_transport(t);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800932}
933
Josh Gao65d18e22020-04-22 20:57:26 -0700934#if ADB_HOST
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700935static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao0d6aa992016-11-22 14:32:34 -0800936 bool sanitize_qual) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700937 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
938 return qual.empty();
Scott Anderson27042382012-05-30 18:11:27 -0700939
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700940 if (qual.empty()) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700941
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700942 const char* ptr = to_test.c_str();
Scott Anderson27042382012-05-30 18:11:27 -0700943 if (prefix) {
944 while (*prefix) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700945 if (*prefix++ != *ptr++) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700946 }
947 }
948
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700949 for (char ch : qual) {
Josh Gao0d6aa992016-11-22 14:32:34 -0800950 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700951 if (ch != *ptr++) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700952 }
953
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700954 /* Everything matched so far. Return true if *ptr is a NUL. */
955 return !*ptr;
Scott Anderson27042382012-05-30 18:11:27 -0700956}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800957
Josh Gaob39e4152017-08-16 16:57:01 -0700958atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
959 bool* is_ambiguous, std::string* error_out,
960 bool accept_any_state) {
Elliott Hughes67943d12015-10-07 14:55:10 -0700961 atransport* result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800962
Josh Gaob39e4152017-08-16 16:57:01 -0700963 if (transport_id != 0) {
964 *error_out =
965 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
966 } else if (serial) {
Elliott Hughes67943d12015-10-07 14:55:10 -0700967 *error_out = android::base::StringPrintf("device '%s' not found", serial);
968 } else if (type == kTransportLocal) {
969 *error_out = "no emulators found";
970 } else if (type == kTransportAny) {
971 *error_out = "no devices/emulators found";
972 } else {
973 *error_out = "no devices found";
974 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800975
Josh Gaoaaa82f72017-08-17 13:50:51 -0700976 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes67943d12015-10-07 14:55:10 -0700977 for (const auto& t : transport_list) {
Yabin Cui3cf1b362017-03-10 16:01:01 -0800978 if (t->GetConnectionState() == kCsNoPerm) {
David Pursell6e5c7eb2015-12-02 15:14:31 -0800979 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwoodadc16b32009-08-08 13:53:16 -0400980 continue;
981 }
Mike Lockwoode45583f2009-08-08 12:37:44 -0400982
Josh Gaob39e4152017-08-16 16:57:01 -0700983 if (transport_id) {
984 if (t->id == transport_id) {
985 result = t;
986 break;
987 }
988 } else if (serial) {
David Pursellc929c6f2016-03-01 08:58:26 -0800989 if (t->MatchesTarget(serial)) {
Scott Anderson27042382012-05-30 18:11:27 -0700990 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700991 *error_out = "more than one device";
Elliott Hughes67943d12015-10-07 14:55:10 -0700992 if (is_ambiguous) *is_ambiguous = true;
993 result = nullptr;
Scott Anderson27042382012-05-30 18:11:27 -0700994 break;
995 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800996 result = t;
Scott Anderson6dfaf4b2012-04-20 11:21:14 -0700997 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800998 } else {
Elliott Hughes3aec2ba2015-05-05 13:10:43 -0700999 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001000 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -07001001 *error_out = "more than one device";
Elliott Hughes67943d12015-10-07 14:55:10 -07001002 if (is_ambiguous) *is_ambiguous = true;
1003 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001004 break;
1005 }
1006 result = t;
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001007 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001008 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -07001009 *error_out = "more than one emulator";
Elliott Hughes67943d12015-10-07 14:55:10 -07001010 if (is_ambiguous) *is_ambiguous = true;
1011 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001012 break;
1013 }
1014 result = t;
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001015 } else if (type == kTransportAny) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001016 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -07001017 *error_out = "more than one device/emulator";
Elliott Hughes67943d12015-10-07 14:55:10 -07001018 if (is_ambiguous) *is_ambiguous = true;
1019 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001020 break;
1021 }
1022 result = t;
1023 }
1024 }
1025 }
Josh Gaoe7daf572016-09-21 12:37:10 -07001026 lock.unlock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001027
Josh Gao7a7c5cb2018-05-04 16:04:49 -07001028 if (result && !accept_any_state) {
1029 // The caller requires an active transport.
1030 // Make sure that we're actually connected.
1031 ConnectionState state = result->GetConnectionState();
1032 switch (state) {
1033 case kCsConnecting:
1034 *error_out = "device still connecting";
1035 result = nullptr;
1036 break;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001037
Josh Gao7a7c5cb2018-05-04 16:04:49 -07001038 case kCsAuthorizing:
1039 *error_out = "device still authorizing";
1040 result = nullptr;
1041 break;
1042
1043 case kCsUnauthorized: {
1044 *error_out = "device unauthorized.\n";
1045 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
1046 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
1047 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
1048 *error_out += "\n";
1049 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
1050 *error_out += "Otherwise check for a confirmation dialog on your device.";
1051 result = nullptr;
1052 break;
1053 }
1054
1055 case kCsOffline:
1056 *error_out = "device offline";
1057 result = nullptr;
1058 break;
1059
1060 default:
1061 break;
1062 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001063 }
1064
1065 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -07001066 *error_out = "success";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001067 }
1068
1069 return result;
1070}
1071
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001072bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
1073 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao8aa57d22019-02-12 13:59:03 -08001074 ScopedLockAssertion assume_locked(mutex_);
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001075 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
1076 return connection_established_ready_;
1077 }) && connection_established_;
1078}
1079
1080void ConnectionWaitable::SetConnectionEstablished(bool success) {
1081 {
1082 std::lock_guard<std::mutex> lock(mutex_);
1083 if (connection_established_ready_) return;
1084 connection_established_ready_ = true;
1085 connection_established_ = success;
1086 D("connection established with %d", success);
1087 }
1088 cv_.notify_one();
1089}
Josh Gao65d18e22020-04-22 20:57:26 -07001090#endif
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001091
1092atransport::~atransport() {
Josh Gao65d18e22020-04-22 20:57:26 -07001093#if ADB_HOST
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001094 // If the connection callback had not been run before, run it now.
1095 SetConnectionEstablished(false);
Josh Gao65d18e22020-04-22 20:57:26 -07001096#endif
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001097}
1098
Yabin Cui3cf1b362017-03-10 16:01:01 -08001099int atransport::Write(apacket* p) {
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -07001100 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cui3cf1b362017-03-10 16:01:01 -08001101}
1102
Josh Gao3a2172b2019-03-28 15:47:44 -07001103void atransport::Reset() {
1104 if (!kicked_.exchange(true)) {
1105 LOG(INFO) << "resetting transport " << this << " " << this->serial;
1106 this->connection()->Reset();
1107 }
1108}
1109
Yabin Cuif2a9f9b2016-04-18 11:22:34 -07001110void atransport::Kick() {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001111 if (!kicked_.exchange(true)) {
Josh Gao3a2172b2019-03-28 15:47:44 -07001112 LOG(INFO) << "kicking transport " << this << " " << this->serial;
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -07001113 this->connection()->Stop();
Yabin Cuif2a9f9b2016-04-18 11:22:34 -07001114 }
1115}
1116
Yabin Cui3cf1b362017-03-10 16:01:01 -08001117ConnectionState atransport::GetConnectionState() const {
1118 return connection_state_;
1119}
1120
1121void atransport::SetConnectionState(ConnectionState state) {
1122 check_main_thread();
1123 connection_state_ = state;
Joshua Duongccde5202021-03-08 15:01:48 -08001124 update_transports();
Yabin Cui3cf1b362017-03-10 16:01:01 -08001125}
1126
Josh Gaof2d6af52021-04-27 20:32:02 -07001127void atransport::SetConnection(std::shared_ptr<Connection> connection) {
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -07001128 std::lock_guard<std::mutex> lock(mutex_);
1129 connection_ = std::shared_ptr<Connection>(std::move(connection));
1130}
1131
Josh Gao3cd03be2018-02-28 14:44:23 -08001132std::string atransport::connection_state_name() const {
Yabin Cui3cf1b362017-03-10 16:01:01 -08001133 ConnectionState state = GetConnectionState();
1134 switch (state) {
Josh Gao0d6aa992016-11-22 14:32:34 -08001135 case kCsOffline:
1136 return "offline";
1137 case kCsBootloader:
1138 return "bootloader";
1139 case kCsDevice:
1140 return "device";
1141 case kCsHost:
1142 return "host";
1143 case kCsRecovery:
1144 return "recovery";
Tao Bao9d6eca52019-04-07 23:24:03 -07001145 case kCsRescue:
1146 return "rescue";
Josh Gao0d6aa992016-11-22 14:32:34 -08001147 case kCsNoPerm:
1148 return UsbNoPermissionsShortHelpText();
1149 case kCsSideload:
1150 return "sideload";
1151 case kCsUnauthorized:
1152 return "unauthorized";
Josh Gao7a7c5cb2018-05-04 16:04:49 -07001153 case kCsAuthorizing:
1154 return "authorizing";
1155 case kCsConnecting:
1156 return "connecting";
Josh Gao0d6aa992016-11-22 14:32:34 -08001157 default:
1158 return "unknown";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001159 }
1160}
1161
Tamas Berghammera1c60c02015-07-13 19:12:28 +01001162void atransport::update_version(int version, size_t payload) {
1163 protocol_version = std::min(version, A_VERSION);
1164 max_payload = std::min(payload, MAX_PAYLOAD);
1165}
1166
1167int atransport::get_protocol_version() const {
1168 return protocol_version;
1169}
1170
Joshua Duong64fab752020-01-21 13:19:42 -08001171int atransport::get_tls_version() const {
1172 return tls_version;
1173}
1174
Tamas Berghammera1c60c02015-07-13 19:12:28 +01001175size_t atransport::get_max_payload() const {
1176 return max_payload;
1177}
1178
Dan Albertbe8e54b2015-05-18 13:06:53 -07001179const FeatureSet& supported_features() {
Yurii Zubrytskyi816c2d22020-03-26 18:19:28 -07001180 static const android::base::NoDestructor<FeatureSet> features([] {
1181 return FeatureSet{
1182 kFeatureShell2,
1183 kFeatureCmd,
1184 kFeatureStat2,
1185 kFeatureLs2,
1186 kFeatureFixedPushMkdir,
1187 kFeatureApex,
1188 kFeatureAbb,
1189 kFeatureFixedPushSymlinkTimestamp,
1190 kFeatureAbbExec,
1191 kFeatureRemountShell,
1192 kFeatureTrackApp,
1193 kFeatureSendRecv2,
1194 kFeatureSendRecv2Brotli,
1195 kFeatureSendRecv2LZ4,
Josh Gaobdebc9b2020-05-27 17:52:52 -07001196 kFeatureSendRecv2Zstd,
Yurii Zubrytskyi816c2d22020-03-26 18:19:28 -07001197 kFeatureSendRecv2DryRunSend,
Joshua Duongf4ba8d72021-01-13 12:18:15 -08001198 kFeatureOpenscreenMdns,
Yurii Zubrytskyi816c2d22020-03-26 18:19:28 -07001199 // Increment ADB_SERVER_VERSION when adding a feature that adbd needs
1200 // to know about. Otherwise, the client can be stuck running an old
1201 // version of the server even after upgrading their copy of adb.
1202 // (http://b/24370690)
1203 };
1204 }());
David Pursella07dbad2015-09-22 10:43:08 -07001205
1206 return *features;
1207}
1208
1209std::string FeatureSetToString(const FeatureSet& features) {
Elliott Hughesc3462f42018-09-05 12:13:11 -07001210 return android::base::Join(features, ',');
David Pursella07dbad2015-09-22 10:43:08 -07001211}
1212
1213FeatureSet StringToFeatureSet(const std::string& features_string) {
David Pursell3d9072b2015-09-25 13:04:21 -07001214 if (features_string.empty()) {
1215 return FeatureSet();
1216 }
1217
Yurii Zubrytskyi816c2d22020-03-26 18:19:28 -07001218 return android::base::Split(features_string, ",");
1219}
1220
1221template <class Range, class Value>
1222static bool contains(const Range& r, const Value& v) {
1223 return std::find(std::begin(r), std::end(r), v) != std::end(r);
Dan Albertbe8e54b2015-05-18 13:06:53 -07001224}
1225
David Pursell22fc5e92015-09-30 13:35:42 -07001226bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Yurii Zubrytskyi816c2d22020-03-26 18:19:28 -07001227 return contains(feature_set, feature) && contains(supported_features(), feature);
David Pursell22fc5e92015-09-30 13:35:42 -07001228}
1229
Dan Albertbe8e54b2015-05-18 13:06:53 -07001230bool atransport::has_feature(const std::string& feature) const {
Yurii Zubrytskyi816c2d22020-03-26 18:19:28 -07001231 return contains(features_, feature);
Dan Albertbe8e54b2015-05-18 13:06:53 -07001232}
1233
David Pursella07dbad2015-09-22 10:43:08 -07001234void atransport::SetFeatures(const std::string& features_string) {
1235 features_ = StringToFeatureSet(features_string);
Dan Albertbe8e54b2015-05-18 13:06:53 -07001236}
1237
Yabin Cui2d4c1982015-08-28 15:09:44 -07001238void atransport::AddDisconnect(adisconnect* disconnect) {
1239 disconnects_.push_back(disconnect);
1240}
1241
1242void atransport::RemoveDisconnect(adisconnect* disconnect) {
1243 disconnects_.remove(disconnect);
1244}
1245
1246void atransport::RunDisconnects() {
Elliott Hughes85952832015-10-07 15:59:35 -07001247 for (const auto& disconnect : disconnects_) {
Yabin Cui2d4c1982015-08-28 15:09:44 -07001248 disconnect->func(disconnect->opaque, this);
1249 }
1250 disconnects_.clear();
1251}
1252
Josh Gao65d18e22020-04-22 20:57:26 -07001253#if ADB_HOST
David Pursellc929c6f2016-03-01 08:58:26 -08001254bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001255 if (!serial.empty()) {
David Pursellc929c6f2016-03-01 08:58:26 -08001256 if (target == serial) {
1257 return true;
1258 } else if (type == kTransportLocal) {
1259 // Local transports can match [tcp:|udp:]<hostname>[:port].
1260 const char* local_target_ptr = target.c_str();
1261
1262 // For fastboot compatibility, ignore protocol prefixes.
1263 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao0d6aa992016-11-22 14:32:34 -08001264 android::base::StartsWith(target, "udp:")) {
David Pursellc929c6f2016-03-01 08:58:26 -08001265 local_target_ptr += 4;
1266 }
1267
1268 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1269 std::string serial_host, error;
1270 int serial_port = -1;
Josh Gao0d6aa992016-11-22 14:32:34 -08001271 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursellc929c6f2016-03-01 08:58:26 -08001272 // |target| may omit the port to default to ours.
1273 std::string target_host;
1274 int target_port = serial_port;
1275 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1276 nullptr, &error) &&
Josh Gao0d6aa992016-11-22 14:32:34 -08001277 serial_host == target_host && serial_port == target_port) {
David Pursellc929c6f2016-03-01 08:58:26 -08001278 return true;
1279 }
1280 }
1281 }
1282 }
1283
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001284 return (target == devpath) || qual_match(target, "product:", product, false) ||
1285 qual_match(target, "model:", model, true) ||
1286 qual_match(target, "device:", device, false);
David Pursellc929c6f2016-03-01 08:58:26 -08001287}
1288
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001289void atransport::SetConnectionEstablished(bool success) {
1290 connection_waitable_->SetConnectionEstablished(success);
1291}
1292
Josh Gaod24580d2018-08-30 11:37:00 -07001293ReconnectResult atransport::Reconnect() {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001294 return reconnect_(this);
1295}
1296
Josh Gaob39e4152017-08-16 16:57:01 -07001297// We use newline as our delimiter, make sure to never output it.
1298static std::string sanitize(std::string str, bool alphanumeric) {
1299 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1300 : [](const char c) { return c == '\n'; };
1301 std::replace_if(str.begin(), str.end(), pred, '_');
1302 return str;
1303}
1304
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001305static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob39e4152017-08-16 16:57:01 -07001306 bool alphanumeric) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001307 if (value.empty()) {
Scott Anderson27042382012-05-30 18:11:27 -07001308 return;
Scott Anderson27042382012-05-30 18:11:27 -07001309 }
1310
Elliott Hughes88b4c852015-04-30 17:32:03 -07001311 *result += ' ';
1312 *result += key;
Josh Gaob39e4152017-08-16 16:57:01 -07001313 *result += sanitize(value, alphanumeric);
Scott Anderson27042382012-05-30 18:11:27 -07001314}
1315
Josh Gao0d6aa992016-11-22 14:32:34 -08001316static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001317 std::string serial = t->serial;
1318 if (serial.empty()) {
Dan Alberta8c34142015-05-06 16:48:52 -07001319 serial = "(no serial number)";
Elliott Hughes88b4c852015-04-30 17:32:03 -07001320 }
Scott Anderson27042382012-05-30 18:11:27 -07001321
1322 if (!long_listing) {
Elliott Hughes88b4c852015-04-30 17:32:03 -07001323 *result += serial;
1324 *result += '\t';
1325 *result += t->connection_state_name();
Scott Anderson27042382012-05-30 18:11:27 -07001326 } else {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001327 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1328 t->connection_state_name().c_str());
Scott Anderson27042382012-05-30 18:11:27 -07001329
Elliott Hughes88b4c852015-04-30 17:32:03 -07001330 append_transport_info(result, "", t->devpath, false);
1331 append_transport_info(result, "product:", t->product, false);
1332 append_transport_info(result, "model:", t->model, true);
1333 append_transport_info(result, "device:", t->device, false);
Josh Gaob39e4152017-08-16 16:57:01 -07001334
1335 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1336 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1337 *result += " transport_id:";
1338 *result += std::to_string(t->id);
Scott Anderson27042382012-05-30 18:11:27 -07001339 }
Elliott Hughes88b4c852015-04-30 17:32:03 -07001340 *result += '\n';
Scott Anderson27042382012-05-30 18:11:27 -07001341}
1342
Elliott Hughes88b4c852015-04-30 17:32:03 -07001343std::string list_transports(bool long_listing) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001344 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov4dd35012017-12-17 10:56:07 +00001345
1346 auto sorted_transport_list = transport_list;
1347 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1348 if (x->type != y->type) {
1349 return x->type < y->type;
1350 }
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001351 return x->serial < y->serial;
Artem Iglikov4dd35012017-12-17 10:56:07 +00001352 });
1353
1354 std::string result;
1355 for (const auto& t : sorted_transport_list) {
Elliott Hughes88b4c852015-04-30 17:32:03 -07001356 append_transport(t, &result, long_listing);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001357 }
Elliott Hughes88b4c852015-04-30 17:32:03 -07001358 return result;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001359}
1360
Josh Gao3a2172b2019-03-28 15:47:44 -07001361void close_usb_devices(std::function<bool(const atransport*)> predicate, bool reset) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001362 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao4e562502016-10-27 14:01:08 -07001363 for (auto& t : transport_list) {
1364 if (predicate(t)) {
Josh Gao3a2172b2019-03-28 15:47:44 -07001365 if (reset) {
1366 t->Reset();
1367 } else {
1368 t->Kick();
1369 }
Josh Gao4e562502016-10-27 14:01:08 -07001370 }
1371 }
1372}
1373
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001374/* hack for osx */
Josh Gao3a2172b2019-03-28 15:47:44 -07001375void close_usb_devices(bool reset) {
1376 close_usb_devices([](const atransport*) { return true; }, reset);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001377}
Josh Gao65d18e22020-04-22 20:57:26 -07001378#endif
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001379
Josh Gao597044d2018-08-08 16:20:14 -07001380bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
Joshua Duong64fab752020-01-21 13:19:42 -08001381 atransport::ReconnectCallback reconnect, bool use_tls, int* error) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001382 atransport* t = new atransport(std::move(reconnect), kCsOffline);
Joshua Duong64fab752020-01-21 13:19:42 -08001383 t->use_tls = use_tls;
David 'Digit' Turner58f59682011-01-06 14:11:07 +01001384
Josh Gaoa3a71472018-08-02 13:58:24 -07001385 D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
Josh Gaofa3107e2018-07-25 17:21:49 -07001386 if (init_socket_transport(t, std::move(s), port, local) < 0) {
Dan Albertecce5032015-05-18 16:46:31 -07001387 delete t;
Josh Gao597044d2018-08-08 16:20:14 -07001388 if (error) *error = errno;
1389 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001390 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001391
Josh Gaoaaa82f72017-08-17 13:50:51 -07001392 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes85952832015-10-07 15:59:35 -07001393 for (const auto& transport : pending_list) {
Josh Gaoa3a71472018-08-02 13:58:24 -07001394 if (serial == transport->serial) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001395 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao0d6aa992016-11-22 14:32:34 -08001396 << " is already in pending_list and fails to register";
Dan Albertecce5032015-05-18 16:46:31 -07001397 delete t;
Josh Gao597044d2018-08-08 16:20:14 -07001398 if (error) *error = EALREADY;
1399 return false;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001400 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001401 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001402
Elliott Hughes85952832015-10-07 15:59:35 -07001403 for (const auto& transport : transport_list) {
Josh Gaoa3a71472018-08-02 13:58:24 -07001404 if (serial == transport->serial) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001405 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao0d6aa992016-11-22 14:32:34 -08001406 << " is already in transport_list and fails to register";
Dan Albertecce5032015-05-18 16:46:31 -07001407 delete t;
Josh Gao597044d2018-08-08 16:20:14 -07001408 if (error) *error = EALREADY;
1409 return false;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001410 }
1411 }
1412
Josh Gaoa3a71472018-08-02 13:58:24 -07001413 t->serial = std::move(serial);
Dan Albertecce5032015-05-18 16:46:31 -07001414 pending_list.push_front(t);
Josh Gaoe7daf572016-09-21 12:37:10 -07001415
1416 lock.unlock();
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001417
Josh Gao65d18e22020-04-22 20:57:26 -07001418#if ADB_HOST
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001419 auto waitable = t->connection_waitable();
Josh Gao65d18e22020-04-22 20:57:26 -07001420#endif
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001421 register_transport(t);
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001422
Luis Hector Chavez25bc41c2018-05-01 17:12:16 -07001423 if (local == 1) {
1424 // Do not wait for emulator transports.
Josh Gao597044d2018-08-08 16:20:14 -07001425 return true;
Luis Hector Chavez25bc41c2018-05-01 17:12:16 -07001426 }
1427
Josh Gao65d18e22020-04-22 20:57:26 -07001428#if ADB_HOST
Josh Gao597044d2018-08-08 16:20:14 -07001429 if (!waitable->WaitForConnection(std::chrono::seconds(10))) {
1430 if (error) *error = ETIMEDOUT;
1431 return false;
1432 }
1433
1434 if (t->GetConnectionState() == kCsUnauthorized) {
1435 if (error) *error = EPERM;
1436 return false;
1437 }
Josh Gao65d18e22020-04-22 20:57:26 -07001438#endif
Josh Gao597044d2018-08-08 16:20:14 -07001439
1440 return true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001441}
1442
Mike Lockwood81ffe172009-10-11 23:04:18 -04001443#if ADB_HOST
Josh Gao0d6aa992016-11-22 14:32:34 -08001444atransport* find_transport(const char* serial) {
Dan Albertecce5032015-05-18 16:46:31 -07001445 atransport* result = nullptr;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001446
Josh Gaoaaa82f72017-08-17 13:50:51 -07001447 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui4d64fd82015-08-27 12:03:11 -07001448 for (auto& t : transport_list) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001449 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertecce5032015-05-18 16:46:31 -07001450 result = t;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001451 break;
1452 }
Dan Albertecce5032015-05-18 16:46:31 -07001453 }
Mike Lockwood81ffe172009-10-11 23:04:18 -04001454
Dan Albertecce5032015-05-18 16:46:31 -07001455 return result;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001456}
1457
Yabin Cui4d64fd82015-08-27 12:03:11 -07001458void kick_all_tcp_devices() {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001459 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui4d64fd82015-08-27 12:03:11 -07001460 for (auto& t : transport_list) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001461 if (t->IsTcpDevice()) {
Yabin Cui4e222292015-08-31 11:50:24 -07001462 // Kicking breaks the read_transport thread of this transport out of any read, then
1463 // the read_transport thread will notify the main thread to make this transport
1464 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cui4d64fd82015-08-27 12:03:11 -07001465 // Finally, this transport will be closed and freed in the main thread.
Yabin Cuif2a9f9b2016-04-18 11:22:34 -07001466 t->Kick();
Mike Lockwood01c2c302010-05-24 10:44:35 -04001467 }
Dan Albertecce5032015-05-18 16:46:31 -07001468 }
Josh Gao13cb8c02018-08-10 14:44:54 -07001469 reconnect_handler.CheckForKicked();
Mike Lockwood01c2c302010-05-24 10:44:35 -04001470}
1471
Josh Gaof2d6af52021-04-27 20:32:02 -07001472void register_usb_transport(std::shared_ptr<Connection> connection, const char* serial,
1473 const char* devpath, unsigned writeable) {
1474 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
1475 if (serial) {
1476 t->serial = serial;
1477 }
1478 if (devpath) {
1479 t->devpath = devpath;
1480 }
1481
1482 t->SetConnection(std::move(connection));
1483 t->type = kTransportUsb;
1484
1485 {
1486 std::lock_guard<std::recursive_mutex> lock(transport_lock);
1487 pending_list.push_front(t);
1488 }
1489
1490 register_transport(t);
1491}
1492
Josh Gao0d6aa992016-11-22 14:32:34 -08001493void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1494 unsigned writeable) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001495 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertecce5032015-05-18 16:46:31 -07001496
Josh Gao0d6aa992016-11-22 14:32:34 -08001497 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cui3cf1b362017-03-10 16:01:01 -08001498 init_usb_transport(t, usb);
Josh Gao0d6aa992016-11-22 14:32:34 -08001499 if (serial) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001500 t->serial = serial;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001501 }
Dan Albertecce5032015-05-18 16:46:31 -07001502
1503 if (devpath) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001504 t->devpath = devpath;
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001505 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001506
Josh Gaoe7daf572016-09-21 12:37:10 -07001507 {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001508 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaoe7daf572016-09-21 12:37:10 -07001509 pending_list.push_front(t);
1510 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001511
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001512 register_transport(t);
1513}
1514
Dan Albert9a50f4c2015-05-18 16:43:57 -07001515// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao0d6aa992016-11-22 14:32:34 -08001516void unregister_usb_transport(usb_handle* usb) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001517 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao395b86a2018-01-28 20:32:46 -08001518 transport_list.remove_if([usb](atransport* t) {
Josh Gao68f2c382018-12-11 13:11:52 -08001519 return t->GetUsbHandle() == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gao395b86a2018-01-28 20:32:46 -08001520 });
Mike Lockwoode45583f2009-08-08 12:37:44 -04001521}
Josh Gao3a34bc52018-10-11 16:33:05 -07001522#endif
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001523
Josh Gao67b683a2017-05-16 15:02:45 -07001524bool check_header(apacket* p, atransport* t) {
Josh Gao0d6aa992016-11-22 14:32:34 -08001525 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cui3cf1b362017-03-10 16:01:01 -08001526 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1527 << ", magic = " << p->msg.magic;
Josh Gao67b683a2017-05-16 15:02:45 -07001528 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001529 }
1530
Josh Gao0d6aa992016-11-22 14:32:34 -08001531 if (p->msg.data_length > t->get_max_payload()) {
1532 VLOG(RWX) << "check_header(): " << p->msg.data_length
1533 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao67b683a2017-05-16 15:02:45 -07001534 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001535 }
1536
Josh Gao67b683a2017-05-16 15:02:45 -07001537 return true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001538}
1539
Josh Gaoeac20582016-10-05 19:02:29 -07001540#if ADB_HOST
Joshua Duong64fab752020-01-21 13:19:42 -08001541std::shared_ptr<RSA> atransport::Key() {
1542 if (keys_.empty()) {
1543 return nullptr;
1544 }
1545
1546 std::shared_ptr<RSA> result = keys_[0];
1547 return result;
1548}
1549
Josh Gao22cb70b2016-08-18 22:00:12 -07001550std::shared_ptr<RSA> atransport::NextKey() {
Josh Gaoeb656522018-12-04 01:07:50 -08001551 if (keys_.empty()) {
1552 LOG(INFO) << "fetching keys for transport " << this->serial_name();
1553 keys_ = adb_auth_get_private_keys();
1554
1555 // We should have gotten at least one key: the one that's automatically generated.
1556 CHECK(!keys_.empty());
Joshua Duong64fab752020-01-21 13:19:42 -08001557 } else {
1558 keys_.pop_front();
Josh Gaoeb656522018-12-04 01:07:50 -08001559 }
Elliott Hughes801066a2016-06-29 17:42:01 -07001560
Josh Gaod60bafd2020-06-11 21:07:27 -07001561 return Key();
Elliott Hughes801066a2016-06-29 17:42:01 -07001562}
Josh Gaoeb656522018-12-04 01:07:50 -08001563
1564void atransport::ResetKeys() {
1565 keys_.clear();
1566}
Josh Gaoeac20582016-10-05 19:02:29 -07001567#endif