blob: ed4a93b5cae6963a93cfa2db71ba4a7b0823271c [file] [log] [blame]
The Android Open Source Projectdd7bc332009-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 Cuiaed3c612015-09-22 15:52:57 -070017#define TRACE_TAG TRANSPORT
Dan Albert76649012015-02-24 15:51:19 -080018
Dan Albert33134262015-03-19 15:21:08 -070019#include "sysdeps.h"
Josh Gao31b5be62018-03-07 16:51:08 -080020
Dan Albert76649012015-02-24 15:51:19 -080021#include "transport.h"
22
Dan Albert055f1aa2015-02-20 17:24:58 -080023#include <ctype.h>
Dan Albert76649012015-02-24 15:51:19 -080024#include <errno.h>
Josh Gaob122b172017-08-16 16:57:01 -070025#include <inttypes.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080026#include <stdio.h>
27#include <stdlib.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080028#include <string.h>
Dan Albert76649012015-02-24 15:51:19 -080029#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080030
Spencer Low363af562015-11-07 18:51:54 -080031#include <algorithm>
Josh Gao0bbf69c2018-02-16 13:24:58 -080032#include <deque>
Dan Albertc7915a32015-05-18 16:46:31 -070033#include <list>
Pirama Arumuga Nainar29e3dd82018-08-08 10:33:24 -070034#include <memory>
Josh Gao0cd3ae12016-09-21 12:37:10 -070035#include <mutex>
Josh Gao8a40c8a2018-08-10 14:28:24 -070036#include <set>
Josh Gaoe1dacfc2017-04-12 17:00:49 -070037#include <thread>
Dan Albertc7915a32015-05-18 16:46:31 -070038
Joshua Duong5cf78682020-01-21 13:19:42 -080039#include <adb/crypto/rsa_2048_key.h>
40#include <adb/crypto/x509_generator.h>
41#include <adb/tls/tls_connection.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080042#include <android-base/logging.h>
David Pursell3f902aa2016-03-01 08:58:26 -080043#include <android-base/parsenetaddress.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080044#include <android-base/stringprintf.h>
45#include <android-base/strings.h>
Josh Gaob122b172017-08-16 16:57:01 -070046#include <android-base/thread_annotations.h>
Elliott Hughese67f1f82015-04-30 17:32:03 -070047
Josh Gao27768452018-01-02 12:01:43 -080048#include <diagnose_usb.h>
49
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080050#include "adb.h"
Elliott Hughes0aeb5052016-06-29 17:42:01 -070051#include "adb_auth.h"
Josh Gaob800d882018-01-28 20:32:46 -080052#include "adb_io.h"
Josh Gaocfe72e22016-11-29 09:40:29 -080053#include "adb_trace.h"
Elliott Hughese67f1f82015-04-30 17:32:03 -070054#include "adb_utils.h"
Josh Gao57e09b12019-06-28 13:50:37 -070055#include "fdevent/fdevent.h"
Josh Gaoe445a6d2018-07-31 14:12:59 -070056#include "sysdeps/chrono.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080057
Joshua Duong5cf78682020-01-21 13:19:42 -080058using namespace adb::crypto;
59using namespace adb::tls;
Josh Gao982f7bd2019-02-12 13:59:03 -080060using android::base::ScopedLockAssertion;
Joshua Duong5cf78682020-01-21 13:19:42 -080061using TlsError = TlsConnection::TlsError;
Josh Gao982f7bd2019-02-12 13:59:03 -080062
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070063static void remove_transport(atransport* transport);
Josh Gao9a8366b2019-12-09 13:45:31 -080064static void transport_destroy(atransport* transport);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080065
Josh Gaob122b172017-08-16 16:57:01 -070066// TODO: unordered_map<TransportId, atransport*>
Josh Gaob7b1edf2015-11-11 17:56:12 -080067static auto& transport_list = *new std::list<atransport*>();
68static auto& pending_list = *new std::list<atransport*>();
Benoit Goby1c45ee92013-03-29 18:22:36 -070069
Josh Gao1db71af2017-08-17 13:50:51 -070070static auto& transport_lock = *new std::recursive_mutex();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080071
Todd Kennedy51c05ec2015-11-10 00:03:25 +000072const char* const kFeatureShell2 = "shell_v2";
73const char* const kFeatureCmd = "cmd";
Josh Gao5a1e3fd2016-12-05 17:11:34 -080074const char* const kFeatureStat2 = "stat_v2";
Josh Gao34a478f2019-08-07 14:23:17 -070075const char* const kFeatureLs2 = "ls_v2";
Josh Gao5d1756c2017-02-22 17:07:01 -080076const char* const kFeatureLibusb = "libusb";
Dan Albert5176df82017-05-23 14:30:00 -070077const char* const kFeaturePushSync = "push_sync";
Dario Freni29814de2018-10-04 16:26:40 +010078const char* const kFeatureApex = "apex";
Josh Gaofb085102018-10-22 13:00:05 -070079const char* const kFeatureFixedPushMkdir = "fixed_push_mkdir";
Alex Buynytskyy01a65ee2019-01-17 13:13:56 -080080const char* const kFeatureAbb = "abb";
Josh Gao7b1cb662019-02-20 13:01:40 -080081const char* const kFeatureFixedPushSymlinkTimestamp = "fixed_push_symlink_timestamp";
Alex Buynytskyy05626c12019-02-21 14:22:51 -080082const char* const kFeatureAbbExec = "abb_exec";
Josh Gao8c2198c2019-07-11 14:15:32 -070083const char* const kFeatureRemountShell = "remount_shell";
Shukang Zhouf4ffae12020-02-13 17:01:39 -080084const char* const kFeatureTrackApp = "track_app";
Josh Gao939fc192020-03-04 19:34:08 -080085const char* const kFeatureSendRecv2 = "sendrecv_v2";
86const char* const kFeatureSendRecv2Brotli = "sendrecv_v2_brotli";
Todd Kennedy51c05ec2015-11-10 00:03:25 +000087
Luis Hector Chavez56fe7532018-04-17 14:25:04 -070088namespace {
89
Josh Gaodef91c02018-07-31 18:28:32 -070090#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070091// Tracks and handles atransport*s that are attempting reconnection.
92class ReconnectHandler {
93 public:
94 ReconnectHandler() = default;
95 ~ReconnectHandler() = default;
96
97 // Starts the ReconnectHandler thread.
98 void Start();
99
100 // Requests the ReconnectHandler thread to stop.
101 void Stop();
102
103 // Adds the atransport* to the queue of reconnect attempts.
104 void TrackTransport(atransport* transport);
105
Josh Gao902dace2018-08-10 14:44:54 -0700106 // Wake up the ReconnectHandler thread to have it check for kicked transports.
107 void CheckForKicked();
108
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700109 private:
110 // The main thread loop.
111 void Run();
112
113 // Tracks a reconnection attempt.
114 struct ReconnectAttempt {
115 atransport* transport;
Josh Gao95af6412018-07-30 18:51:55 -0700116 std::chrono::steady_clock::time_point reconnect_time;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700117 size_t attempts_left;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700118
119 bool operator<(const ReconnectAttempt& rhs) const {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700120 if (reconnect_time == rhs.reconnect_time) {
121 return reinterpret_cast<uintptr_t>(transport) <
122 reinterpret_cast<uintptr_t>(rhs.transport);
123 }
124 return reconnect_time < rhs.reconnect_time;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700125 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700126 };
127
128 // Only retry for up to one minute.
Josh Gaoe445a6d2018-07-31 14:12:59 -0700129 static constexpr const std::chrono::seconds kDefaultTimeout = 10s;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700130 static constexpr const size_t kMaxAttempts = 6;
131
132 // Protects all members.
133 std::mutex reconnect_mutex_;
134 bool running_ GUARDED_BY(reconnect_mutex_) = true;
135 std::thread handler_thread_;
136 std::condition_variable reconnect_cv_;
Josh Gao8a40c8a2018-08-10 14:28:24 -0700137 std::set<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700138
139 DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
140};
141
142void ReconnectHandler::Start() {
143 check_main_thread();
144 handler_thread_ = std::thread(&ReconnectHandler::Run, this);
145}
146
147void ReconnectHandler::Stop() {
148 check_main_thread();
149 {
150 std::lock_guard<std::mutex> lock(reconnect_mutex_);
151 running_ = false;
152 }
153 reconnect_cv_.notify_one();
154 handler_thread_.join();
155
156 // Drain the queue to free all resources.
157 std::lock_guard<std::mutex> lock(reconnect_mutex_);
158 while (!reconnect_queue_.empty()) {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700159 ReconnectAttempt attempt = *reconnect_queue_.begin();
160 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700161 remove_transport(attempt.transport);
162 }
163}
164
165void ReconnectHandler::TrackTransport(atransport* transport) {
166 check_main_thread();
167 {
168 std::lock_guard<std::mutex> lock(reconnect_mutex_);
169 if (!running_) return;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700170 // Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
171 auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
172 reconnect_queue_.emplace(
173 ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700174 }
175 reconnect_cv_.notify_one();
176}
177
Josh Gao902dace2018-08-10 14:44:54 -0700178void ReconnectHandler::CheckForKicked() {
179 reconnect_cv_.notify_one();
180}
181
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700182void ReconnectHandler::Run() {
183 while (true) {
184 ReconnectAttempt attempt;
185 {
186 std::unique_lock<std::mutex> lock(reconnect_mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800187 ScopedLockAssertion assume_lock(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700188
Josh Gao95af6412018-07-30 18:51:55 -0700189 if (!reconnect_queue_.empty()) {
190 // FIXME: libstdc++ (used on Windows) implements condition_variable with
191 // system_clock as its clock, so we're probably hosed if the clock changes,
192 // even if we use steady_clock throughout. This problem goes away once we
193 // switch to libc++.
Josh Gao8a40c8a2018-08-10 14:28:24 -0700194 reconnect_cv_.wait_until(lock, reconnect_queue_.begin()->reconnect_time);
Josh Gao95af6412018-07-30 18:51:55 -0700195 } else {
196 reconnect_cv_.wait(lock);
197 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700198
199 if (!running_) return;
Josh Gao902dace2018-08-10 14:44:54 -0700200
201 // Scan the whole list for kicked transports, so that we immediately handle an explicit
202 // disconnect request.
203 bool kicked = false;
204 for (auto it = reconnect_queue_.begin(); it != reconnect_queue_.end();) {
205 if (it->transport->kicked()) {
206 D("transport %s was kicked. giving up on it.", it->transport->serial.c_str());
207 remove_transport(it->transport);
208 it = reconnect_queue_.erase(it);
209 } else {
210 ++it;
211 }
212 kicked = true;
213 }
214
Josh Gao95af6412018-07-30 18:51:55 -0700215 if (reconnect_queue_.empty()) continue;
216
Josh Gao902dace2018-08-10 14:44:54 -0700217 // Go back to sleep if we either woke up spuriously, or we were woken up to remove
218 // a kicked transport, and the first transport isn't ready for reconnection yet.
Josh Gao95af6412018-07-30 18:51:55 -0700219 auto now = std::chrono::steady_clock::now();
Josh Gao8a40c8a2018-08-10 14:28:24 -0700220 if (reconnect_queue_.begin()->reconnect_time > now) {
Josh Gao95af6412018-07-30 18:51:55 -0700221 continue;
222 }
223
Josh Gao8a40c8a2018-08-10 14:28:24 -0700224 attempt = *reconnect_queue_.begin();
225 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700226 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700227 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700228
Josh Gaofc2e56f2018-08-30 11:37:00 -0700229 switch (attempt.transport->Reconnect()) {
230 case ReconnectResult::Retry: {
231 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
232 if (attempt.attempts_left == 0) {
233 D("transport %s exceeded the number of retry attempts. giving up on it.",
234 attempt.transport->serial.c_str());
235 remove_transport(attempt.transport);
236 continue;
237 }
238
239 std::lock_guard<std::mutex> lock(reconnect_mutex_);
240 reconnect_queue_.emplace(ReconnectAttempt{
241 attempt.transport,
242 std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
243 attempt.attempts_left - 1});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700244 continue;
245 }
246
Josh Gaofc2e56f2018-08-30 11:37:00 -0700247 case ReconnectResult::Success:
248 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
249 register_transport(attempt.transport);
250 continue;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700251
Josh Gaofc2e56f2018-08-30 11:37:00 -0700252 case ReconnectResult::Abort:
253 D("cancelling reconnection attempt to %s.", attempt.transport->serial.c_str());
254 remove_transport(attempt.transport);
255 continue;
256 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700257 }
258}
259
260static auto& reconnect_handler = *new ReconnectHandler();
261
Josh Gaodef91c02018-07-31 18:28:32 -0700262#endif
263
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700264} // namespace
265
Josh Gaob122b172017-08-16 16:57:01 -0700266TransportId NextTransportId() {
267 static std::atomic<TransportId> next(1);
268 return next++;
269}
270
Josh Gao3705b342019-03-28 15:47:44 -0700271void Connection::Reset() {
272 LOG(INFO) << "Connection::Reset(): stopping";
273 Stop();
274}
275
Josh Gao0bbf69c2018-02-16 13:24:58 -0800276BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
277 : underlying_(std::move(connection)) {}
278
279BlockingConnectionAdapter::~BlockingConnectionAdapter() {
280 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
281 Stop();
282}
283
284void BlockingConnectionAdapter::Start() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700285 std::lock_guard<std::mutex> lock(mutex_);
286 if (started_) {
287 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
288 << "): started multiple times";
289 }
290
Joshua Duong5cf78682020-01-21 13:19:42 -0800291 StartReadThread();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800292
293 write_thread_ = std::thread([this]() {
294 LOG(INFO) << this->transport_name_ << ": write thread spawning";
295 while (true) {
296 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800297 ScopedLockAssertion assume_locked(mutex_);
Josh Gaoc251ec52018-04-03 12:55:18 -0700298 cv_.wait(lock, [this]() REQUIRES(mutex_) {
299 return this->stopped_ || !this->write_queue_.empty();
300 });
301
Josh Gao0bbf69c2018-02-16 13:24:58 -0800302 if (this->stopped_) {
303 return;
304 }
305
306 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
307 this->write_queue_.pop_front();
308 lock.unlock();
309
310 if (!this->underlying_->Write(packet.get())) {
311 break;
312 }
313 }
314 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
315 });
Josh Gaoc251ec52018-04-03 12:55:18 -0700316
317 started_ = true;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800318}
319
Joshua Duong5cf78682020-01-21 13:19:42 -0800320void BlockingConnectionAdapter::StartReadThread() {
321 read_thread_ = std::thread([this]() {
322 LOG(INFO) << this->transport_name_ << ": read thread spawning";
323 while (true) {
324 auto packet = std::make_unique<apacket>();
325 if (!underlying_->Read(packet.get())) {
326 PLOG(INFO) << this->transport_name_ << ": read failed";
327 break;
328 }
329
330 bool got_stls_cmd = false;
331 if (packet->msg.command == A_STLS) {
332 got_stls_cmd = true;
333 }
334
335 read_callback_(this, std::move(packet));
336
337 // If we received the STLS packet, we are about to perform the TLS
338 // handshake. So this read thread must stop and resume after the
339 // handshake completes otherwise this will interfere in the process.
340 if (got_stls_cmd) {
341 LOG(INFO) << this->transport_name_
342 << ": Received STLS packet. Stopping read thread.";
343 return;
344 }
345 }
346 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
347 });
348}
349
350bool BlockingConnectionAdapter::DoTlsHandshake(RSA* key, std::string* auth_key) {
351 std::lock_guard<std::mutex> lock(mutex_);
352 if (read_thread_.joinable()) {
353 read_thread_.join();
354 }
355 bool success = this->underlying_->DoTlsHandshake(key, auth_key);
356 StartReadThread();
357 return success;
358}
359
Josh Gao3705b342019-03-28 15:47:44 -0700360void BlockingConnectionAdapter::Reset() {
361 {
362 std::lock_guard<std::mutex> lock(mutex_);
363 if (!started_) {
364 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
365 return;
366 }
367
368 if (stopped_) {
369 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
370 << "): already stopped";
371 return;
372 }
373 }
374
375 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): resetting";
376 this->underlying_->Reset();
377 Stop();
378}
379
Josh Gao0bbf69c2018-02-16 13:24:58 -0800380void BlockingConnectionAdapter::Stop() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700381 {
382 std::lock_guard<std::mutex> lock(mutex_);
383 if (!started_) {
384 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
385 return;
386 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800387
Josh Gaoc251ec52018-04-03 12:55:18 -0700388 if (stopped_) {
389 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
390 << "): already stopped";
391 return;
392 }
393
394 stopped_ = true;
395 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800396
397 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
398
399 this->underlying_->Close();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800400 this->cv_.notify_one();
Josh Gaoc251ec52018-04-03 12:55:18 -0700401
402 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
403 std::thread read_thread;
404 std::thread write_thread;
405
406 {
407 std::lock_guard<std::mutex> lock(mutex_);
408 read_thread = std::move(read_thread_);
409 write_thread = std::move(write_thread_);
410 }
411
412 read_thread.join();
413 write_thread.join();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800414
415 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
416 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
417}
418
419bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
420 {
Josh Gaoc251ec52018-04-03 12:55:18 -0700421 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800422 write_queue_.emplace_back(std::move(packet));
423 }
424
425 cv_.notify_one();
426 return true;
427}
428
Joshua Duong5cf78682020-01-21 13:19:42 -0800429FdConnection::FdConnection(unique_fd fd) : fd_(std::move(fd)) {}
430
431FdConnection::~FdConnection() {}
432
433bool FdConnection::DispatchRead(void* buf, size_t len) {
434 if (tls_ != nullptr) {
435 // The TlsConnection doesn't allow 0 byte reads
436 if (len == 0) {
437 return true;
438 }
439 return tls_->ReadFully(buf, len);
440 }
441
442 return ReadFdExactly(fd_.get(), buf, len);
443}
444
445bool FdConnection::DispatchWrite(void* buf, size_t len) {
446 if (tls_ != nullptr) {
447 // The TlsConnection doesn't allow 0 byte writes
448 if (len == 0) {
449 return true;
450 }
451 return tls_->WriteFully(std::string_view(reinterpret_cast<const char*>(buf), len));
452 }
453
454 return WriteFdExactly(fd_.get(), buf, len);
455}
456
Josh Gaob800d882018-01-28 20:32:46 -0800457bool FdConnection::Read(apacket* packet) {
Joshua Duong5cf78682020-01-21 13:19:42 -0800458 if (!DispatchRead(&packet->msg, sizeof(amessage))) {
Josh Gaob800d882018-01-28 20:32:46 -0800459 D("remote local: read terminated (message)");
460 return false;
461 }
462
Josh Gaof571fcb2018-02-05 18:49:10 -0800463 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gao5caaebd2018-02-02 14:38:04 -0800464 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
465 return false;
466 }
467
Josh Gaof571fcb2018-02-05 18:49:10 -0800468 packet->payload.resize(packet->msg.data_length);
469
Joshua Duong5cf78682020-01-21 13:19:42 -0800470 if (!DispatchRead(&packet->payload[0], packet->payload.size())) {
Josh Gaob800d882018-01-28 20:32:46 -0800471 D("remote local: terminated (data)");
472 return false;
473 }
474
475 return true;
476}
477
478bool FdConnection::Write(apacket* packet) {
Joshua Duong5cf78682020-01-21 13:19:42 -0800479 if (!DispatchWrite(&packet->msg, sizeof(packet->msg))) {
Josh Gaob800d882018-01-28 20:32:46 -0800480 D("remote local: write terminated");
481 return false;
482 }
483
Josh Gaof571fcb2018-02-05 18:49:10 -0800484 if (packet->msg.data_length) {
Joshua Duong5cf78682020-01-21 13:19:42 -0800485 if (!DispatchWrite(&packet->payload[0], packet->msg.data_length)) {
Josh Gaof571fcb2018-02-05 18:49:10 -0800486 D("remote local: write terminated");
487 return false;
488 }
489 }
490
Josh Gaob800d882018-01-28 20:32:46 -0800491 return true;
492}
493
Joshua Duong5cf78682020-01-21 13:19:42 -0800494bool FdConnection::DoTlsHandshake(RSA* key, std::string* auth_key) {
495 bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
496 if (!EVP_PKEY_set1_RSA(evp_pkey.get(), key)) {
497 LOG(ERROR) << "EVP_PKEY_set1_RSA failed";
498 return false;
499 }
500 auto x509 = GenerateX509Certificate(evp_pkey.get());
501 auto x509_str = X509ToPEMString(x509.get());
502 auto evp_str = Key::ToPEMString(evp_pkey.get());
Joshua Duong1b273ed2020-03-24 09:50:59 -0700503#ifdef _WIN32
504 int osh = cast_handle_to_int(adb_get_os_handle(fd_));
505#else
506 int osh = adb_get_os_handle(fd_);
507#endif
508
Joshua Duong5cf78682020-01-21 13:19:42 -0800509#if ADB_HOST
510 tls_ = TlsConnection::Create(TlsConnection::Role::Client,
511#else
512 tls_ = TlsConnection::Create(TlsConnection::Role::Server,
513#endif
Joshua Duong1b273ed2020-03-24 09:50:59 -0700514 x509_str, evp_str, osh);
Joshua Duong5cf78682020-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 Gaob800d882018-01-28 20:32:46 -0800545void FdConnection::Close() {
546 adb_shutdown(fd_.get());
547 fd_.reset();
548}
549
Josh Gao06d61d42016-10-06 13:31:44 -0700550void send_packet(apacket* p, atransport* t) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800551 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayde471942017-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 Projectdd7bc332009-03-03 19:32:55 -0800558
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700559 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800560
Yi Kongaed415c2018-07-13 18:15:16 -0700561 if (t == nullptr) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700562 LOG(FATAL) << "Transport is null";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800563 }
564
Josh Gao0bbf69c2018-02-16 13:24:58 -0800565 if (t->Write(p) != 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700566 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800567 t->Kick();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800568 }
569}
570
Josh Gao3705b342019-03-28 15:47:44 -0700571void kick_transport(atransport* t, bool reset) {
Josh Gao1db71af2017-08-17 13:50:51 -0700572 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui1f4ec192016-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 Gaob122b172017-08-16 16:57:01 -0700575 //
576 // TODO(jmgao): WTF? Is this actually true?
Yabin Cui1f4ec192016-04-05 13:50:44 -0700577 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Josh Gao3705b342019-03-28 15:47:44 -0700578 if (reset) {
579 t->Reset();
580 } else {
581 t->Kick();
582 }
Yabin Cui1f4ec192016-04-05 13:50:44 -0700583 }
Josh Gao902dace2018-08-10 14:44:54 -0700584
585#if ADB_HOST
586 reconnect_handler.CheckForKicked();
587#endif
Yabin Cuif4b99282015-08-27 12:03:11 -0700588}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800589
590static int transport_registration_send = -1;
591static int transport_registration_recv = -1;
Josh Gao71f775a2018-05-14 11:14:33 -0700592static fdevent* transport_registration_fde;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800593
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800594#if ADB_HOST
The Android Open Source Projectdd7bc332009-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 Projectdd7bc332009-03-03 19:32:55 -0800601struct device_tracker {
Josh Gao1290fbf2016-11-22 14:32:34 -0800602 asocket socket;
Josh Gaoe0361d12018-02-12 17:24:00 -0800603 bool update_needed = false;
604 bool long_output = false;
605 device_tracker* next = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800606};
607
608/* linked list of all device trackers */
Josh Gao1290fbf2016-11-22 14:32:34 -0800609static device_tracker* device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800610
Josh Gao1290fbf2016-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 Projectdd7bc332009-03-03 19:32:55 -0800614
Josh Gao1db71af2017-08-17 13:50:51 -0700615 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800616 while (node) {
617 if (node == tracker) {
618 *pnode = node->next;
619 break;
620 }
621 pnode = &node->next;
Josh Gao1290fbf2016-11-22 14:32:34 -0800622 node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800623 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800624}
625
Josh Gao1290fbf2016-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 Projectdd7bc332009-03-03 19:32:55 -0800629
Josh Gao1290fbf2016-11-22 14:32:34 -0800630 D("device tracker %p removed", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800631 if (peer) {
Yi Kongaed415c2018-07-13 18:15:16 -0700632 peer->peer = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800633 peer->close(peer);
634 }
635 device_tracker_remove(tracker);
Josh Gaoe0361d12018-02-12 17:24:00 -0800636 delete tracker;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800637}
638
Josh Gao1ce99572018-03-07 16:52:28 -0800639static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800640 /* you can't read from a device tracker, close immediately */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800641 device_tracker_close(socket);
642 return -1;
643}
644
Elliott Hughese67f1f82015-04-30 17:32:03 -0700645static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700646 asocket* peer = tracker->socket.peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800647
Josh Gao1ce99572018-03-07 16:52:28 -0800648 apacket::payload_type data;
Josh Gao27cb7dc2018-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 Projectdd7bc332009-03-03 19:32:55 -0800655}
656
Elliott Hughese67f1f82015-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 Projectdd7bc332009-03-03 19:32:55 -0800659
Elliott Hughese67f1f82015-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 Gaob0c18022017-08-14 18:57:54 -0700662 if (tracker->update_needed) {
663 tracker->update_needed = false;
Elliott Hughesfc2f5f62019-07-31 14:13:57 -0700664 device_tracker_send(tracker, list_transports(tracker->long_output));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800665 }
666}
667
Josh Gaob0c18022017-08-14 18:57:54 -0700668asocket* create_device_tracker(bool long_output) {
Josh Gaoe0361d12018-02-12 17:24:00 -0800669 device_tracker* tracker = new device_tracker();
Elliott Hughes4679a392018-10-19 13:59:44 -0700670 if (tracker == nullptr) LOG(FATAL) << "cannot allocate device tracker";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800671
Josh Gao1290fbf2016-11-22 14:32:34 -0800672 D("device tracker %p created", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800673
674 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao1290fbf2016-11-22 14:32:34 -0800675 tracker->socket.ready = device_tracker_ready;
676 tracker->socket.close = device_tracker_close;
Josh Gaob0c18022017-08-14 18:57:54 -0700677 tracker->update_needed = true;
678 tracker->long_output = long_output;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800679
Josh Gao1290fbf2016-11-22 14:32:34 -0800680 tracker->next = device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800681 device_tracker_list = tracker;
682
683 return &tracker->socket;
684}
685
Josh Gaofd713e52017-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 Gao1db71af2017-08-17 13:50:51 -0700688 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaofd713e52017-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 Hughese67f1f82015-04-30 17:32:03 -0700702// Call this function each time the transport list has changed.
703void update_transports() {
Josh Gaofd713e52017-05-03 22:37:10 -0700704 update_transport_status();
705
706 // Notify `adb track-devices` clients.
Elliott Hughese67f1f82015-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 Hughesfc2f5f62019-07-31 14:13:57 -0700711 device_tracker_send(tracker, list_transports(tracker->long_output));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800712 tracker = next;
713 }
714}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700715
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800716#else
Elliott Hughese67f1f82015-04-30 17:32:03 -0700717
718void update_transports() {
719 // Nothing to do on the device side.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800720}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700721
Josh Gao1290fbf2016-11-22 14:32:34 -0800722#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800723
Josh Gao1290fbf2016-11-22 14:32:34 -0800724struct tmsg {
725 atransport* transport;
726 int action;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800727};
728
Josh Gao1290fbf2016-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 Projectdd7bc332009-03-03 19:32:55 -0800733
Josh Gao1290fbf2016-11-22 14:32:34 -0800734 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800735 r = adb_read(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800736 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800737 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800738 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800739 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700740 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800741 return -1;
742 }
743 }
744 return 0;
745}
746
Josh Gao1290fbf2016-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 Projectdd7bc332009-03-03 19:32:55 -0800751
Josh Gao1290fbf2016-11-22 14:32:34 -0800752 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800753 r = adb_write(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800754 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800755 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800756 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800757 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700758 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800759 return -1;
760 }
761 }
762 return 0;
763}
764
Josh Gao0bbf69c2018-02-16 13:24:58 -0800765static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800766 tmsg m;
Josh Gao1290fbf2016-11-22 14:32:34 -0800767 atransport* t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800768
Josh Gao1290fbf2016-11-22 14:32:34 -0800769 if (!(ev & FDE_READ)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800770 return;
771 }
772
Josh Gao1290fbf2016-11-22 14:32:34 -0800773 if (transport_read_action(_fd, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700774 PLOG(FATAL) << "cannot read transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800775 }
776
777 t = m.transport;
778
Dan Albert1792c232015-05-18 13:06:53 -0700779 if (m.action == 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700780 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800781
Josh Gao0cd3ae12016-09-21 12:37:10 -0700782 {
Josh Gao1db71af2017-08-17 13:50:51 -0700783 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700784 transport_list.remove(t);
785 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800786
Dan Albertc7915a32015-05-18 16:46:31 -0700787 delete t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800788
789 update_transports();
790 return;
791 }
792
Mike Lockwood0927bf92009-08-08 12:37:44 -0400793 /* don't create transport threads for inaccessible devices */
Yabin Cuib5e11412017-03-10 16:01:01 -0800794 if (t->GetConnectionState() != kCsNoPerm) {
Luis Hector Chavez454bc7c2018-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 Chavez9a388d52018-04-25 08:56:41 -0700797 t->connection()->SetTransportName(t->serial_name());
798 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao0bbf69c2018-02-16 13:24:58 -0800799 if (!check_header(p.get(), t)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700800 D("%s: remote read: bad header", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800801 return false;
802 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800803
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700804 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "from remote", p.get());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800805 apacket* packet = p.release();
Mike Lockwood0927bf92009-08-08 12:37:44 -0400806
Josh Gao0bbf69c2018-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 Chavez9a388d52018-04-25 08:56:41 -0700811 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700812 LOG(INFO) << t->serial_name() << ": connection terminated: " << error;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800813 fdevent_run_on_main_thread([t]() {
814 handle_offline(t);
Josh Gao9a8366b2019-12-09 13:45:31 -0800815 transport_destroy(t);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800816 });
817 });
Mike Lockwood0927bf92009-08-08 12:37:44 -0400818
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700819 t->connection()->Start();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800820#if ADB_HOST
821 send_connect(t);
822#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800823 }
824
Josh Gao0cd3ae12016-09-21 12:37:10 -0700825 {
Josh Gao1db71af2017-08-17 13:50:51 -0700826 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez454bc7c2018-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 Gao0cd3ae12016-09-21 12:37:10 -0700832 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800833
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800834 update_transports();
835}
836
Josh Gaodef91c02018-07-31 18:28:32 -0700837#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700838void init_reconnect_handler(void) {
839 reconnect_handler.Start();
840}
Josh Gaodef91c02018-07-31 18:28:32 -0700841#endif
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700842
Josh Gao1290fbf2016-11-22 14:32:34 -0800843void init_transport_registration(void) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800844 int s[2];
845
Josh Gao1290fbf2016-11-22 14:32:34 -0800846 if (adb_socketpair(s)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700847 PLOG(FATAL) << "cannot open transport registration socketpair";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800848 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700849 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800850
851 transport_registration_send = s[0];
852 transport_registration_recv = s[1];
853
Josh Gao71f775a2018-05-14 11:14:33 -0700854 transport_registration_fde =
Yi Kongaed415c2018-07-13 18:15:16 -0700855 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao71f775a2018-05-14 11:14:33 -0700856 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao01b7bc42017-05-09 13:43:35 -0700857}
858
859void kick_all_transports() {
Josh Gaodef91c02018-07-31 18:28:32 -0700860#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700861 reconnect_handler.Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700862#endif
Josh Gao01b7bc42017-05-09 13:43:35 -0700863 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gao1db71af2017-08-17 13:50:51 -0700864 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao01b7bc42017-05-09 13:43:35 -0700865 for (auto t : transport_list) {
866 t->Kick();
867 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800868}
869
Joshua Duong5cf78682020-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 Projectdd7bc332009-03-03 19:32:55 -0800890/* the fdevent select pump is single threaded */
Josh Gaoc51726c2018-10-11 16:33:05 -0700891void register_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800892 tmsg m;
893 m.transport = transport;
894 m.action = 1;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700895 D("transport: %s registered", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800896 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700897 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800898 }
899}
900
Josh Gao1290fbf2016-11-22 14:32:34 -0800901static void remove_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800902 tmsg m;
903 m.transport = transport;
904 m.action = 0;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700905 D("transport: %s removed", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800906 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700907 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800908 }
909}
910
Josh Gao9a8366b2019-12-09 13:45:31 -0800911static void transport_destroy(atransport* t) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700912 check_main_thread();
Yabin Cuif4b99282015-08-27 12:03:11 -0700913 CHECK(t != nullptr);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700914
Josh Gaoe48ecce2017-09-13 13:40:57 -0700915 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao9a8366b2019-12-09 13:45:31 -0800916 LOG(INFO) << "destroying transport " << t->serial_name();
917 t->connection()->Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700918#if ADB_HOST
Josh Gao9a8366b2019-12-09 13:45:31 -0800919 if (t->IsTcpDevice() && !t->kicked()) {
920 D("transport: %s destroy (attempting reconnection)", t->serial.c_str());
Josh Gao4414e4c2018-12-04 01:07:50 -0800921
Josh Gao9a8366b2019-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 Gaodef91c02018-07-31 18:28:32 -0700928#endif
929
Josh Gao9a8366b2019-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 Projectdd7bc332009-03-03 19:32:55 -0800932}
933
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700934static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao1290fbf2016-11-22 14:32:34 -0800935 bool sanitize_qual) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700936 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
937 return qual.empty();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700938
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700939 if (qual.empty()) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700940
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700941 const char* ptr = to_test.c_str();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700942 if (prefix) {
943 while (*prefix) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700944 if (*prefix++ != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700945 }
946 }
947
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700948 for (char ch : qual) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800949 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700950 if (ch != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700951 }
952
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700953 /* Everything matched so far. Return true if *ptr is a NUL. */
954 return !*ptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700955}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800956
Josh Gaob122b172017-08-16 16:57:01 -0700957atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
958 bool* is_ambiguous, std::string* error_out,
959 bool accept_any_state) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700960 atransport* result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800961
Josh Gaob122b172017-08-16 16:57:01 -0700962 if (transport_id != 0) {
963 *error_out =
964 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
965 } else if (serial) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700966 *error_out = android::base::StringPrintf("device '%s' not found", serial);
967 } else if (type == kTransportLocal) {
968 *error_out = "no emulators found";
969 } else if (type == kTransportAny) {
970 *error_out = "no devices/emulators found";
971 } else {
972 *error_out = "no devices found";
973 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800974
Josh Gao1db71af2017-08-17 13:50:51 -0700975 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes8d28e192015-10-07 14:55:10 -0700976 for (const auto& t : transport_list) {
Yabin Cuib5e11412017-03-10 16:01:01 -0800977 if (t->GetConnectionState() == kCsNoPerm) {
David Purselld2acbd12015-12-02 15:14:31 -0800978 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwood37d31112009-08-08 13:53:16 -0400979 continue;
980 }
Mike Lockwood0927bf92009-08-08 12:37:44 -0400981
Josh Gaob122b172017-08-16 16:57:01 -0700982 if (transport_id) {
983 if (t->id == transport_id) {
984 result = t;
985 break;
986 }
987 } else if (serial) {
David Pursell3f902aa2016-03-01 08:58:26 -0800988 if (t->MatchesTarget(serial)) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700989 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700990 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700991 if (is_ambiguous) *is_ambiguous = true;
992 result = nullptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700993 break;
994 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800995 result = t;
Scott Andersone109d262012-04-20 11:21:14 -0700996 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800997 } else {
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700998 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800999 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -07001000 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -07001001 if (is_ambiguous) *is_ambiguous = true;
1002 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001003 break;
1004 }
1005 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001006 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001007 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -07001008 *error_out = "more than one emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -07001009 if (is_ambiguous) *is_ambiguous = true;
1010 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001011 break;
1012 }
1013 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001014 } else if (type == kTransportAny) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001015 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -07001016 *error_out = "more than one device/emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -07001017 if (is_ambiguous) *is_ambiguous = true;
1018 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001019 break;
1020 }
1021 result = t;
1022 }
1023 }
1024 }
Josh Gao0cd3ae12016-09-21 12:37:10 -07001025 lock.unlock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001026
Josh Gao704494b2018-05-04 16:04:49 -07001027 if (result && !accept_any_state) {
1028 // The caller requires an active transport.
1029 // Make sure that we're actually connected.
1030 ConnectionState state = result->GetConnectionState();
1031 switch (state) {
1032 case kCsConnecting:
1033 *error_out = "device still connecting";
1034 result = nullptr;
1035 break;
Benoit Goby77e8e582013-01-15 12:36:47 -08001036
Josh Gao704494b2018-05-04 16:04:49 -07001037 case kCsAuthorizing:
1038 *error_out = "device still authorizing";
1039 result = nullptr;
1040 break;
1041
1042 case kCsUnauthorized: {
1043 *error_out = "device unauthorized.\n";
1044 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
1045 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
1046 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
1047 *error_out += "\n";
1048 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
1049 *error_out += "Otherwise check for a confirmation dialog on your device.";
1050 result = nullptr;
1051 break;
1052 }
1053
1054 case kCsOffline:
1055 *error_out = "device offline";
1056 result = nullptr;
1057 break;
1058
1059 default:
1060 break;
1061 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001062 }
1063
1064 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -07001065 *error_out = "success";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001066 }
1067
1068 return result;
1069}
1070
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001071bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
1072 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -08001073 ScopedLockAssertion assume_locked(mutex_);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001074 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
1075 return connection_established_ready_;
1076 }) && connection_established_;
1077}
1078
1079void ConnectionWaitable::SetConnectionEstablished(bool success) {
1080 {
1081 std::lock_guard<std::mutex> lock(mutex_);
1082 if (connection_established_ready_) return;
1083 connection_established_ready_ = true;
1084 connection_established_ = success;
1085 D("connection established with %d", success);
1086 }
1087 cv_.notify_one();
1088}
1089
1090atransport::~atransport() {
1091 // If the connection callback had not been run before, run it now.
1092 SetConnectionEstablished(false);
1093}
1094
Yabin Cuib5e11412017-03-10 16:01:01 -08001095int atransport::Write(apacket* p) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -07001096 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cuib5e11412017-03-10 16:01:01 -08001097}
1098
Josh Gao3705b342019-03-28 15:47:44 -07001099void atransport::Reset() {
1100 if (!kicked_.exchange(true)) {
1101 LOG(INFO) << "resetting transport " << this << " " << this->serial;
1102 this->connection()->Reset();
1103 }
1104}
1105
Yabin Cui7f274902016-04-18 11:22:34 -07001106void atransport::Kick() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001107 if (!kicked_.exchange(true)) {
Josh Gao3705b342019-03-28 15:47:44 -07001108 LOG(INFO) << "kicking transport " << this << " " << this->serial;
Luis Hector Chavez9a388d52018-04-25 08:56:41 -07001109 this->connection()->Stop();
Yabin Cui7f274902016-04-18 11:22:34 -07001110 }
1111}
1112
Yabin Cuib5e11412017-03-10 16:01:01 -08001113ConnectionState atransport::GetConnectionState() const {
1114 return connection_state_;
1115}
1116
1117void atransport::SetConnectionState(ConnectionState state) {
1118 check_main_thread();
1119 connection_state_ = state;
1120}
1121
Luis Hector Chavez9a388d52018-04-25 08:56:41 -07001122void atransport::SetConnection(std::unique_ptr<Connection> connection) {
1123 std::lock_guard<std::mutex> lock(mutex_);
1124 connection_ = std::shared_ptr<Connection>(std::move(connection));
1125}
1126
Josh Gaoffbd3362018-02-28 14:44:23 -08001127std::string atransport::connection_state_name() const {
Yabin Cuib5e11412017-03-10 16:01:01 -08001128 ConnectionState state = GetConnectionState();
1129 switch (state) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001130 case kCsOffline:
1131 return "offline";
1132 case kCsBootloader:
1133 return "bootloader";
1134 case kCsDevice:
1135 return "device";
1136 case kCsHost:
1137 return "host";
1138 case kCsRecovery:
1139 return "recovery";
Tao Bao55d407e2019-04-07 23:24:03 -07001140 case kCsRescue:
1141 return "rescue";
Josh Gao1290fbf2016-11-22 14:32:34 -08001142 case kCsNoPerm:
1143 return UsbNoPermissionsShortHelpText();
1144 case kCsSideload:
1145 return "sideload";
1146 case kCsUnauthorized:
1147 return "unauthorized";
Josh Gao704494b2018-05-04 16:04:49 -07001148 case kCsAuthorizing:
1149 return "authorizing";
1150 case kCsConnecting:
1151 return "connecting";
Josh Gao1290fbf2016-11-22 14:32:34 -08001152 default:
1153 return "unknown";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001154 }
1155}
1156
Tamas Berghammer3d2904c2015-07-13 19:12:28 +01001157void atransport::update_version(int version, size_t payload) {
1158 protocol_version = std::min(version, A_VERSION);
1159 max_payload = std::min(payload, MAX_PAYLOAD);
1160}
1161
1162int atransport::get_protocol_version() const {
1163 return protocol_version;
1164}
1165
Joshua Duong5cf78682020-01-21 13:19:42 -08001166int atransport::get_tls_version() const {
1167 return tls_version;
1168}
1169
Tamas Berghammer3d2904c2015-07-13 19:12:28 +01001170size_t atransport::get_max_payload() const {
1171 return max_payload;
1172}
1173
Dan Albert1792c232015-05-18 13:06:53 -07001174const FeatureSet& supported_features() {
David Pursell4e2fd362015-09-22 10:43:08 -07001175 // Local static allocation to avoid global non-POD variables.
1176 static const FeatureSet* features = new FeatureSet{
Josh Gao7b1cb662019-02-20 13:01:40 -08001177 kFeatureShell2,
1178 kFeatureCmd,
1179 kFeatureStat2,
Josh Gao34a478f2019-08-07 14:23:17 -07001180 kFeatureLs2,
Josh Gao7b1cb662019-02-20 13:01:40 -08001181 kFeatureFixedPushMkdir,
1182 kFeatureApex,
1183 kFeatureAbb,
1184 kFeatureFixedPushSymlinkTimestamp,
Alex Buynytskyy05626c12019-02-21 14:22:51 -08001185 kFeatureAbbExec,
Josh Gao8c2198c2019-07-11 14:15:32 -07001186 kFeatureRemountShell,
Shukang Zhouf4ffae12020-02-13 17:01:39 -08001187 kFeatureTrackApp,
Josh Gao939fc192020-03-04 19:34:08 -08001188 kFeatureSendRecv2,
1189 kFeatureSendRecv2Brotli,
Josh Gao919b70c2018-11-08 22:39:43 -08001190 // Increment ADB_SERVER_VERSION when adding a feature that adbd needs
1191 // to know about. Otherwise, the client can be stuck running an old
1192 // version of the server even after upgrading their copy of adb.
1193 // (http://b/24370690)
David Pursell4e2fd362015-09-22 10:43:08 -07001194 };
1195
1196 return *features;
1197}
1198
1199std::string FeatureSetToString(const FeatureSet& features) {
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001200 return android::base::Join(features, ',');
David Pursell4e2fd362015-09-22 10:43:08 -07001201}
1202
1203FeatureSet StringToFeatureSet(const std::string& features_string) {
David Purselld2b588e2015-09-25 13:04:21 -07001204 if (features_string.empty()) {
1205 return FeatureSet();
1206 }
1207
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001208 auto names = android::base::Split(features_string, ",");
David Pursell4e2fd362015-09-22 10:43:08 -07001209 return FeatureSet(names.begin(), names.end());
Dan Albert1792c232015-05-18 13:06:53 -07001210}
1211
David Pursell70ef7b42015-09-30 13:35:42 -07001212bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001213 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell70ef7b42015-09-30 13:35:42 -07001214}
1215
Dan Albert1792c232015-05-18 13:06:53 -07001216bool atransport::has_feature(const std::string& feature) const {
1217 return features_.count(feature) > 0;
1218}
1219
David Pursell4e2fd362015-09-22 10:43:08 -07001220void atransport::SetFeatures(const std::string& features_string) {
1221 features_ = StringToFeatureSet(features_string);
Dan Albert1792c232015-05-18 13:06:53 -07001222}
1223
Yabin Cuib3298242015-08-28 15:09:44 -07001224void atransport::AddDisconnect(adisconnect* disconnect) {
1225 disconnects_.push_back(disconnect);
1226}
1227
1228void atransport::RemoveDisconnect(adisconnect* disconnect) {
1229 disconnects_.remove(disconnect);
1230}
1231
1232void atransport::RunDisconnects() {
Elliott Hughes65fe2512015-10-07 15:59:35 -07001233 for (const auto& disconnect : disconnects_) {
Yabin Cuib3298242015-08-28 15:09:44 -07001234 disconnect->func(disconnect->opaque, this);
1235 }
1236 disconnects_.clear();
1237}
1238
David Pursell3f902aa2016-03-01 08:58:26 -08001239bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001240 if (!serial.empty()) {
David Pursell3f902aa2016-03-01 08:58:26 -08001241 if (target == serial) {
1242 return true;
1243 } else if (type == kTransportLocal) {
1244 // Local transports can match [tcp:|udp:]<hostname>[:port].
1245 const char* local_target_ptr = target.c_str();
1246
1247 // For fastboot compatibility, ignore protocol prefixes.
1248 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao1290fbf2016-11-22 14:32:34 -08001249 android::base::StartsWith(target, "udp:")) {
David Pursell3f902aa2016-03-01 08:58:26 -08001250 local_target_ptr += 4;
1251 }
1252
1253 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1254 std::string serial_host, error;
1255 int serial_port = -1;
Josh Gao1290fbf2016-11-22 14:32:34 -08001256 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursell3f902aa2016-03-01 08:58:26 -08001257 // |target| may omit the port to default to ours.
1258 std::string target_host;
1259 int target_port = serial_port;
1260 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1261 nullptr, &error) &&
Josh Gao1290fbf2016-11-22 14:32:34 -08001262 serial_host == target_host && serial_port == target_port) {
David Pursell3f902aa2016-03-01 08:58:26 -08001263 return true;
1264 }
1265 }
1266 }
1267 }
1268
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001269 return (target == devpath) || qual_match(target, "product:", product, false) ||
1270 qual_match(target, "model:", model, true) ||
1271 qual_match(target, "device:", device, false);
David Pursell3f902aa2016-03-01 08:58:26 -08001272}
1273
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001274void atransport::SetConnectionEstablished(bool success) {
1275 connection_waitable_->SetConnectionEstablished(success);
1276}
1277
Josh Gaofc2e56f2018-08-30 11:37:00 -07001278ReconnectResult atransport::Reconnect() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001279 return reconnect_(this);
1280}
1281
Elliott Hughese67f1f82015-04-30 17:32:03 -07001282#if ADB_HOST
1283
Josh Gaob122b172017-08-16 16:57:01 -07001284// We use newline as our delimiter, make sure to never output it.
1285static std::string sanitize(std::string str, bool alphanumeric) {
1286 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1287 : [](const char c) { return c == '\n'; };
1288 std::replace_if(str.begin(), str.end(), pred, '_');
1289 return str;
1290}
1291
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001292static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob122b172017-08-16 16:57:01 -07001293 bool alphanumeric) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001294 if (value.empty()) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001295 return;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001296 }
1297
Elliott Hughese67f1f82015-04-30 17:32:03 -07001298 *result += ' ';
1299 *result += key;
Josh Gaob122b172017-08-16 16:57:01 -07001300 *result += sanitize(value, alphanumeric);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001301}
1302
Josh Gao1290fbf2016-11-22 14:32:34 -08001303static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001304 std::string serial = t->serial;
1305 if (serial.empty()) {
Dan Albertd99d9022015-05-06 16:48:52 -07001306 serial = "(no serial number)";
Elliott Hughese67f1f82015-04-30 17:32:03 -07001307 }
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001308
1309 if (!long_listing) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001310 *result += serial;
1311 *result += '\t';
1312 *result += t->connection_state_name();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001313 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001314 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1315 t->connection_state_name().c_str());
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001316
Elliott Hughese67f1f82015-04-30 17:32:03 -07001317 append_transport_info(result, "", t->devpath, false);
1318 append_transport_info(result, "product:", t->product, false);
1319 append_transport_info(result, "model:", t->model, true);
1320 append_transport_info(result, "device:", t->device, false);
Josh Gaob122b172017-08-16 16:57:01 -07001321
1322 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1323 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1324 *result += " transport_id:";
1325 *result += std::to_string(t->id);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001326 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001327 *result += '\n';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001328}
1329
Elliott Hughese67f1f82015-04-30 17:32:03 -07001330std::string list_transports(bool long_listing) {
Josh Gao1db71af2017-08-17 13:50:51 -07001331 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov04398a92017-12-17 10:56:07 +00001332
1333 auto sorted_transport_list = transport_list;
1334 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1335 if (x->type != y->type) {
1336 return x->type < y->type;
1337 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001338 return x->serial < y->serial;
Artem Iglikov04398a92017-12-17 10:56:07 +00001339 });
1340
1341 std::string result;
1342 for (const auto& t : sorted_transport_list) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001343 append_transport(t, &result, long_listing);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001344 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001345 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001346}
1347
Josh Gao3705b342019-03-28 15:47:44 -07001348void close_usb_devices(std::function<bool(const atransport*)> predicate, bool reset) {
Josh Gao1db71af2017-08-17 13:50:51 -07001349 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao22d2b3e2016-10-27 14:01:08 -07001350 for (auto& t : transport_list) {
1351 if (predicate(t)) {
Josh Gao3705b342019-03-28 15:47:44 -07001352 if (reset) {
1353 t->Reset();
1354 } else {
1355 t->Kick();
1356 }
Josh Gao22d2b3e2016-10-27 14:01:08 -07001357 }
1358 }
1359}
1360
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001361/* hack for osx */
Josh Gao3705b342019-03-28 15:47:44 -07001362void close_usb_devices(bool reset) {
1363 close_usb_devices([](const atransport*) { return true; }, reset);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001364}
Josh Gao1290fbf2016-11-22 14:32:34 -08001365#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001366
Josh Gao362e6962018-08-08 16:20:14 -07001367bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
Joshua Duong5cf78682020-01-21 13:19:42 -08001368 atransport::ReconnectCallback reconnect, bool use_tls, int* error) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001369 atransport* t = new atransport(std::move(reconnect), kCsOffline);
Joshua Duong5cf78682020-01-21 13:19:42 -08001370 t->use_tls = use_tls;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +01001371
Josh Gao3b4de3c2018-08-02 13:58:24 -07001372 D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
Josh Gao56300c92018-07-25 17:21:49 -07001373 if (init_socket_transport(t, std::move(s), port, local) < 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001374 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001375 if (error) *error = errno;
1376 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001377 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001378
Josh Gao1db71af2017-08-17 13:50:51 -07001379 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes65fe2512015-10-07 15:59:35 -07001380 for (const auto& transport : pending_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001381 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001382 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001383 << " is already in pending_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001384 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001385 if (error) *error = EALREADY;
1386 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001387 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001388 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001389
Elliott Hughes65fe2512015-10-07 15:59:35 -07001390 for (const auto& transport : transport_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001391 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001392 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001393 << " is already in transport_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001394 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001395 if (error) *error = EALREADY;
1396 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001397 }
1398 }
1399
Josh Gao3b4de3c2018-08-02 13:58:24 -07001400 t->serial = std::move(serial);
Dan Albertc7915a32015-05-18 16:46:31 -07001401 pending_list.push_front(t);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001402
1403 lock.unlock();
Benoit Goby1c45ee92013-03-29 18:22:36 -07001404
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001405 auto waitable = t->connection_waitable();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001406 register_transport(t);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001407
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001408 if (local == 1) {
1409 // Do not wait for emulator transports.
Josh Gao362e6962018-08-08 16:20:14 -07001410 return true;
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001411 }
1412
Josh Gao362e6962018-08-08 16:20:14 -07001413 if (!waitable->WaitForConnection(std::chrono::seconds(10))) {
1414 if (error) *error = ETIMEDOUT;
1415 return false;
1416 }
1417
1418 if (t->GetConnectionState() == kCsUnauthorized) {
1419 if (error) *error = EPERM;
1420 return false;
1421 }
1422
1423 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001424}
1425
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001426#if ADB_HOST
Josh Gao1290fbf2016-11-22 14:32:34 -08001427atransport* find_transport(const char* serial) {
Dan Albertc7915a32015-05-18 16:46:31 -07001428 atransport* result = nullptr;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001429
Josh Gao1db71af2017-08-17 13:50:51 -07001430 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001431 for (auto& t : transport_list) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001432 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001433 result = t;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001434 break;
1435 }
Dan Albertc7915a32015-05-18 16:46:31 -07001436 }
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001437
Dan Albertc7915a32015-05-18 16:46:31 -07001438 return result;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001439}
1440
Yabin Cuif4b99282015-08-27 12:03:11 -07001441void kick_all_tcp_devices() {
Josh Gao1db71af2017-08-17 13:50:51 -07001442 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001443 for (auto& t : transport_list) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001444 if (t->IsTcpDevice()) {
Yabin Cuid6ab3c22015-08-31 11:50:24 -07001445 // Kicking breaks the read_transport thread of this transport out of any read, then
1446 // the read_transport thread will notify the main thread to make this transport
1447 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cuif4b99282015-08-27 12:03:11 -07001448 // Finally, this transport will be closed and freed in the main thread.
Yabin Cui7f274902016-04-18 11:22:34 -07001449 t->Kick();
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001450 }
Dan Albertc7915a32015-05-18 16:46:31 -07001451 }
Josh Gao902dace2018-08-10 14:44:54 -07001452#if ADB_HOST
1453 reconnect_handler.CheckForKicked();
1454#endif
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001455}
1456
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001457#endif
1458
Josh Gao1290fbf2016-11-22 14:32:34 -08001459void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1460 unsigned writeable) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001461 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertc7915a32015-05-18 16:46:31 -07001462
Josh Gao1290fbf2016-11-22 14:32:34 -08001463 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cuib5e11412017-03-10 16:01:01 -08001464 init_usb_transport(t, usb);
Josh Gao1290fbf2016-11-22 14:32:34 -08001465 if (serial) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001466 t->serial = serial;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001467 }
Dan Albertc7915a32015-05-18 16:46:31 -07001468
1469 if (devpath) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001470 t->devpath = devpath;
Scott Andersone109d262012-04-20 11:21:14 -07001471 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001472
Josh Gao0cd3ae12016-09-21 12:37:10 -07001473 {
Josh Gao1db71af2017-08-17 13:50:51 -07001474 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001475 pending_list.push_front(t);
1476 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001477
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001478 register_transport(t);
1479}
1480
Josh Gaoc51726c2018-10-11 16:33:05 -07001481#if ADB_HOST
Dan Albertdcd78a12015-05-18 16:43:57 -07001482// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao1290fbf2016-11-22 14:32:34 -08001483void unregister_usb_transport(usb_handle* usb) {
Josh Gao1db71af2017-08-17 13:50:51 -07001484 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaob800d882018-01-28 20:32:46 -08001485 transport_list.remove_if([usb](atransport* t) {
Josh Gaoce5ce872018-12-11 13:11:52 -08001486 return t->GetUsbHandle() == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gaob800d882018-01-28 20:32:46 -08001487 });
Mike Lockwood0927bf92009-08-08 12:37:44 -04001488}
Josh Gaoc51726c2018-10-11 16:33:05 -07001489#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001490
Josh Gao36dadca2017-05-16 15:02:45 -07001491bool check_header(apacket* p, atransport* t) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001492 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cuib5e11412017-03-10 16:01:01 -08001493 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1494 << ", magic = " << p->msg.magic;
Josh Gao36dadca2017-05-16 15:02:45 -07001495 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001496 }
1497
Josh Gao1290fbf2016-11-22 14:32:34 -08001498 if (p->msg.data_length > t->get_max_payload()) {
1499 VLOG(RWX) << "check_header(): " << p->msg.data_length
1500 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao36dadca2017-05-16 15:02:45 -07001501 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001502 }
1503
Josh Gao36dadca2017-05-16 15:02:45 -07001504 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001505}
1506
Josh Gao3bd28792016-10-05 19:02:29 -07001507#if ADB_HOST
Joshua Duong5cf78682020-01-21 13:19:42 -08001508std::shared_ptr<RSA> atransport::Key() {
1509 if (keys_.empty()) {
1510 return nullptr;
1511 }
1512
1513 std::shared_ptr<RSA> result = keys_[0];
1514 return result;
1515}
1516
Josh Gao2e671202016-08-18 22:00:12 -07001517std::shared_ptr<RSA> atransport::NextKey() {
Josh Gao4414e4c2018-12-04 01:07:50 -08001518 if (keys_.empty()) {
1519 LOG(INFO) << "fetching keys for transport " << this->serial_name();
1520 keys_ = adb_auth_get_private_keys();
1521
1522 // We should have gotten at least one key: the one that's automatically generated.
1523 CHECK(!keys_.empty());
Joshua Duong5cf78682020-01-21 13:19:42 -08001524 } else {
1525 keys_.pop_front();
Josh Gao4414e4c2018-12-04 01:07:50 -08001526 }
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001527
Josh Gao2e671202016-08-18 22:00:12 -07001528 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001529 return result;
1530}
Josh Gao4414e4c2018-12-04 01:07:50 -08001531
1532void atransport::ResetKeys() {
1533 keys_.clear();
1534}
Josh Gao3bd28792016-10-05 19:02:29 -07001535#endif