blob: 61467cb612097cd395abdd19f2e5ac7ce6ecc0ac [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";
Josh Gao50ab0a62020-03-04 19:34:08 -080084const char* const kFeatureSendRecv2 = "sendrecv_v2";
85const char* const kFeatureSendRecv2Brotli = "sendrecv_v2_brotli";
Todd Kennedy51c05ec2015-11-10 00:03:25 +000086
Luis Hector Chavez56fe7532018-04-17 14:25:04 -070087namespace {
88
Josh Gaodef91c02018-07-31 18:28:32 -070089#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070090// Tracks and handles atransport*s that are attempting reconnection.
91class ReconnectHandler {
92 public:
93 ReconnectHandler() = default;
94 ~ReconnectHandler() = default;
95
96 // Starts the ReconnectHandler thread.
97 void Start();
98
99 // Requests the ReconnectHandler thread to stop.
100 void Stop();
101
102 // Adds the atransport* to the queue of reconnect attempts.
103 void TrackTransport(atransport* transport);
104
Josh Gao902dace2018-08-10 14:44:54 -0700105 // Wake up the ReconnectHandler thread to have it check for kicked transports.
106 void CheckForKicked();
107
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700108 private:
109 // The main thread loop.
110 void Run();
111
112 // Tracks a reconnection attempt.
113 struct ReconnectAttempt {
114 atransport* transport;
Josh Gao95af6412018-07-30 18:51:55 -0700115 std::chrono::steady_clock::time_point reconnect_time;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700116 size_t attempts_left;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700117
118 bool operator<(const ReconnectAttempt& rhs) const {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700119 if (reconnect_time == rhs.reconnect_time) {
120 return reinterpret_cast<uintptr_t>(transport) <
121 reinterpret_cast<uintptr_t>(rhs.transport);
122 }
123 return reconnect_time < rhs.reconnect_time;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700124 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700125 };
126
127 // Only retry for up to one minute.
Josh Gaoe445a6d2018-07-31 14:12:59 -0700128 static constexpr const std::chrono::seconds kDefaultTimeout = 10s;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700129 static constexpr const size_t kMaxAttempts = 6;
130
131 // Protects all members.
132 std::mutex reconnect_mutex_;
133 bool running_ GUARDED_BY(reconnect_mutex_) = true;
134 std::thread handler_thread_;
135 std::condition_variable reconnect_cv_;
Josh Gao8a40c8a2018-08-10 14:28:24 -0700136 std::set<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700137
138 DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
139};
140
141void ReconnectHandler::Start() {
142 check_main_thread();
143 handler_thread_ = std::thread(&ReconnectHandler::Run, this);
144}
145
146void ReconnectHandler::Stop() {
147 check_main_thread();
148 {
149 std::lock_guard<std::mutex> lock(reconnect_mutex_);
150 running_ = false;
151 }
152 reconnect_cv_.notify_one();
153 handler_thread_.join();
154
155 // Drain the queue to free all resources.
156 std::lock_guard<std::mutex> lock(reconnect_mutex_);
157 while (!reconnect_queue_.empty()) {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700158 ReconnectAttempt attempt = *reconnect_queue_.begin();
159 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700160 remove_transport(attempt.transport);
161 }
162}
163
164void ReconnectHandler::TrackTransport(atransport* transport) {
165 check_main_thread();
166 {
167 std::lock_guard<std::mutex> lock(reconnect_mutex_);
168 if (!running_) return;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700169 // Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
170 auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
171 reconnect_queue_.emplace(
172 ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700173 }
174 reconnect_cv_.notify_one();
175}
176
Josh Gao902dace2018-08-10 14:44:54 -0700177void ReconnectHandler::CheckForKicked() {
178 reconnect_cv_.notify_one();
179}
180
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700181void ReconnectHandler::Run() {
182 while (true) {
183 ReconnectAttempt attempt;
184 {
185 std::unique_lock<std::mutex> lock(reconnect_mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800186 ScopedLockAssertion assume_lock(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700187
Josh Gao95af6412018-07-30 18:51:55 -0700188 if (!reconnect_queue_.empty()) {
189 // FIXME: libstdc++ (used on Windows) implements condition_variable with
190 // system_clock as its clock, so we're probably hosed if the clock changes,
191 // even if we use steady_clock throughout. This problem goes away once we
192 // switch to libc++.
Josh Gao8a40c8a2018-08-10 14:28:24 -0700193 reconnect_cv_.wait_until(lock, reconnect_queue_.begin()->reconnect_time);
Josh Gao95af6412018-07-30 18:51:55 -0700194 } else {
195 reconnect_cv_.wait(lock);
196 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700197
198 if (!running_) return;
Josh Gao902dace2018-08-10 14:44:54 -0700199
200 // Scan the whole list for kicked transports, so that we immediately handle an explicit
201 // disconnect request.
202 bool kicked = false;
203 for (auto it = reconnect_queue_.begin(); it != reconnect_queue_.end();) {
204 if (it->transport->kicked()) {
205 D("transport %s was kicked. giving up on it.", it->transport->serial.c_str());
206 remove_transport(it->transport);
207 it = reconnect_queue_.erase(it);
208 } else {
209 ++it;
210 }
211 kicked = true;
212 }
213
Josh Gao95af6412018-07-30 18:51:55 -0700214 if (reconnect_queue_.empty()) continue;
215
Josh Gao902dace2018-08-10 14:44:54 -0700216 // Go back to sleep if we either woke up spuriously, or we were woken up to remove
217 // a kicked transport, and the first transport isn't ready for reconnection yet.
Josh Gao95af6412018-07-30 18:51:55 -0700218 auto now = std::chrono::steady_clock::now();
Josh Gao8a40c8a2018-08-10 14:28:24 -0700219 if (reconnect_queue_.begin()->reconnect_time > now) {
Josh Gao95af6412018-07-30 18:51:55 -0700220 continue;
221 }
222
Josh Gao8a40c8a2018-08-10 14:28:24 -0700223 attempt = *reconnect_queue_.begin();
224 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700225 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700226 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700227
Josh Gaofc2e56f2018-08-30 11:37:00 -0700228 switch (attempt.transport->Reconnect()) {
229 case ReconnectResult::Retry: {
230 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
231 if (attempt.attempts_left == 0) {
232 D("transport %s exceeded the number of retry attempts. giving up on it.",
233 attempt.transport->serial.c_str());
234 remove_transport(attempt.transport);
235 continue;
236 }
237
238 std::lock_guard<std::mutex> lock(reconnect_mutex_);
239 reconnect_queue_.emplace(ReconnectAttempt{
240 attempt.transport,
241 std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
242 attempt.attempts_left - 1});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700243 continue;
244 }
245
Josh Gaofc2e56f2018-08-30 11:37:00 -0700246 case ReconnectResult::Success:
247 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
248 register_transport(attempt.transport);
249 continue;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700250
Josh Gaofc2e56f2018-08-30 11:37:00 -0700251 case ReconnectResult::Abort:
252 D("cancelling reconnection attempt to %s.", attempt.transport->serial.c_str());
253 remove_transport(attempt.transport);
254 continue;
255 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700256 }
257}
258
259static auto& reconnect_handler = *new ReconnectHandler();
260
Josh Gaodef91c02018-07-31 18:28:32 -0700261#endif
262
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700263} // namespace
264
Josh Gaob122b172017-08-16 16:57:01 -0700265TransportId NextTransportId() {
266 static std::atomic<TransportId> next(1);
267 return next++;
268}
269
Josh Gao3705b342019-03-28 15:47:44 -0700270void Connection::Reset() {
271 LOG(INFO) << "Connection::Reset(): stopping";
272 Stop();
273}
274
Josh Gao0bbf69c2018-02-16 13:24:58 -0800275BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
276 : underlying_(std::move(connection)) {}
277
278BlockingConnectionAdapter::~BlockingConnectionAdapter() {
279 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
280 Stop();
281}
282
283void BlockingConnectionAdapter::Start() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700284 std::lock_guard<std::mutex> lock(mutex_);
285 if (started_) {
286 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
287 << "): started multiple times";
288 }
289
Joshua Duong5cf78682020-01-21 13:19:42 -0800290 StartReadThread();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800291
292 write_thread_ = std::thread([this]() {
293 LOG(INFO) << this->transport_name_ << ": write thread spawning";
294 while (true) {
295 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800296 ScopedLockAssertion assume_locked(mutex_);
Josh Gaoc251ec52018-04-03 12:55:18 -0700297 cv_.wait(lock, [this]() REQUIRES(mutex_) {
298 return this->stopped_ || !this->write_queue_.empty();
299 });
300
Josh Gao0bbf69c2018-02-16 13:24:58 -0800301 if (this->stopped_) {
302 return;
303 }
304
305 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
306 this->write_queue_.pop_front();
307 lock.unlock();
308
309 if (!this->underlying_->Write(packet.get())) {
310 break;
311 }
312 }
313 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
314 });
Josh Gaoc251ec52018-04-03 12:55:18 -0700315
316 started_ = true;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800317}
318
Joshua Duong5cf78682020-01-21 13:19:42 -0800319void BlockingConnectionAdapter::StartReadThread() {
320 read_thread_ = std::thread([this]() {
321 LOG(INFO) << this->transport_name_ << ": read thread spawning";
322 while (true) {
323 auto packet = std::make_unique<apacket>();
324 if (!underlying_->Read(packet.get())) {
325 PLOG(INFO) << this->transport_name_ << ": read failed";
326 break;
327 }
328
329 bool got_stls_cmd = false;
330 if (packet->msg.command == A_STLS) {
331 got_stls_cmd = true;
332 }
333
334 read_callback_(this, std::move(packet));
335
336 // If we received the STLS packet, we are about to perform the TLS
337 // handshake. So this read thread must stop and resume after the
338 // handshake completes otherwise this will interfere in the process.
339 if (got_stls_cmd) {
340 LOG(INFO) << this->transport_name_
341 << ": Received STLS packet. Stopping read thread.";
342 return;
343 }
344 }
345 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
346 });
347}
348
349bool BlockingConnectionAdapter::DoTlsHandshake(RSA* key, std::string* auth_key) {
350 std::lock_guard<std::mutex> lock(mutex_);
351 if (read_thread_.joinable()) {
352 read_thread_.join();
353 }
354 bool success = this->underlying_->DoTlsHandshake(key, auth_key);
355 StartReadThread();
356 return success;
357}
358
Josh Gao3705b342019-03-28 15:47:44 -0700359void BlockingConnectionAdapter::Reset() {
360 {
361 std::lock_guard<std::mutex> lock(mutex_);
362 if (!started_) {
363 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
364 return;
365 }
366
367 if (stopped_) {
368 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
369 << "): already stopped";
370 return;
371 }
372 }
373
374 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): resetting";
375 this->underlying_->Reset();
376 Stop();
377}
378
Josh Gao0bbf69c2018-02-16 13:24:58 -0800379void BlockingConnectionAdapter::Stop() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700380 {
381 std::lock_guard<std::mutex> lock(mutex_);
382 if (!started_) {
383 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
384 return;
385 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800386
Josh Gaoc251ec52018-04-03 12:55:18 -0700387 if (stopped_) {
388 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
389 << "): already stopped";
390 return;
391 }
392
393 stopped_ = true;
394 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800395
396 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
397
398 this->underlying_->Close();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800399 this->cv_.notify_one();
Josh Gaoc251ec52018-04-03 12:55:18 -0700400
401 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
402 std::thread read_thread;
403 std::thread write_thread;
404
405 {
406 std::lock_guard<std::mutex> lock(mutex_);
407 read_thread = std::move(read_thread_);
408 write_thread = std::move(write_thread_);
409 }
410
411 read_thread.join();
412 write_thread.join();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800413
414 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
415 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
416}
417
418bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
419 {
Josh Gaoc251ec52018-04-03 12:55:18 -0700420 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800421 write_queue_.emplace_back(std::move(packet));
422 }
423
424 cv_.notify_one();
425 return true;
426}
427
Joshua Duong5cf78682020-01-21 13:19:42 -0800428FdConnection::FdConnection(unique_fd fd) : fd_(std::move(fd)) {}
429
430FdConnection::~FdConnection() {}
431
432bool FdConnection::DispatchRead(void* buf, size_t len) {
433 if (tls_ != nullptr) {
434 // The TlsConnection doesn't allow 0 byte reads
435 if (len == 0) {
436 return true;
437 }
438 return tls_->ReadFully(buf, len);
439 }
440
441 return ReadFdExactly(fd_.get(), buf, len);
442}
443
444bool FdConnection::DispatchWrite(void* buf, size_t len) {
445 if (tls_ != nullptr) {
446 // The TlsConnection doesn't allow 0 byte writes
447 if (len == 0) {
448 return true;
449 }
450 return tls_->WriteFully(std::string_view(reinterpret_cast<const char*>(buf), len));
451 }
452
453 return WriteFdExactly(fd_.get(), buf, len);
454}
455
Josh Gaob800d882018-01-28 20:32:46 -0800456bool FdConnection::Read(apacket* packet) {
Joshua Duong5cf78682020-01-21 13:19:42 -0800457 if (!DispatchRead(&packet->msg, sizeof(amessage))) {
Josh Gaob800d882018-01-28 20:32:46 -0800458 D("remote local: read terminated (message)");
459 return false;
460 }
461
Josh Gaof571fcb2018-02-05 18:49:10 -0800462 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gao5caaebd2018-02-02 14:38:04 -0800463 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
464 return false;
465 }
466
Josh Gaof571fcb2018-02-05 18:49:10 -0800467 packet->payload.resize(packet->msg.data_length);
468
Joshua Duong5cf78682020-01-21 13:19:42 -0800469 if (!DispatchRead(&packet->payload[0], packet->payload.size())) {
Josh Gaob800d882018-01-28 20:32:46 -0800470 D("remote local: terminated (data)");
471 return false;
472 }
473
474 return true;
475}
476
477bool FdConnection::Write(apacket* packet) {
Joshua Duong5cf78682020-01-21 13:19:42 -0800478 if (!DispatchWrite(&packet->msg, sizeof(packet->msg))) {
Josh Gaob800d882018-01-28 20:32:46 -0800479 D("remote local: write terminated");
480 return false;
481 }
482
Josh Gaof571fcb2018-02-05 18:49:10 -0800483 if (packet->msg.data_length) {
Joshua Duong5cf78682020-01-21 13:19:42 -0800484 if (!DispatchWrite(&packet->payload[0], packet->msg.data_length)) {
Josh Gaof571fcb2018-02-05 18:49:10 -0800485 D("remote local: write terminated");
486 return false;
487 }
488 }
489
Josh Gaob800d882018-01-28 20:32:46 -0800490 return true;
491}
492
Joshua Duong5cf78682020-01-21 13:19:42 -0800493bool FdConnection::DoTlsHandshake(RSA* key, std::string* auth_key) {
494 bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
495 if (!EVP_PKEY_set1_RSA(evp_pkey.get(), key)) {
496 LOG(ERROR) << "EVP_PKEY_set1_RSA failed";
497 return false;
498 }
499 auto x509 = GenerateX509Certificate(evp_pkey.get());
500 auto x509_str = X509ToPEMString(x509.get());
501 auto evp_str = Key::ToPEMString(evp_pkey.get());
Joshua Duongbba72d92020-03-24 09:50:59 -0700502#ifdef _WIN32
503 int osh = cast_handle_to_int(adb_get_os_handle(fd_));
504#else
505 int osh = adb_get_os_handle(fd_);
506#endif
507
Joshua Duong5cf78682020-01-21 13:19:42 -0800508#if ADB_HOST
509 tls_ = TlsConnection::Create(TlsConnection::Role::Client,
510#else
511 tls_ = TlsConnection::Create(TlsConnection::Role::Server,
512#endif
Joshua Duongbba72d92020-03-24 09:50:59 -0700513 x509_str, evp_str, osh);
Joshua Duong5cf78682020-01-21 13:19:42 -0800514 CHECK(tls_);
515#if ADB_HOST
516 // TLS 1.3 gives the client no message if the server rejected the
517 // certificate. This will enable a check in the tls connection to check
518 // whether the client certificate got rejected. Note that this assumes
519 // that, on handshake success, the server speaks first.
520 tls_->EnableClientPostHandshakeCheck(true);
521 // Add callback to set the certificate when server issues the
522 // CertificateRequest.
523 tls_->SetCertificateCallback(adb_tls_set_certificate);
524 // Allow any server certificate
525 tls_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
526#else
527 // Add callback to check certificate against a list of known public keys
528 tls_->SetCertVerifyCallback(
529 [auth_key](X509_STORE_CTX* ctx) { return adbd_tls_verify_cert(ctx, auth_key); });
530 // Add the list of allowed client CA issuers
531 auto ca_list = adbd_tls_client_ca_list();
532 tls_->SetClientCAList(ca_list.get());
533#endif
534
535 auto err = tls_->DoHandshake();
536 if (err == TlsError::Success) {
537 return true;
538 }
539
540 tls_.reset();
541 return false;
542}
543
Josh Gaob800d882018-01-28 20:32:46 -0800544void FdConnection::Close() {
545 adb_shutdown(fd_.get());
546 fd_.reset();
547}
548
Josh Gao06d61d42016-10-06 13:31:44 -0700549void send_packet(apacket* p, atransport* t) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800550 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayde471942017-12-07 11:40:00 -0800551 // compute a checksum for connection/auth packets for compatibility reasons
552 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
553 p->msg.data_check = 0;
554 } else {
555 p->msg.data_check = calculate_apacket_checksum(p);
556 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800557
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700558 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800559
Yi Kongaed415c2018-07-13 18:15:16 -0700560 if (t == nullptr) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700561 LOG(FATAL) << "Transport is null";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800562 }
563
Josh Gao0bbf69c2018-02-16 13:24:58 -0800564 if (t->Write(p) != 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700565 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800566 t->Kick();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800567 }
568}
569
Josh Gao3705b342019-03-28 15:47:44 -0700570void kick_transport(atransport* t, bool reset) {
Josh Gao1db71af2017-08-17 13:50:51 -0700571 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui1f4ec192016-04-05 13:50:44 -0700572 // As kick_transport() can be called from threads without guarantee that t is valid,
573 // check if the transport is in transport_list first.
Josh Gaob122b172017-08-16 16:57:01 -0700574 //
575 // TODO(jmgao): WTF? Is this actually true?
Yabin Cui1f4ec192016-04-05 13:50:44 -0700576 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Josh Gao3705b342019-03-28 15:47:44 -0700577 if (reset) {
578 t->Reset();
579 } else {
580 t->Kick();
581 }
Yabin Cui1f4ec192016-04-05 13:50:44 -0700582 }
Josh Gao902dace2018-08-10 14:44:54 -0700583
584#if ADB_HOST
585 reconnect_handler.CheckForKicked();
586#endif
Yabin Cuif4b99282015-08-27 12:03:11 -0700587}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800588
589static int transport_registration_send = -1;
590static int transport_registration_recv = -1;
Josh Gao71f775a2018-05-14 11:14:33 -0700591static fdevent* transport_registration_fde;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800592
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800593#if ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800594
595/* this adds support required by the 'track-devices' service.
596 * this is used to send the content of "list_transport" to any
597 * number of client connections that want it through a single
598 * live TCP connection
599 */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800600struct device_tracker {
Josh Gao1290fbf2016-11-22 14:32:34 -0800601 asocket socket;
Josh Gaoe0361d12018-02-12 17:24:00 -0800602 bool update_needed = false;
603 bool long_output = false;
604 device_tracker* next = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800605};
606
607/* linked list of all device trackers */
Josh Gao1290fbf2016-11-22 14:32:34 -0800608static device_tracker* device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800609
Josh Gao1290fbf2016-11-22 14:32:34 -0800610static void device_tracker_remove(device_tracker* tracker) {
611 device_tracker** pnode = &device_tracker_list;
612 device_tracker* node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800613
Josh Gao1db71af2017-08-17 13:50:51 -0700614 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800615 while (node) {
616 if (node == tracker) {
617 *pnode = node->next;
618 break;
619 }
620 pnode = &node->next;
Josh Gao1290fbf2016-11-22 14:32:34 -0800621 node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800622 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800623}
624
Josh Gao1290fbf2016-11-22 14:32:34 -0800625static void device_tracker_close(asocket* socket) {
626 device_tracker* tracker = (device_tracker*)socket;
627 asocket* peer = socket->peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800628
Josh Gao1290fbf2016-11-22 14:32:34 -0800629 D("device tracker %p removed", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800630 if (peer) {
Yi Kongaed415c2018-07-13 18:15:16 -0700631 peer->peer = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800632 peer->close(peer);
633 }
634 device_tracker_remove(tracker);
Josh Gaoe0361d12018-02-12 17:24:00 -0800635 delete tracker;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800636}
637
Josh Gao1ce99572018-03-07 16:52:28 -0800638static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800639 /* you can't read from a device tracker, close immediately */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800640 device_tracker_close(socket);
641 return -1;
642}
643
Elliott Hughese67f1f82015-04-30 17:32:03 -0700644static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700645 asocket* peer = tracker->socket.peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800646
Josh Gao1ce99572018-03-07 16:52:28 -0800647 apacket::payload_type data;
Josh Gao27cb7dc2018-02-01 13:17:50 -0800648 data.resize(4 + string.size());
649 char buf[5];
650 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
651 memcpy(&data[0], buf, 4);
652 memcpy(&data[4], string.data(), string.size());
653 return peer->enqueue(peer, std::move(data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800654}
655
Elliott Hughese67f1f82015-04-30 17:32:03 -0700656static void device_tracker_ready(asocket* socket) {
657 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800658
Elliott Hughese67f1f82015-04-30 17:32:03 -0700659 // We want to send the device list when the tracker connects
660 // for the first time, even if no update occurred.
Josh Gaob0c18022017-08-14 18:57:54 -0700661 if (tracker->update_needed) {
662 tracker->update_needed = false;
Elliott Hughesfc2f5f62019-07-31 14:13:57 -0700663 device_tracker_send(tracker, list_transports(tracker->long_output));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800664 }
665}
666
Josh Gaob0c18022017-08-14 18:57:54 -0700667asocket* create_device_tracker(bool long_output) {
Josh Gaoe0361d12018-02-12 17:24:00 -0800668 device_tracker* tracker = new device_tracker();
Elliott Hughes4679a392018-10-19 13:59:44 -0700669 if (tracker == nullptr) LOG(FATAL) << "cannot allocate device tracker";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800670
Josh Gao1290fbf2016-11-22 14:32:34 -0800671 D("device tracker %p created", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800672
673 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao1290fbf2016-11-22 14:32:34 -0800674 tracker->socket.ready = device_tracker_ready;
675 tracker->socket.close = device_tracker_close;
Josh Gaob0c18022017-08-14 18:57:54 -0700676 tracker->update_needed = true;
677 tracker->long_output = long_output;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800678
Josh Gao1290fbf2016-11-22 14:32:34 -0800679 tracker->next = device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800680 device_tracker_list = tracker;
681
682 return &tracker->socket;
683}
684
Josh Gaofd713e52017-05-03 22:37:10 -0700685// Check if all of the USB transports are connected.
686bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gao1db71af2017-08-17 13:50:51 -0700687 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaofd713e52017-05-03 22:37:10 -0700688 for (const auto& t : transport_list) {
689 if (!fn(t)) {
690 return false;
691 }
692 }
693 for (const auto& t : pending_list) {
694 if (!fn(t)) {
695 return false;
696 }
697 }
698 return true;
699}
700
Elliott Hughese67f1f82015-04-30 17:32:03 -0700701// Call this function each time the transport list has changed.
702void update_transports() {
Josh Gaofd713e52017-05-03 22:37:10 -0700703 update_transport_status();
704
705 // Notify `adb track-devices` clients.
Elliott Hughese67f1f82015-04-30 17:32:03 -0700706 device_tracker* tracker = device_tracker_list;
707 while (tracker != nullptr) {
708 device_tracker* next = tracker->next;
709 // This may destroy the tracker if the connection is closed.
Elliott Hughesfc2f5f62019-07-31 14:13:57 -0700710 device_tracker_send(tracker, list_transports(tracker->long_output));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800711 tracker = next;
712 }
713}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700714
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800715#else
Elliott Hughese67f1f82015-04-30 17:32:03 -0700716
717void update_transports() {
718 // Nothing to do on the device side.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800719}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700720
Josh Gao1290fbf2016-11-22 14:32:34 -0800721#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800722
Josh Gao1290fbf2016-11-22 14:32:34 -0800723struct tmsg {
724 atransport* transport;
725 int action;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800726};
727
Josh Gao1290fbf2016-11-22 14:32:34 -0800728static int transport_read_action(int fd, struct tmsg* m) {
729 char* p = (char*)m;
730 int len = sizeof(*m);
731 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800732
Josh Gao1290fbf2016-11-22 14:32:34 -0800733 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800734 r = adb_read(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800735 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800736 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800737 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800738 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700739 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800740 return -1;
741 }
742 }
743 return 0;
744}
745
Josh Gao1290fbf2016-11-22 14:32:34 -0800746static int transport_write_action(int fd, struct tmsg* m) {
747 char* p = (char*)m;
748 int len = sizeof(*m);
749 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800750
Josh Gao1290fbf2016-11-22 14:32:34 -0800751 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800752 r = adb_write(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800753 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800754 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800755 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800756 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700757 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800758 return -1;
759 }
760 }
761 return 0;
762}
763
Josh Gao0bbf69c2018-02-16 13:24:58 -0800764static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800765 tmsg m;
Josh Gao1290fbf2016-11-22 14:32:34 -0800766 atransport* t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800767
Josh Gao1290fbf2016-11-22 14:32:34 -0800768 if (!(ev & FDE_READ)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800769 return;
770 }
771
Josh Gao1290fbf2016-11-22 14:32:34 -0800772 if (transport_read_action(_fd, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700773 PLOG(FATAL) << "cannot read transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800774 }
775
776 t = m.transport;
777
Dan Albert1792c232015-05-18 13:06:53 -0700778 if (m.action == 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700779 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800780
Josh Gao0cd3ae12016-09-21 12:37:10 -0700781 {
Josh Gao1db71af2017-08-17 13:50:51 -0700782 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700783 transport_list.remove(t);
784 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800785
Dan Albertc7915a32015-05-18 16:46:31 -0700786 delete t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800787
788 update_transports();
789 return;
790 }
791
Mike Lockwood0927bf92009-08-08 12:37:44 -0400792 /* don't create transport threads for inaccessible devices */
Yabin Cuib5e11412017-03-10 16:01:01 -0800793 if (t->GetConnectionState() != kCsNoPerm) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700794 // The connection gets a reference to the atransport. It will release it
795 // upon a read/write error.
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700796 t->connection()->SetTransportName(t->serial_name());
797 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao0bbf69c2018-02-16 13:24:58 -0800798 if (!check_header(p.get(), t)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700799 D("%s: remote read: bad header", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800800 return false;
801 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800802
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700803 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "from remote", p.get());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800804 apacket* packet = p.release();
Mike Lockwood0927bf92009-08-08 12:37:44 -0400805
Josh Gao0bbf69c2018-02-16 13:24:58 -0800806 // TODO: Does this need to run on the main thread?
807 fdevent_run_on_main_thread([packet, t]() { handle_packet(packet, t); });
808 return true;
809 });
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700810 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700811 LOG(INFO) << t->serial_name() << ": connection terminated: " << error;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800812 fdevent_run_on_main_thread([t]() {
813 handle_offline(t);
Josh Gao9a8366b2019-12-09 13:45:31 -0800814 transport_destroy(t);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800815 });
816 });
Mike Lockwood0927bf92009-08-08 12:37:44 -0400817
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700818 t->connection()->Start();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800819#if ADB_HOST
820 send_connect(t);
821#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800822 }
823
Josh Gao0cd3ae12016-09-21 12:37:10 -0700824 {
Josh Gao1db71af2017-08-17 13:50:51 -0700825 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700826 auto it = std::find(pending_list.begin(), pending_list.end(), t);
827 if (it != pending_list.end()) {
828 pending_list.remove(t);
829 transport_list.push_front(t);
830 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700831 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800832
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800833 update_transports();
834}
835
Josh Gaodef91c02018-07-31 18:28:32 -0700836#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700837void init_reconnect_handler(void) {
838 reconnect_handler.Start();
839}
Josh Gaodef91c02018-07-31 18:28:32 -0700840#endif
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700841
Josh Gao1290fbf2016-11-22 14:32:34 -0800842void init_transport_registration(void) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800843 int s[2];
844
Josh Gao1290fbf2016-11-22 14:32:34 -0800845 if (adb_socketpair(s)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700846 PLOG(FATAL) << "cannot open transport registration socketpair";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800847 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700848 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800849
850 transport_registration_send = s[0];
851 transport_registration_recv = s[1];
852
Josh Gao71f775a2018-05-14 11:14:33 -0700853 transport_registration_fde =
Yi Kongaed415c2018-07-13 18:15:16 -0700854 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao71f775a2018-05-14 11:14:33 -0700855 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao01b7bc42017-05-09 13:43:35 -0700856}
857
858void kick_all_transports() {
Josh Gaodef91c02018-07-31 18:28:32 -0700859#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700860 reconnect_handler.Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700861#endif
Josh Gao01b7bc42017-05-09 13:43:35 -0700862 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gao1db71af2017-08-17 13:50:51 -0700863 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao01b7bc42017-05-09 13:43:35 -0700864 for (auto t : transport_list) {
865 t->Kick();
866 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800867}
868
Joshua Duong5cf78682020-01-21 13:19:42 -0800869void kick_all_tcp_tls_transports() {
870 std::lock_guard<std::recursive_mutex> lock(transport_lock);
871 for (auto t : transport_list) {
872 if (t->IsTcpDevice() && t->use_tls) {
873 t->Kick();
874 }
875 }
876}
877
878#if !ADB_HOST
879void kick_all_transports_by_auth_key(std::string_view auth_key) {
880 std::lock_guard<std::recursive_mutex> lock(transport_lock);
881 for (auto t : transport_list) {
882 if (auth_key == t->auth_key) {
883 t->Kick();
884 }
885 }
886}
887#endif
888
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800889/* the fdevent select pump is single threaded */
Josh Gaoc51726c2018-10-11 16:33:05 -0700890void register_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800891 tmsg m;
892 m.transport = transport;
893 m.action = 1;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700894 D("transport: %s registered", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800895 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700896 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800897 }
898}
899
Josh Gao1290fbf2016-11-22 14:32:34 -0800900static void remove_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800901 tmsg m;
902 m.transport = transport;
903 m.action = 0;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700904 D("transport: %s removed", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800905 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700906 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800907 }
908}
909
Josh Gao9a8366b2019-12-09 13:45:31 -0800910static void transport_destroy(atransport* t) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700911 check_main_thread();
Yabin Cuif4b99282015-08-27 12:03:11 -0700912 CHECK(t != nullptr);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700913
Josh Gaoe48ecce2017-09-13 13:40:57 -0700914 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao9a8366b2019-12-09 13:45:31 -0800915 LOG(INFO) << "destroying transport " << t->serial_name();
916 t->connection()->Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700917#if ADB_HOST
Josh Gao9a8366b2019-12-09 13:45:31 -0800918 if (t->IsTcpDevice() && !t->kicked()) {
919 D("transport: %s destroy (attempting reconnection)", t->serial.c_str());
Josh Gao4414e4c2018-12-04 01:07:50 -0800920
Josh Gao9a8366b2019-12-09 13:45:31 -0800921 // We need to clear the transport's keys, so that on the next connection, it tries
922 // again from the beginning.
923 t->ResetKeys();
924 reconnect_handler.TrackTransport(t);
925 return;
926 }
Josh Gaodef91c02018-07-31 18:28:32 -0700927#endif
928
Josh Gao9a8366b2019-12-09 13:45:31 -0800929 D("transport: %s destroy (kicking and closing)", t->serial.c_str());
930 remove_transport(t);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800931}
932
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700933static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao1290fbf2016-11-22 14:32:34 -0800934 bool sanitize_qual) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700935 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
936 return qual.empty();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700937
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700938 if (qual.empty()) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700939
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700940 const char* ptr = to_test.c_str();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700941 if (prefix) {
942 while (*prefix) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700943 if (*prefix++ != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700944 }
945 }
946
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700947 for (char ch : qual) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800948 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700949 if (ch != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700950 }
951
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700952 /* Everything matched so far. Return true if *ptr is a NUL. */
953 return !*ptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700954}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800955
Josh Gaob122b172017-08-16 16:57:01 -0700956atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
957 bool* is_ambiguous, std::string* error_out,
958 bool accept_any_state) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700959 atransport* result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800960
Josh Gaob122b172017-08-16 16:57:01 -0700961 if (transport_id != 0) {
962 *error_out =
963 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
964 } else if (serial) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700965 *error_out = android::base::StringPrintf("device '%s' not found", serial);
966 } else if (type == kTransportLocal) {
967 *error_out = "no emulators found";
968 } else if (type == kTransportAny) {
969 *error_out = "no devices/emulators found";
970 } else {
971 *error_out = "no devices found";
972 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800973
Josh Gao1db71af2017-08-17 13:50:51 -0700974 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes8d28e192015-10-07 14:55:10 -0700975 for (const auto& t : transport_list) {
Yabin Cuib5e11412017-03-10 16:01:01 -0800976 if (t->GetConnectionState() == kCsNoPerm) {
David Purselld2acbd12015-12-02 15:14:31 -0800977 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwood37d31112009-08-08 13:53:16 -0400978 continue;
979 }
Mike Lockwood0927bf92009-08-08 12:37:44 -0400980
Josh Gaob122b172017-08-16 16:57:01 -0700981 if (transport_id) {
982 if (t->id == transport_id) {
983 result = t;
984 break;
985 }
986 } else if (serial) {
David Pursell3f902aa2016-03-01 08:58:26 -0800987 if (t->MatchesTarget(serial)) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700988 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700989 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700990 if (is_ambiguous) *is_ambiguous = true;
991 result = nullptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700992 break;
993 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800994 result = t;
Scott Andersone109d262012-04-20 11:21:14 -0700995 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800996 } else {
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700997 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800998 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700999 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -07001000 if (is_ambiguous) *is_ambiguous = true;
1001 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001002 break;
1003 }
1004 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001005 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001006 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -07001007 *error_out = "more than one emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -07001008 if (is_ambiguous) *is_ambiguous = true;
1009 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001010 break;
1011 }
1012 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001013 } else if (type == kTransportAny) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001014 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -07001015 *error_out = "more than one device/emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -07001016 if (is_ambiguous) *is_ambiguous = true;
1017 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001018 break;
1019 }
1020 result = t;
1021 }
1022 }
1023 }
Josh Gao0cd3ae12016-09-21 12:37:10 -07001024 lock.unlock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001025
Josh Gao704494b2018-05-04 16:04:49 -07001026 if (result && !accept_any_state) {
1027 // The caller requires an active transport.
1028 // Make sure that we're actually connected.
1029 ConnectionState state = result->GetConnectionState();
1030 switch (state) {
1031 case kCsConnecting:
1032 *error_out = "device still connecting";
1033 result = nullptr;
1034 break;
Benoit Goby77e8e582013-01-15 12:36:47 -08001035
Josh Gao704494b2018-05-04 16:04:49 -07001036 case kCsAuthorizing:
1037 *error_out = "device still authorizing";
1038 result = nullptr;
1039 break;
1040
1041 case kCsUnauthorized: {
1042 *error_out = "device unauthorized.\n";
1043 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
1044 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
1045 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
1046 *error_out += "\n";
1047 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
1048 *error_out += "Otherwise check for a confirmation dialog on your device.";
1049 result = nullptr;
1050 break;
1051 }
1052
1053 case kCsOffline:
1054 *error_out = "device offline";
1055 result = nullptr;
1056 break;
1057
1058 default:
1059 break;
1060 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001061 }
1062
1063 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -07001064 *error_out = "success";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001065 }
1066
1067 return result;
1068}
1069
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001070bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
1071 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -08001072 ScopedLockAssertion assume_locked(mutex_);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001073 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
1074 return connection_established_ready_;
1075 }) && connection_established_;
1076}
1077
1078void ConnectionWaitable::SetConnectionEstablished(bool success) {
1079 {
1080 std::lock_guard<std::mutex> lock(mutex_);
1081 if (connection_established_ready_) return;
1082 connection_established_ready_ = true;
1083 connection_established_ = success;
1084 D("connection established with %d", success);
1085 }
1086 cv_.notify_one();
1087}
1088
1089atransport::~atransport() {
1090 // If the connection callback had not been run before, run it now.
1091 SetConnectionEstablished(false);
1092}
1093
Yabin Cuib5e11412017-03-10 16:01:01 -08001094int atransport::Write(apacket* p) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -07001095 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cuib5e11412017-03-10 16:01:01 -08001096}
1097
Josh Gao3705b342019-03-28 15:47:44 -07001098void atransport::Reset() {
1099 if (!kicked_.exchange(true)) {
1100 LOG(INFO) << "resetting transport " << this << " " << this->serial;
1101 this->connection()->Reset();
1102 }
1103}
1104
Yabin Cui7f274902016-04-18 11:22:34 -07001105void atransport::Kick() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001106 if (!kicked_.exchange(true)) {
Josh Gao3705b342019-03-28 15:47:44 -07001107 LOG(INFO) << "kicking transport " << this << " " << this->serial;
Luis Hector Chavez9a388d52018-04-25 08:56:41 -07001108 this->connection()->Stop();
Yabin Cui7f274902016-04-18 11:22:34 -07001109 }
1110}
1111
Yabin Cuib5e11412017-03-10 16:01:01 -08001112ConnectionState atransport::GetConnectionState() const {
1113 return connection_state_;
1114}
1115
1116void atransport::SetConnectionState(ConnectionState state) {
1117 check_main_thread();
1118 connection_state_ = state;
1119}
1120
Luis Hector Chavez9a388d52018-04-25 08:56:41 -07001121void atransport::SetConnection(std::unique_ptr<Connection> connection) {
1122 std::lock_guard<std::mutex> lock(mutex_);
1123 connection_ = std::shared_ptr<Connection>(std::move(connection));
1124}
1125
Josh Gaoffbd3362018-02-28 14:44:23 -08001126std::string atransport::connection_state_name() const {
Yabin Cuib5e11412017-03-10 16:01:01 -08001127 ConnectionState state = GetConnectionState();
1128 switch (state) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001129 case kCsOffline:
1130 return "offline";
1131 case kCsBootloader:
1132 return "bootloader";
1133 case kCsDevice:
1134 return "device";
1135 case kCsHost:
1136 return "host";
1137 case kCsRecovery:
1138 return "recovery";
Tao Bao55d407e2019-04-07 23:24:03 -07001139 case kCsRescue:
1140 return "rescue";
Josh Gao1290fbf2016-11-22 14:32:34 -08001141 case kCsNoPerm:
1142 return UsbNoPermissionsShortHelpText();
1143 case kCsSideload:
1144 return "sideload";
1145 case kCsUnauthorized:
1146 return "unauthorized";
Josh Gao704494b2018-05-04 16:04:49 -07001147 case kCsAuthorizing:
1148 return "authorizing";
1149 case kCsConnecting:
1150 return "connecting";
Josh Gao1290fbf2016-11-22 14:32:34 -08001151 default:
1152 return "unknown";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001153 }
1154}
1155
Tamas Berghammer3d2904c2015-07-13 19:12:28 +01001156void atransport::update_version(int version, size_t payload) {
1157 protocol_version = std::min(version, A_VERSION);
1158 max_payload = std::min(payload, MAX_PAYLOAD);
1159}
1160
1161int atransport::get_protocol_version() const {
1162 return protocol_version;
1163}
1164
Joshua Duong5cf78682020-01-21 13:19:42 -08001165int atransport::get_tls_version() const {
1166 return tls_version;
1167}
1168
Tamas Berghammer3d2904c2015-07-13 19:12:28 +01001169size_t atransport::get_max_payload() const {
1170 return max_payload;
1171}
1172
Dan Albert1792c232015-05-18 13:06:53 -07001173const FeatureSet& supported_features() {
David Pursell4e2fd362015-09-22 10:43:08 -07001174 // Local static allocation to avoid global non-POD variables.
1175 static const FeatureSet* features = new FeatureSet{
Josh Gao7b1cb662019-02-20 13:01:40 -08001176 kFeatureShell2,
1177 kFeatureCmd,
1178 kFeatureStat2,
Josh Gao34a478f2019-08-07 14:23:17 -07001179 kFeatureLs2,
Josh Gao7b1cb662019-02-20 13:01:40 -08001180 kFeatureFixedPushMkdir,
1181 kFeatureApex,
1182 kFeatureAbb,
1183 kFeatureFixedPushSymlinkTimestamp,
Alex Buynytskyy05626c12019-02-21 14:22:51 -08001184 kFeatureAbbExec,
Josh Gao8c2198c2019-07-11 14:15:32 -07001185 kFeatureRemountShell,
Josh Gao50ab0a62020-03-04 19:34:08 -08001186 kFeatureSendRecv2,
1187 kFeatureSendRecv2Brotli,
Josh Gao919b70c2018-11-08 22:39:43 -08001188 // Increment ADB_SERVER_VERSION when adding a feature that adbd needs
1189 // to know about. Otherwise, the client can be stuck running an old
1190 // version of the server even after upgrading their copy of adb.
1191 // (http://b/24370690)
David Pursell4e2fd362015-09-22 10:43:08 -07001192 };
1193
1194 return *features;
1195}
1196
1197std::string FeatureSetToString(const FeatureSet& features) {
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001198 return android::base::Join(features, ',');
David Pursell4e2fd362015-09-22 10:43:08 -07001199}
1200
1201FeatureSet StringToFeatureSet(const std::string& features_string) {
David Purselld2b588e2015-09-25 13:04:21 -07001202 if (features_string.empty()) {
1203 return FeatureSet();
1204 }
1205
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001206 auto names = android::base::Split(features_string, ",");
David Pursell4e2fd362015-09-22 10:43:08 -07001207 return FeatureSet(names.begin(), names.end());
Dan Albert1792c232015-05-18 13:06:53 -07001208}
1209
David Pursell70ef7b42015-09-30 13:35:42 -07001210bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001211 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell70ef7b42015-09-30 13:35:42 -07001212}
1213
Dan Albert1792c232015-05-18 13:06:53 -07001214bool atransport::has_feature(const std::string& feature) const {
1215 return features_.count(feature) > 0;
1216}
1217
David Pursell4e2fd362015-09-22 10:43:08 -07001218void atransport::SetFeatures(const std::string& features_string) {
1219 features_ = StringToFeatureSet(features_string);
Dan Albert1792c232015-05-18 13:06:53 -07001220}
1221
Yabin Cuib3298242015-08-28 15:09:44 -07001222void atransport::AddDisconnect(adisconnect* disconnect) {
1223 disconnects_.push_back(disconnect);
1224}
1225
1226void atransport::RemoveDisconnect(adisconnect* disconnect) {
1227 disconnects_.remove(disconnect);
1228}
1229
1230void atransport::RunDisconnects() {
Elliott Hughes65fe2512015-10-07 15:59:35 -07001231 for (const auto& disconnect : disconnects_) {
Yabin Cuib3298242015-08-28 15:09:44 -07001232 disconnect->func(disconnect->opaque, this);
1233 }
1234 disconnects_.clear();
1235}
1236
David Pursell3f902aa2016-03-01 08:58:26 -08001237bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001238 if (!serial.empty()) {
David Pursell3f902aa2016-03-01 08:58:26 -08001239 if (target == serial) {
1240 return true;
1241 } else if (type == kTransportLocal) {
1242 // Local transports can match [tcp:|udp:]<hostname>[:port].
1243 const char* local_target_ptr = target.c_str();
1244
1245 // For fastboot compatibility, ignore protocol prefixes.
1246 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao1290fbf2016-11-22 14:32:34 -08001247 android::base::StartsWith(target, "udp:")) {
David Pursell3f902aa2016-03-01 08:58:26 -08001248 local_target_ptr += 4;
1249 }
1250
1251 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1252 std::string serial_host, error;
1253 int serial_port = -1;
Josh Gao1290fbf2016-11-22 14:32:34 -08001254 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursell3f902aa2016-03-01 08:58:26 -08001255 // |target| may omit the port to default to ours.
1256 std::string target_host;
1257 int target_port = serial_port;
1258 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1259 nullptr, &error) &&
Josh Gao1290fbf2016-11-22 14:32:34 -08001260 serial_host == target_host && serial_port == target_port) {
David Pursell3f902aa2016-03-01 08:58:26 -08001261 return true;
1262 }
1263 }
1264 }
1265 }
1266
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001267 return (target == devpath) || qual_match(target, "product:", product, false) ||
1268 qual_match(target, "model:", model, true) ||
1269 qual_match(target, "device:", device, false);
David Pursell3f902aa2016-03-01 08:58:26 -08001270}
1271
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001272void atransport::SetConnectionEstablished(bool success) {
1273 connection_waitable_->SetConnectionEstablished(success);
1274}
1275
Josh Gaofc2e56f2018-08-30 11:37:00 -07001276ReconnectResult atransport::Reconnect() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001277 return reconnect_(this);
1278}
1279
Elliott Hughese67f1f82015-04-30 17:32:03 -07001280#if ADB_HOST
1281
Josh Gaob122b172017-08-16 16:57:01 -07001282// We use newline as our delimiter, make sure to never output it.
1283static std::string sanitize(std::string str, bool alphanumeric) {
1284 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1285 : [](const char c) { return c == '\n'; };
1286 std::replace_if(str.begin(), str.end(), pred, '_');
1287 return str;
1288}
1289
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001290static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob122b172017-08-16 16:57:01 -07001291 bool alphanumeric) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001292 if (value.empty()) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001293 return;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001294 }
1295
Elliott Hughese67f1f82015-04-30 17:32:03 -07001296 *result += ' ';
1297 *result += key;
Josh Gaob122b172017-08-16 16:57:01 -07001298 *result += sanitize(value, alphanumeric);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001299}
1300
Josh Gao1290fbf2016-11-22 14:32:34 -08001301static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001302 std::string serial = t->serial;
1303 if (serial.empty()) {
Dan Albertd99d9022015-05-06 16:48:52 -07001304 serial = "(no serial number)";
Elliott Hughese67f1f82015-04-30 17:32:03 -07001305 }
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001306
1307 if (!long_listing) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001308 *result += serial;
1309 *result += '\t';
1310 *result += t->connection_state_name();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001311 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001312 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1313 t->connection_state_name().c_str());
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001314
Elliott Hughese67f1f82015-04-30 17:32:03 -07001315 append_transport_info(result, "", t->devpath, false);
1316 append_transport_info(result, "product:", t->product, false);
1317 append_transport_info(result, "model:", t->model, true);
1318 append_transport_info(result, "device:", t->device, false);
Josh Gaob122b172017-08-16 16:57:01 -07001319
1320 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1321 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1322 *result += " transport_id:";
1323 *result += std::to_string(t->id);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001324 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001325 *result += '\n';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001326}
1327
Elliott Hughese67f1f82015-04-30 17:32:03 -07001328std::string list_transports(bool long_listing) {
Josh Gao1db71af2017-08-17 13:50:51 -07001329 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov04398a92017-12-17 10:56:07 +00001330
1331 auto sorted_transport_list = transport_list;
1332 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1333 if (x->type != y->type) {
1334 return x->type < y->type;
1335 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001336 return x->serial < y->serial;
Artem Iglikov04398a92017-12-17 10:56:07 +00001337 });
1338
1339 std::string result;
1340 for (const auto& t : sorted_transport_list) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001341 append_transport(t, &result, long_listing);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001342 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001343 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001344}
1345
Josh Gao3705b342019-03-28 15:47:44 -07001346void close_usb_devices(std::function<bool(const atransport*)> predicate, bool reset) {
Josh Gao1db71af2017-08-17 13:50:51 -07001347 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao22d2b3e2016-10-27 14:01:08 -07001348 for (auto& t : transport_list) {
1349 if (predicate(t)) {
Josh Gao3705b342019-03-28 15:47:44 -07001350 if (reset) {
1351 t->Reset();
1352 } else {
1353 t->Kick();
1354 }
Josh Gao22d2b3e2016-10-27 14:01:08 -07001355 }
1356 }
1357}
1358
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001359/* hack for osx */
Josh Gao3705b342019-03-28 15:47:44 -07001360void close_usb_devices(bool reset) {
1361 close_usb_devices([](const atransport*) { return true; }, reset);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001362}
Josh Gao1290fbf2016-11-22 14:32:34 -08001363#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001364
Josh Gao362e6962018-08-08 16:20:14 -07001365bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
Joshua Duong5cf78682020-01-21 13:19:42 -08001366 atransport::ReconnectCallback reconnect, bool use_tls, int* error) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001367 atransport* t = new atransport(std::move(reconnect), kCsOffline);
Joshua Duong5cf78682020-01-21 13:19:42 -08001368 t->use_tls = use_tls;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +01001369
Josh Gao3b4de3c2018-08-02 13:58:24 -07001370 D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
Josh Gao56300c92018-07-25 17:21:49 -07001371 if (init_socket_transport(t, std::move(s), port, local) < 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001372 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001373 if (error) *error = errno;
1374 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001375 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001376
Josh Gao1db71af2017-08-17 13:50:51 -07001377 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes65fe2512015-10-07 15:59:35 -07001378 for (const auto& transport : pending_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001379 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001380 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001381 << " is already in pending_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001382 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001383 if (error) *error = EALREADY;
1384 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001385 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001386 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001387
Elliott Hughes65fe2512015-10-07 15:59:35 -07001388 for (const auto& transport : transport_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001389 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001390 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001391 << " is already in transport_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001392 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001393 if (error) *error = EALREADY;
1394 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001395 }
1396 }
1397
Josh Gao3b4de3c2018-08-02 13:58:24 -07001398 t->serial = std::move(serial);
Dan Albertc7915a32015-05-18 16:46:31 -07001399 pending_list.push_front(t);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001400
1401 lock.unlock();
Benoit Goby1c45ee92013-03-29 18:22:36 -07001402
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001403 auto waitable = t->connection_waitable();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001404 register_transport(t);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001405
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001406 if (local == 1) {
1407 // Do not wait for emulator transports.
Josh Gao362e6962018-08-08 16:20:14 -07001408 return true;
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001409 }
1410
Josh Gao362e6962018-08-08 16:20:14 -07001411 if (!waitable->WaitForConnection(std::chrono::seconds(10))) {
1412 if (error) *error = ETIMEDOUT;
1413 return false;
1414 }
1415
1416 if (t->GetConnectionState() == kCsUnauthorized) {
1417 if (error) *error = EPERM;
1418 return false;
1419 }
1420
1421 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001422}
1423
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001424#if ADB_HOST
Josh Gao1290fbf2016-11-22 14:32:34 -08001425atransport* find_transport(const char* serial) {
Dan Albertc7915a32015-05-18 16:46:31 -07001426 atransport* result = nullptr;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001427
Josh Gao1db71af2017-08-17 13:50:51 -07001428 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001429 for (auto& t : transport_list) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001430 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001431 result = t;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001432 break;
1433 }
Dan Albertc7915a32015-05-18 16:46:31 -07001434 }
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001435
Dan Albertc7915a32015-05-18 16:46:31 -07001436 return result;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001437}
1438
Yabin Cuif4b99282015-08-27 12:03:11 -07001439void kick_all_tcp_devices() {
Josh Gao1db71af2017-08-17 13:50:51 -07001440 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001441 for (auto& t : transport_list) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001442 if (t->IsTcpDevice()) {
Yabin Cuid6ab3c22015-08-31 11:50:24 -07001443 // Kicking breaks the read_transport thread of this transport out of any read, then
1444 // the read_transport thread will notify the main thread to make this transport
1445 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cuif4b99282015-08-27 12:03:11 -07001446 // Finally, this transport will be closed and freed in the main thread.
Yabin Cui7f274902016-04-18 11:22:34 -07001447 t->Kick();
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001448 }
Dan Albertc7915a32015-05-18 16:46:31 -07001449 }
Josh Gao902dace2018-08-10 14:44:54 -07001450#if ADB_HOST
1451 reconnect_handler.CheckForKicked();
1452#endif
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001453}
1454
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001455#endif
1456
Josh Gao27831222020-03-27 18:09:56 -07001457#if ADB_HOST
Josh Gao1290fbf2016-11-22 14:32:34 -08001458void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1459 unsigned writeable) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001460 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertc7915a32015-05-18 16:46:31 -07001461
Josh Gao1290fbf2016-11-22 14:32:34 -08001462 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cuib5e11412017-03-10 16:01:01 -08001463 init_usb_transport(t, usb);
Josh Gao1290fbf2016-11-22 14:32:34 -08001464 if (serial) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001465 t->serial = serial;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001466 }
Dan Albertc7915a32015-05-18 16:46:31 -07001467
1468 if (devpath) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001469 t->devpath = devpath;
Scott Andersone109d262012-04-20 11:21:14 -07001470 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001471
Josh Gao0cd3ae12016-09-21 12:37:10 -07001472 {
Josh Gao1db71af2017-08-17 13:50:51 -07001473 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001474 pending_list.push_front(t);
1475 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001476
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001477 register_transport(t);
1478}
Josh Gao27831222020-03-27 18:09:56 -07001479#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001480
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