blob: be440e2e6ddfafc66eeeaabc274d1b7efefb7929 [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";
Todd Kennedy51c05ec2015-11-10 00:03:25 +000085
Luis Hector Chavez56fe7532018-04-17 14:25:04 -070086namespace {
87
Josh Gaodef91c02018-07-31 18:28:32 -070088#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070089// Tracks and handles atransport*s that are attempting reconnection.
90class ReconnectHandler {
91 public:
92 ReconnectHandler() = default;
93 ~ReconnectHandler() = default;
94
95 // Starts the ReconnectHandler thread.
96 void Start();
97
98 // Requests the ReconnectHandler thread to stop.
99 void Stop();
100
101 // Adds the atransport* to the queue of reconnect attempts.
102 void TrackTransport(atransport* transport);
103
Josh Gao902dace2018-08-10 14:44:54 -0700104 // Wake up the ReconnectHandler thread to have it check for kicked transports.
105 void CheckForKicked();
106
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700107 private:
108 // The main thread loop.
109 void Run();
110
111 // Tracks a reconnection attempt.
112 struct ReconnectAttempt {
113 atransport* transport;
Josh Gao95af6412018-07-30 18:51:55 -0700114 std::chrono::steady_clock::time_point reconnect_time;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700115 size_t attempts_left;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700116
117 bool operator<(const ReconnectAttempt& rhs) const {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700118 if (reconnect_time == rhs.reconnect_time) {
119 return reinterpret_cast<uintptr_t>(transport) <
120 reinterpret_cast<uintptr_t>(rhs.transport);
121 }
122 return reconnect_time < rhs.reconnect_time;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700123 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700124 };
125
126 // Only retry for up to one minute.
Josh Gaoe445a6d2018-07-31 14:12:59 -0700127 static constexpr const std::chrono::seconds kDefaultTimeout = 10s;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700128 static constexpr const size_t kMaxAttempts = 6;
129
130 // Protects all members.
131 std::mutex reconnect_mutex_;
132 bool running_ GUARDED_BY(reconnect_mutex_) = true;
133 std::thread handler_thread_;
134 std::condition_variable reconnect_cv_;
Josh Gao8a40c8a2018-08-10 14:28:24 -0700135 std::set<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700136
137 DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
138};
139
140void ReconnectHandler::Start() {
141 check_main_thread();
142 handler_thread_ = std::thread(&ReconnectHandler::Run, this);
143}
144
145void ReconnectHandler::Stop() {
146 check_main_thread();
147 {
148 std::lock_guard<std::mutex> lock(reconnect_mutex_);
149 running_ = false;
150 }
151 reconnect_cv_.notify_one();
152 handler_thread_.join();
153
154 // Drain the queue to free all resources.
155 std::lock_guard<std::mutex> lock(reconnect_mutex_);
156 while (!reconnect_queue_.empty()) {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700157 ReconnectAttempt attempt = *reconnect_queue_.begin();
158 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700159 remove_transport(attempt.transport);
160 }
161}
162
163void ReconnectHandler::TrackTransport(atransport* transport) {
164 check_main_thread();
165 {
166 std::lock_guard<std::mutex> lock(reconnect_mutex_);
167 if (!running_) return;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700168 // Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
169 auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
170 reconnect_queue_.emplace(
171 ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700172 }
173 reconnect_cv_.notify_one();
174}
175
Josh Gao902dace2018-08-10 14:44:54 -0700176void ReconnectHandler::CheckForKicked() {
177 reconnect_cv_.notify_one();
178}
179
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700180void ReconnectHandler::Run() {
181 while (true) {
182 ReconnectAttempt attempt;
183 {
184 std::unique_lock<std::mutex> lock(reconnect_mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800185 ScopedLockAssertion assume_lock(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700186
Josh Gao95af6412018-07-30 18:51:55 -0700187 if (!reconnect_queue_.empty()) {
188 // FIXME: libstdc++ (used on Windows) implements condition_variable with
189 // system_clock as its clock, so we're probably hosed if the clock changes,
190 // even if we use steady_clock throughout. This problem goes away once we
191 // switch to libc++.
Josh Gao8a40c8a2018-08-10 14:28:24 -0700192 reconnect_cv_.wait_until(lock, reconnect_queue_.begin()->reconnect_time);
Josh Gao95af6412018-07-30 18:51:55 -0700193 } else {
194 reconnect_cv_.wait(lock);
195 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700196
197 if (!running_) return;
Josh Gao902dace2018-08-10 14:44:54 -0700198
199 // Scan the whole list for kicked transports, so that we immediately handle an explicit
200 // disconnect request.
201 bool kicked = false;
202 for (auto it = reconnect_queue_.begin(); it != reconnect_queue_.end();) {
203 if (it->transport->kicked()) {
204 D("transport %s was kicked. giving up on it.", it->transport->serial.c_str());
205 remove_transport(it->transport);
206 it = reconnect_queue_.erase(it);
207 } else {
208 ++it;
209 }
210 kicked = true;
211 }
212
Josh Gao95af6412018-07-30 18:51:55 -0700213 if (reconnect_queue_.empty()) continue;
214
Josh Gao902dace2018-08-10 14:44:54 -0700215 // Go back to sleep if we either woke up spuriously, or we were woken up to remove
216 // a kicked transport, and the first transport isn't ready for reconnection yet.
Josh Gao95af6412018-07-30 18:51:55 -0700217 auto now = std::chrono::steady_clock::now();
Josh Gao8a40c8a2018-08-10 14:28:24 -0700218 if (reconnect_queue_.begin()->reconnect_time > now) {
Josh Gao95af6412018-07-30 18:51:55 -0700219 continue;
220 }
221
Josh Gao8a40c8a2018-08-10 14:28:24 -0700222 attempt = *reconnect_queue_.begin();
223 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700224 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700225 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700226
Josh Gaofc2e56f2018-08-30 11:37:00 -0700227 switch (attempt.transport->Reconnect()) {
228 case ReconnectResult::Retry: {
229 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
230 if (attempt.attempts_left == 0) {
231 D("transport %s exceeded the number of retry attempts. giving up on it.",
232 attempt.transport->serial.c_str());
233 remove_transport(attempt.transport);
234 continue;
235 }
236
237 std::lock_guard<std::mutex> lock(reconnect_mutex_);
238 reconnect_queue_.emplace(ReconnectAttempt{
239 attempt.transport,
240 std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
241 attempt.attempts_left - 1});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700242 continue;
243 }
244
Josh Gaofc2e56f2018-08-30 11:37:00 -0700245 case ReconnectResult::Success:
246 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
247 register_transport(attempt.transport);
248 continue;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700249
Josh Gaofc2e56f2018-08-30 11:37:00 -0700250 case ReconnectResult::Abort:
251 D("cancelling reconnection attempt to %s.", attempt.transport->serial.c_str());
252 remove_transport(attempt.transport);
253 continue;
254 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700255 }
256}
257
258static auto& reconnect_handler = *new ReconnectHandler();
259
Josh Gaodef91c02018-07-31 18:28:32 -0700260#endif
261
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700262} // namespace
263
Josh Gaob122b172017-08-16 16:57:01 -0700264TransportId NextTransportId() {
265 static std::atomic<TransportId> next(1);
266 return next++;
267}
268
Josh Gao3705b342019-03-28 15:47:44 -0700269void Connection::Reset() {
270 LOG(INFO) << "Connection::Reset(): stopping";
271 Stop();
272}
273
Josh Gao0bbf69c2018-02-16 13:24:58 -0800274BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
275 : underlying_(std::move(connection)) {}
276
277BlockingConnectionAdapter::~BlockingConnectionAdapter() {
278 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
279 Stop();
280}
281
282void BlockingConnectionAdapter::Start() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700283 std::lock_guard<std::mutex> lock(mutex_);
284 if (started_) {
285 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
286 << "): started multiple times";
287 }
288
Joshua Duong5cf78682020-01-21 13:19:42 -0800289 StartReadThread();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800290
291 write_thread_ = std::thread([this]() {
292 LOG(INFO) << this->transport_name_ << ": write thread spawning";
293 while (true) {
294 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800295 ScopedLockAssertion assume_locked(mutex_);
Josh Gaoc251ec52018-04-03 12:55:18 -0700296 cv_.wait(lock, [this]() REQUIRES(mutex_) {
297 return this->stopped_ || !this->write_queue_.empty();
298 });
299
Josh Gao0bbf69c2018-02-16 13:24:58 -0800300 if (this->stopped_) {
301 return;
302 }
303
304 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
305 this->write_queue_.pop_front();
306 lock.unlock();
307
308 if (!this->underlying_->Write(packet.get())) {
309 break;
310 }
311 }
312 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
313 });
Josh Gaoc251ec52018-04-03 12:55:18 -0700314
315 started_ = true;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800316}
317
Joshua Duong5cf78682020-01-21 13:19:42 -0800318void BlockingConnectionAdapter::StartReadThread() {
319 read_thread_ = std::thread([this]() {
320 LOG(INFO) << this->transport_name_ << ": read thread spawning";
321 while (true) {
322 auto packet = std::make_unique<apacket>();
323 if (!underlying_->Read(packet.get())) {
324 PLOG(INFO) << this->transport_name_ << ": read failed";
325 break;
326 }
327
328 bool got_stls_cmd = false;
329 if (packet->msg.command == A_STLS) {
330 got_stls_cmd = true;
331 }
332
333 read_callback_(this, std::move(packet));
334
335 // If we received the STLS packet, we are about to perform the TLS
336 // handshake. So this read thread must stop and resume after the
337 // handshake completes otherwise this will interfere in the process.
338 if (got_stls_cmd) {
339 LOG(INFO) << this->transport_name_
340 << ": Received STLS packet. Stopping read thread.";
341 return;
342 }
343 }
344 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
345 });
346}
347
348bool BlockingConnectionAdapter::DoTlsHandshake(RSA* key, std::string* auth_key) {
349 std::lock_guard<std::mutex> lock(mutex_);
350 if (read_thread_.joinable()) {
351 read_thread_.join();
352 }
353 bool success = this->underlying_->DoTlsHandshake(key, auth_key);
354 StartReadThread();
355 return success;
356}
357
Josh Gao3705b342019-03-28 15:47:44 -0700358void BlockingConnectionAdapter::Reset() {
359 {
360 std::lock_guard<std::mutex> lock(mutex_);
361 if (!started_) {
362 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
363 return;
364 }
365
366 if (stopped_) {
367 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
368 << "): already stopped";
369 return;
370 }
371 }
372
373 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): resetting";
374 this->underlying_->Reset();
375 Stop();
376}
377
Josh Gao0bbf69c2018-02-16 13:24:58 -0800378void BlockingConnectionAdapter::Stop() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700379 {
380 std::lock_guard<std::mutex> lock(mutex_);
381 if (!started_) {
382 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
383 return;
384 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800385
Josh Gaoc251ec52018-04-03 12:55:18 -0700386 if (stopped_) {
387 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
388 << "): already stopped";
389 return;
390 }
391
392 stopped_ = true;
393 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800394
395 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
396
397 this->underlying_->Close();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800398 this->cv_.notify_one();
Josh Gaoc251ec52018-04-03 12:55:18 -0700399
400 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
401 std::thread read_thread;
402 std::thread write_thread;
403
404 {
405 std::lock_guard<std::mutex> lock(mutex_);
406 read_thread = std::move(read_thread_);
407 write_thread = std::move(write_thread_);
408 }
409
410 read_thread.join();
411 write_thread.join();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800412
413 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
414 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
415}
416
417bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
418 {
Josh Gaoc251ec52018-04-03 12:55:18 -0700419 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800420 write_queue_.emplace_back(std::move(packet));
421 }
422
423 cv_.notify_one();
424 return true;
425}
426
Joshua Duong5cf78682020-01-21 13:19:42 -0800427FdConnection::FdConnection(unique_fd fd) : fd_(std::move(fd)) {}
428
429FdConnection::~FdConnection() {}
430
431bool FdConnection::DispatchRead(void* buf, size_t len) {
432 if (tls_ != nullptr) {
433 // The TlsConnection doesn't allow 0 byte reads
434 if (len == 0) {
435 return true;
436 }
437 return tls_->ReadFully(buf, len);
438 }
439
440 return ReadFdExactly(fd_.get(), buf, len);
441}
442
443bool FdConnection::DispatchWrite(void* buf, size_t len) {
444 if (tls_ != nullptr) {
445 // The TlsConnection doesn't allow 0 byte writes
446 if (len == 0) {
447 return true;
448 }
449 return tls_->WriteFully(std::string_view(reinterpret_cast<const char*>(buf), len));
450 }
451
452 return WriteFdExactly(fd_.get(), buf, len);
453}
454
Josh Gaob800d882018-01-28 20:32:46 -0800455bool FdConnection::Read(apacket* packet) {
Joshua Duong5cf78682020-01-21 13:19:42 -0800456 if (!DispatchRead(&packet->msg, sizeof(amessage))) {
Josh Gaob800d882018-01-28 20:32:46 -0800457 D("remote local: read terminated (message)");
458 return false;
459 }
460
Josh Gaof571fcb2018-02-05 18:49:10 -0800461 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gao5caaebd2018-02-02 14:38:04 -0800462 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
463 return false;
464 }
465
Josh Gaof571fcb2018-02-05 18:49:10 -0800466 packet->payload.resize(packet->msg.data_length);
467
Joshua Duong5cf78682020-01-21 13:19:42 -0800468 if (!DispatchRead(&packet->payload[0], packet->payload.size())) {
Josh Gaob800d882018-01-28 20:32:46 -0800469 D("remote local: terminated (data)");
470 return false;
471 }
472
473 return true;
474}
475
476bool FdConnection::Write(apacket* packet) {
Joshua Duong5cf78682020-01-21 13:19:42 -0800477 if (!DispatchWrite(&packet->msg, sizeof(packet->msg))) {
Josh Gaob800d882018-01-28 20:32:46 -0800478 D("remote local: write terminated");
479 return false;
480 }
481
Josh Gaof571fcb2018-02-05 18:49:10 -0800482 if (packet->msg.data_length) {
Joshua Duong5cf78682020-01-21 13:19:42 -0800483 if (!DispatchWrite(&packet->payload[0], packet->msg.data_length)) {
Josh Gaof571fcb2018-02-05 18:49:10 -0800484 D("remote local: write terminated");
485 return false;
486 }
487 }
488
Josh Gaob800d882018-01-28 20:32:46 -0800489 return true;
490}
491
Joshua Duong5cf78682020-01-21 13:19:42 -0800492bool FdConnection::DoTlsHandshake(RSA* key, std::string* auth_key) {
493 bssl::UniquePtr<EVP_PKEY> evp_pkey(EVP_PKEY_new());
494 if (!EVP_PKEY_set1_RSA(evp_pkey.get(), key)) {
495 LOG(ERROR) << "EVP_PKEY_set1_RSA failed";
496 return false;
497 }
498 auto x509 = GenerateX509Certificate(evp_pkey.get());
499 auto x509_str = X509ToPEMString(x509.get());
500 auto evp_str = Key::ToPEMString(evp_pkey.get());
Joshua Duong1b273ed2020-03-24 09:50:59 -0700501#ifdef _WIN32
502 int osh = cast_handle_to_int(adb_get_os_handle(fd_));
503#else
504 int osh = adb_get_os_handle(fd_);
505#endif
506
Joshua Duong5cf78682020-01-21 13:19:42 -0800507#if ADB_HOST
508 tls_ = TlsConnection::Create(TlsConnection::Role::Client,
509#else
510 tls_ = TlsConnection::Create(TlsConnection::Role::Server,
511#endif
Joshua Duong1b273ed2020-03-24 09:50:59 -0700512 x509_str, evp_str, osh);
Joshua Duong5cf78682020-01-21 13:19:42 -0800513 CHECK(tls_);
514#if ADB_HOST
515 // TLS 1.3 gives the client no message if the server rejected the
516 // certificate. This will enable a check in the tls connection to check
517 // whether the client certificate got rejected. Note that this assumes
518 // that, on handshake success, the server speaks first.
519 tls_->EnableClientPostHandshakeCheck(true);
520 // Add callback to set the certificate when server issues the
521 // CertificateRequest.
522 tls_->SetCertificateCallback(adb_tls_set_certificate);
523 // Allow any server certificate
524 tls_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
525#else
526 // Add callback to check certificate against a list of known public keys
527 tls_->SetCertVerifyCallback(
528 [auth_key](X509_STORE_CTX* ctx) { return adbd_tls_verify_cert(ctx, auth_key); });
529 // Add the list of allowed client CA issuers
530 auto ca_list = adbd_tls_client_ca_list();
531 tls_->SetClientCAList(ca_list.get());
532#endif
533
534 auto err = tls_->DoHandshake();
535 if (err == TlsError::Success) {
536 return true;
537 }
538
539 tls_.reset();
540 return false;
541}
542
Josh Gaob800d882018-01-28 20:32:46 -0800543void FdConnection::Close() {
544 adb_shutdown(fd_.get());
545 fd_.reset();
546}
547
Josh Gao06d61d42016-10-06 13:31:44 -0700548void send_packet(apacket* p, atransport* t) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800549 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayde471942017-12-07 11:40:00 -0800550 // compute a checksum for connection/auth packets for compatibility reasons
551 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
552 p->msg.data_check = 0;
553 } else {
554 p->msg.data_check = calculate_apacket_checksum(p);
555 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800556
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700557 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800558
Yi Kongaed415c2018-07-13 18:15:16 -0700559 if (t == nullptr) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700560 LOG(FATAL) << "Transport is null";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800561 }
562
Josh Gao0bbf69c2018-02-16 13:24:58 -0800563 if (t->Write(p) != 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700564 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800565 t->Kick();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800566 }
567}
568
Josh Gao3705b342019-03-28 15:47:44 -0700569void kick_transport(atransport* t, bool reset) {
Josh Gao1db71af2017-08-17 13:50:51 -0700570 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui1f4ec192016-04-05 13:50:44 -0700571 // As kick_transport() can be called from threads without guarantee that t is valid,
572 // check if the transport is in transport_list first.
Josh Gaob122b172017-08-16 16:57:01 -0700573 //
574 // TODO(jmgao): WTF? Is this actually true?
Yabin Cui1f4ec192016-04-05 13:50:44 -0700575 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Josh Gao3705b342019-03-28 15:47:44 -0700576 if (reset) {
577 t->Reset();
578 } else {
579 t->Kick();
580 }
Yabin Cui1f4ec192016-04-05 13:50:44 -0700581 }
Josh Gao902dace2018-08-10 14:44:54 -0700582
583#if ADB_HOST
584 reconnect_handler.CheckForKicked();
585#endif
Yabin Cuif4b99282015-08-27 12:03:11 -0700586}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800587
588static int transport_registration_send = -1;
589static int transport_registration_recv = -1;
Josh Gao71f775a2018-05-14 11:14:33 -0700590static fdevent* transport_registration_fde;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800591
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800592#if ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800593
594/* this adds support required by the 'track-devices' service.
595 * this is used to send the content of "list_transport" to any
596 * number of client connections that want it through a single
597 * live TCP connection
598 */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800599struct device_tracker {
Josh Gao1290fbf2016-11-22 14:32:34 -0800600 asocket socket;
Josh Gaoe0361d12018-02-12 17:24:00 -0800601 bool update_needed = false;
602 bool long_output = false;
603 device_tracker* next = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800604};
605
606/* linked list of all device trackers */
Josh Gao1290fbf2016-11-22 14:32:34 -0800607static device_tracker* device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800608
Josh Gao1290fbf2016-11-22 14:32:34 -0800609static void device_tracker_remove(device_tracker* tracker) {
610 device_tracker** pnode = &device_tracker_list;
611 device_tracker* node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800612
Josh Gao1db71af2017-08-17 13:50:51 -0700613 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800614 while (node) {
615 if (node == tracker) {
616 *pnode = node->next;
617 break;
618 }
619 pnode = &node->next;
Josh Gao1290fbf2016-11-22 14:32:34 -0800620 node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800621 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800622}
623
Josh Gao1290fbf2016-11-22 14:32:34 -0800624static void device_tracker_close(asocket* socket) {
625 device_tracker* tracker = (device_tracker*)socket;
626 asocket* peer = socket->peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800627
Josh Gao1290fbf2016-11-22 14:32:34 -0800628 D("device tracker %p removed", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800629 if (peer) {
Yi Kongaed415c2018-07-13 18:15:16 -0700630 peer->peer = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800631 peer->close(peer);
632 }
633 device_tracker_remove(tracker);
Josh Gaoe0361d12018-02-12 17:24:00 -0800634 delete tracker;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800635}
636
Josh Gao1ce99572018-03-07 16:52:28 -0800637static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800638 /* you can't read from a device tracker, close immediately */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800639 device_tracker_close(socket);
640 return -1;
641}
642
Elliott Hughese67f1f82015-04-30 17:32:03 -0700643static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700644 asocket* peer = tracker->socket.peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800645
Josh Gao1ce99572018-03-07 16:52:28 -0800646 apacket::payload_type data;
Josh Gao27cb7dc2018-02-01 13:17:50 -0800647 data.resize(4 + string.size());
648 char buf[5];
649 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
650 memcpy(&data[0], buf, 4);
651 memcpy(&data[4], string.data(), string.size());
652 return peer->enqueue(peer, std::move(data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800653}
654
Elliott Hughese67f1f82015-04-30 17:32:03 -0700655static void device_tracker_ready(asocket* socket) {
656 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800657
Elliott Hughese67f1f82015-04-30 17:32:03 -0700658 // We want to send the device list when the tracker connects
659 // for the first time, even if no update occurred.
Josh Gaob0c18022017-08-14 18:57:54 -0700660 if (tracker->update_needed) {
661 tracker->update_needed = false;
Elliott Hughesfc2f5f62019-07-31 14:13:57 -0700662 device_tracker_send(tracker, list_transports(tracker->long_output));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800663 }
664}
665
Josh Gaob0c18022017-08-14 18:57:54 -0700666asocket* create_device_tracker(bool long_output) {
Josh Gaoe0361d12018-02-12 17:24:00 -0800667 device_tracker* tracker = new device_tracker();
Elliott Hughes4679a392018-10-19 13:59:44 -0700668 if (tracker == nullptr) LOG(FATAL) << "cannot allocate device tracker";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800669
Josh Gao1290fbf2016-11-22 14:32:34 -0800670 D("device tracker %p created", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800671
672 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao1290fbf2016-11-22 14:32:34 -0800673 tracker->socket.ready = device_tracker_ready;
674 tracker->socket.close = device_tracker_close;
Josh Gaob0c18022017-08-14 18:57:54 -0700675 tracker->update_needed = true;
676 tracker->long_output = long_output;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800677
Josh Gao1290fbf2016-11-22 14:32:34 -0800678 tracker->next = device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800679 device_tracker_list = tracker;
680
681 return &tracker->socket;
682}
683
Josh Gaofd713e52017-05-03 22:37:10 -0700684// Check if all of the USB transports are connected.
685bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gao1db71af2017-08-17 13:50:51 -0700686 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaofd713e52017-05-03 22:37:10 -0700687 for (const auto& t : transport_list) {
688 if (!fn(t)) {
689 return false;
690 }
691 }
692 for (const auto& t : pending_list) {
693 if (!fn(t)) {
694 return false;
695 }
696 }
697 return true;
698}
699
Elliott Hughese67f1f82015-04-30 17:32:03 -0700700// Call this function each time the transport list has changed.
701void update_transports() {
Josh Gaofd713e52017-05-03 22:37:10 -0700702 update_transport_status();
703
704 // Notify `adb track-devices` clients.
Elliott Hughese67f1f82015-04-30 17:32:03 -0700705 device_tracker* tracker = device_tracker_list;
706 while (tracker != nullptr) {
707 device_tracker* next = tracker->next;
708 // This may destroy the tracker if the connection is closed.
Elliott Hughesfc2f5f62019-07-31 14:13:57 -0700709 device_tracker_send(tracker, list_transports(tracker->long_output));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800710 tracker = next;
711 }
712}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700713
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800714#else
Elliott Hughese67f1f82015-04-30 17:32:03 -0700715
716void update_transports() {
717 // Nothing to do on the device side.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800718}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700719
Josh Gao1290fbf2016-11-22 14:32:34 -0800720#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800721
Josh Gao1290fbf2016-11-22 14:32:34 -0800722struct tmsg {
723 atransport* transport;
724 int action;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800725};
726
Josh Gao1290fbf2016-11-22 14:32:34 -0800727static int transport_read_action(int fd, struct tmsg* m) {
728 char* p = (char*)m;
729 int len = sizeof(*m);
730 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800731
Josh Gao1290fbf2016-11-22 14:32:34 -0800732 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800733 r = adb_read(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800734 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800735 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800736 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800737 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700738 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800739 return -1;
740 }
741 }
742 return 0;
743}
744
Josh Gao1290fbf2016-11-22 14:32:34 -0800745static int transport_write_action(int fd, struct tmsg* m) {
746 char* p = (char*)m;
747 int len = sizeof(*m);
748 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800749
Josh Gao1290fbf2016-11-22 14:32:34 -0800750 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800751 r = adb_write(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800752 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800753 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800754 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800755 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700756 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800757 return -1;
758 }
759 }
760 return 0;
761}
762
Josh Gao0bbf69c2018-02-16 13:24:58 -0800763static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800764 tmsg m;
Josh Gao1290fbf2016-11-22 14:32:34 -0800765 atransport* t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800766
Josh Gao1290fbf2016-11-22 14:32:34 -0800767 if (!(ev & FDE_READ)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800768 return;
769 }
770
Josh Gao1290fbf2016-11-22 14:32:34 -0800771 if (transport_read_action(_fd, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700772 PLOG(FATAL) << "cannot read transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800773 }
774
775 t = m.transport;
776
Dan Albert1792c232015-05-18 13:06:53 -0700777 if (m.action == 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700778 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800779
Josh Gao0cd3ae12016-09-21 12:37:10 -0700780 {
Josh Gao1db71af2017-08-17 13:50:51 -0700781 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700782 transport_list.remove(t);
783 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800784
Dan Albertc7915a32015-05-18 16:46:31 -0700785 delete t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800786
787 update_transports();
788 return;
789 }
790
Mike Lockwood0927bf92009-08-08 12:37:44 -0400791 /* don't create transport threads for inaccessible devices */
Yabin Cuib5e11412017-03-10 16:01:01 -0800792 if (t->GetConnectionState() != kCsNoPerm) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700793 // The connection gets a reference to the atransport. It will release it
794 // upon a read/write error.
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700795 t->connection()->SetTransportName(t->serial_name());
796 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao0bbf69c2018-02-16 13:24:58 -0800797 if (!check_header(p.get(), t)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700798 D("%s: remote read: bad header", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800799 return false;
800 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800801
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700802 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "from remote", p.get());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800803 apacket* packet = p.release();
Mike Lockwood0927bf92009-08-08 12:37:44 -0400804
Josh Gao0bbf69c2018-02-16 13:24:58 -0800805 // TODO: Does this need to run on the main thread?
806 fdevent_run_on_main_thread([packet, t]() { handle_packet(packet, t); });
807 return true;
808 });
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700809 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700810 LOG(INFO) << t->serial_name() << ": connection terminated: " << error;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800811 fdevent_run_on_main_thread([t]() {
812 handle_offline(t);
Josh Gao9a8366b2019-12-09 13:45:31 -0800813 transport_destroy(t);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800814 });
815 });
Mike Lockwood0927bf92009-08-08 12:37:44 -0400816
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700817 t->connection()->Start();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800818#if ADB_HOST
819 send_connect(t);
820#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800821 }
822
Josh Gao0cd3ae12016-09-21 12:37:10 -0700823 {
Josh Gao1db71af2017-08-17 13:50:51 -0700824 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700825 auto it = std::find(pending_list.begin(), pending_list.end(), t);
826 if (it != pending_list.end()) {
827 pending_list.remove(t);
828 transport_list.push_front(t);
829 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700830 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800831
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800832 update_transports();
833}
834
Josh Gaodef91c02018-07-31 18:28:32 -0700835#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700836void init_reconnect_handler(void) {
837 reconnect_handler.Start();
838}
Josh Gaodef91c02018-07-31 18:28:32 -0700839#endif
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700840
Josh Gao1290fbf2016-11-22 14:32:34 -0800841void init_transport_registration(void) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800842 int s[2];
843
Josh Gao1290fbf2016-11-22 14:32:34 -0800844 if (adb_socketpair(s)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700845 PLOG(FATAL) << "cannot open transport registration socketpair";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800846 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700847 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800848
849 transport_registration_send = s[0];
850 transport_registration_recv = s[1];
851
Josh Gao71f775a2018-05-14 11:14:33 -0700852 transport_registration_fde =
Yi Kongaed415c2018-07-13 18:15:16 -0700853 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao71f775a2018-05-14 11:14:33 -0700854 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao01b7bc42017-05-09 13:43:35 -0700855}
856
857void kick_all_transports() {
Josh Gaodef91c02018-07-31 18:28:32 -0700858#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700859 reconnect_handler.Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700860#endif
Josh Gao01b7bc42017-05-09 13:43:35 -0700861 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gao1db71af2017-08-17 13:50:51 -0700862 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao01b7bc42017-05-09 13:43:35 -0700863 for (auto t : transport_list) {
864 t->Kick();
865 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800866}
867
Joshua Duong5cf78682020-01-21 13:19:42 -0800868void kick_all_tcp_tls_transports() {
869 std::lock_guard<std::recursive_mutex> lock(transport_lock);
870 for (auto t : transport_list) {
871 if (t->IsTcpDevice() && t->use_tls) {
872 t->Kick();
873 }
874 }
875}
876
877#if !ADB_HOST
878void kick_all_transports_by_auth_key(std::string_view auth_key) {
879 std::lock_guard<std::recursive_mutex> lock(transport_lock);
880 for (auto t : transport_list) {
881 if (auth_key == t->auth_key) {
882 t->Kick();
883 }
884 }
885}
886#endif
887
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800888/* the fdevent select pump is single threaded */
Josh Gaoc51726c2018-10-11 16:33:05 -0700889void register_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800890 tmsg m;
891 m.transport = transport;
892 m.action = 1;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700893 D("transport: %s registered", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800894 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700895 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800896 }
897}
898
Josh Gao1290fbf2016-11-22 14:32:34 -0800899static void remove_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800900 tmsg m;
901 m.transport = transport;
902 m.action = 0;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700903 D("transport: %s removed", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800904 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700905 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800906 }
907}
908
Josh Gao9a8366b2019-12-09 13:45:31 -0800909static void transport_destroy(atransport* t) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700910 check_main_thread();
Yabin Cuif4b99282015-08-27 12:03:11 -0700911 CHECK(t != nullptr);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700912
Josh Gaoe48ecce2017-09-13 13:40:57 -0700913 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao9a8366b2019-12-09 13:45:31 -0800914 LOG(INFO) << "destroying transport " << t->serial_name();
915 t->connection()->Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700916#if ADB_HOST
Josh Gao9a8366b2019-12-09 13:45:31 -0800917 if (t->IsTcpDevice() && !t->kicked()) {
918 D("transport: %s destroy (attempting reconnection)", t->serial.c_str());
Josh Gao4414e4c2018-12-04 01:07:50 -0800919
Josh Gao9a8366b2019-12-09 13:45:31 -0800920 // We need to clear the transport's keys, so that on the next connection, it tries
921 // again from the beginning.
922 t->ResetKeys();
923 reconnect_handler.TrackTransport(t);
924 return;
925 }
Josh Gaodef91c02018-07-31 18:28:32 -0700926#endif
927
Josh Gao9a8366b2019-12-09 13:45:31 -0800928 D("transport: %s destroy (kicking and closing)", t->serial.c_str());
929 remove_transport(t);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800930}
931
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700932static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao1290fbf2016-11-22 14:32:34 -0800933 bool sanitize_qual) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700934 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
935 return qual.empty();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700936
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700937 if (qual.empty()) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700938
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700939 const char* ptr = to_test.c_str();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700940 if (prefix) {
941 while (*prefix) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700942 if (*prefix++ != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700943 }
944 }
945
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700946 for (char ch : qual) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800947 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700948 if (ch != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700949 }
950
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700951 /* Everything matched so far. Return true if *ptr is a NUL. */
952 return !*ptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700953}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800954
Josh Gaob122b172017-08-16 16:57:01 -0700955atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
956 bool* is_ambiguous, std::string* error_out,
957 bool accept_any_state) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700958 atransport* result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800959
Josh Gaob122b172017-08-16 16:57:01 -0700960 if (transport_id != 0) {
961 *error_out =
962 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
963 } else if (serial) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700964 *error_out = android::base::StringPrintf("device '%s' not found", serial);
965 } else if (type == kTransportLocal) {
966 *error_out = "no emulators found";
967 } else if (type == kTransportAny) {
968 *error_out = "no devices/emulators found";
969 } else {
970 *error_out = "no devices found";
971 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800972
Josh Gao1db71af2017-08-17 13:50:51 -0700973 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes8d28e192015-10-07 14:55:10 -0700974 for (const auto& t : transport_list) {
Yabin Cuib5e11412017-03-10 16:01:01 -0800975 if (t->GetConnectionState() == kCsNoPerm) {
David Purselld2acbd12015-12-02 15:14:31 -0800976 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwood37d31112009-08-08 13:53:16 -0400977 continue;
978 }
Mike Lockwood0927bf92009-08-08 12:37:44 -0400979
Josh Gaob122b172017-08-16 16:57:01 -0700980 if (transport_id) {
981 if (t->id == transport_id) {
982 result = t;
983 break;
984 }
985 } else if (serial) {
David Pursell3f902aa2016-03-01 08:58:26 -0800986 if (t->MatchesTarget(serial)) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700987 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700988 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700989 if (is_ambiguous) *is_ambiguous = true;
990 result = nullptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700991 break;
992 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800993 result = t;
Scott Andersone109d262012-04-20 11:21:14 -0700994 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800995 } else {
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700996 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800997 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700998 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700999 if (is_ambiguous) *is_ambiguous = true;
1000 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001001 break;
1002 }
1003 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001004 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001005 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -07001006 *error_out = "more than one emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -07001007 if (is_ambiguous) *is_ambiguous = true;
1008 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001009 break;
1010 }
1011 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001012 } else if (type == kTransportAny) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001013 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -07001014 *error_out = "more than one device/emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -07001015 if (is_ambiguous) *is_ambiguous = true;
1016 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001017 break;
1018 }
1019 result = t;
1020 }
1021 }
1022 }
Josh Gao0cd3ae12016-09-21 12:37:10 -07001023 lock.unlock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001024
Josh Gao704494b2018-05-04 16:04:49 -07001025 if (result && !accept_any_state) {
1026 // The caller requires an active transport.
1027 // Make sure that we're actually connected.
1028 ConnectionState state = result->GetConnectionState();
1029 switch (state) {
1030 case kCsConnecting:
1031 *error_out = "device still connecting";
1032 result = nullptr;
1033 break;
Benoit Goby77e8e582013-01-15 12:36:47 -08001034
Josh Gao704494b2018-05-04 16:04:49 -07001035 case kCsAuthorizing:
1036 *error_out = "device still authorizing";
1037 result = nullptr;
1038 break;
1039
1040 case kCsUnauthorized: {
1041 *error_out = "device unauthorized.\n";
1042 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
1043 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
1044 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
1045 *error_out += "\n";
1046 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
1047 *error_out += "Otherwise check for a confirmation dialog on your device.";
1048 result = nullptr;
1049 break;
1050 }
1051
1052 case kCsOffline:
1053 *error_out = "device offline";
1054 result = nullptr;
1055 break;
1056
1057 default:
1058 break;
1059 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001060 }
1061
1062 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -07001063 *error_out = "success";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001064 }
1065
1066 return result;
1067}
1068
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001069bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
1070 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -08001071 ScopedLockAssertion assume_locked(mutex_);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001072 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
1073 return connection_established_ready_;
1074 }) && connection_established_;
1075}
1076
1077void ConnectionWaitable::SetConnectionEstablished(bool success) {
1078 {
1079 std::lock_guard<std::mutex> lock(mutex_);
1080 if (connection_established_ready_) return;
1081 connection_established_ready_ = true;
1082 connection_established_ = success;
1083 D("connection established with %d", success);
1084 }
1085 cv_.notify_one();
1086}
1087
1088atransport::~atransport() {
1089 // If the connection callback had not been run before, run it now.
1090 SetConnectionEstablished(false);
1091}
1092
Yabin Cuib5e11412017-03-10 16:01:01 -08001093int atransport::Write(apacket* p) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -07001094 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cuib5e11412017-03-10 16:01:01 -08001095}
1096
Josh Gao3705b342019-03-28 15:47:44 -07001097void atransport::Reset() {
1098 if (!kicked_.exchange(true)) {
1099 LOG(INFO) << "resetting transport " << this << " " << this->serial;
1100 this->connection()->Reset();
1101 }
1102}
1103
Yabin Cui7f274902016-04-18 11:22:34 -07001104void atransport::Kick() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001105 if (!kicked_.exchange(true)) {
Josh Gao3705b342019-03-28 15:47:44 -07001106 LOG(INFO) << "kicking transport " << this << " " << this->serial;
Luis Hector Chavez9a388d52018-04-25 08:56:41 -07001107 this->connection()->Stop();
Yabin Cui7f274902016-04-18 11:22:34 -07001108 }
1109}
1110
Yabin Cuib5e11412017-03-10 16:01:01 -08001111ConnectionState atransport::GetConnectionState() const {
1112 return connection_state_;
1113}
1114
1115void atransport::SetConnectionState(ConnectionState state) {
1116 check_main_thread();
1117 connection_state_ = state;
1118}
1119
Luis Hector Chavez9a388d52018-04-25 08:56:41 -07001120void atransport::SetConnection(std::unique_ptr<Connection> connection) {
1121 std::lock_guard<std::mutex> lock(mutex_);
1122 connection_ = std::shared_ptr<Connection>(std::move(connection));
1123}
1124
Josh Gaoffbd3362018-02-28 14:44:23 -08001125std::string atransport::connection_state_name() const {
Yabin Cuib5e11412017-03-10 16:01:01 -08001126 ConnectionState state = GetConnectionState();
1127 switch (state) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001128 case kCsOffline:
1129 return "offline";
1130 case kCsBootloader:
1131 return "bootloader";
1132 case kCsDevice:
1133 return "device";
1134 case kCsHost:
1135 return "host";
1136 case kCsRecovery:
1137 return "recovery";
Tao Bao55d407e2019-04-07 23:24:03 -07001138 case kCsRescue:
1139 return "rescue";
Josh Gao1290fbf2016-11-22 14:32:34 -08001140 case kCsNoPerm:
1141 return UsbNoPermissionsShortHelpText();
1142 case kCsSideload:
1143 return "sideload";
1144 case kCsUnauthorized:
1145 return "unauthorized";
Josh Gao704494b2018-05-04 16:04:49 -07001146 case kCsAuthorizing:
1147 return "authorizing";
1148 case kCsConnecting:
1149 return "connecting";
Josh Gao1290fbf2016-11-22 14:32:34 -08001150 default:
1151 return "unknown";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001152 }
1153}
1154
Tamas Berghammer3d2904c2015-07-13 19:12:28 +01001155void atransport::update_version(int version, size_t payload) {
1156 protocol_version = std::min(version, A_VERSION);
1157 max_payload = std::min(payload, MAX_PAYLOAD);
1158}
1159
1160int atransport::get_protocol_version() const {
1161 return protocol_version;
1162}
1163
Joshua Duong5cf78682020-01-21 13:19:42 -08001164int atransport::get_tls_version() const {
1165 return tls_version;
1166}
1167
Tamas Berghammer3d2904c2015-07-13 19:12:28 +01001168size_t atransport::get_max_payload() const {
1169 return max_payload;
1170}
1171
Dan Albert1792c232015-05-18 13:06:53 -07001172const FeatureSet& supported_features() {
David Pursell4e2fd362015-09-22 10:43:08 -07001173 // Local static allocation to avoid global non-POD variables.
1174 static const FeatureSet* features = new FeatureSet{
Josh Gao7b1cb662019-02-20 13:01:40 -08001175 kFeatureShell2,
1176 kFeatureCmd,
1177 kFeatureStat2,
Josh Gao34a478f2019-08-07 14:23:17 -07001178 kFeatureLs2,
Josh Gao7b1cb662019-02-20 13:01:40 -08001179 kFeatureFixedPushMkdir,
1180 kFeatureApex,
1181 kFeatureAbb,
1182 kFeatureFixedPushSymlinkTimestamp,
Alex Buynytskyy05626c12019-02-21 14:22:51 -08001183 kFeatureAbbExec,
Josh Gao8c2198c2019-07-11 14:15:32 -07001184 kFeatureRemountShell,
Shukang Zhouf4ffae12020-02-13 17:01:39 -08001185 kFeatureTrackApp,
Josh Gao919b70c2018-11-08 22:39:43 -08001186 // Increment ADB_SERVER_VERSION when adding a feature that adbd needs
1187 // to know about. Otherwise, the client can be stuck running an old
1188 // version of the server even after upgrading their copy of adb.
1189 // (http://b/24370690)
David Pursell4e2fd362015-09-22 10:43:08 -07001190 };
1191
1192 return *features;
1193}
1194
1195std::string FeatureSetToString(const FeatureSet& features) {
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001196 return android::base::Join(features, ',');
David Pursell4e2fd362015-09-22 10:43:08 -07001197}
1198
1199FeatureSet StringToFeatureSet(const std::string& features_string) {
David Purselld2b588e2015-09-25 13:04:21 -07001200 if (features_string.empty()) {
1201 return FeatureSet();
1202 }
1203
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001204 auto names = android::base::Split(features_string, ",");
David Pursell4e2fd362015-09-22 10:43:08 -07001205 return FeatureSet(names.begin(), names.end());
Dan Albert1792c232015-05-18 13:06:53 -07001206}
1207
David Pursell70ef7b42015-09-30 13:35:42 -07001208bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001209 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell70ef7b42015-09-30 13:35:42 -07001210}
1211
Dan Albert1792c232015-05-18 13:06:53 -07001212bool atransport::has_feature(const std::string& feature) const {
1213 return features_.count(feature) > 0;
1214}
1215
David Pursell4e2fd362015-09-22 10:43:08 -07001216void atransport::SetFeatures(const std::string& features_string) {
1217 features_ = StringToFeatureSet(features_string);
Dan Albert1792c232015-05-18 13:06:53 -07001218}
1219
Yabin Cuib3298242015-08-28 15:09:44 -07001220void atransport::AddDisconnect(adisconnect* disconnect) {
1221 disconnects_.push_back(disconnect);
1222}
1223
1224void atransport::RemoveDisconnect(adisconnect* disconnect) {
1225 disconnects_.remove(disconnect);
1226}
1227
1228void atransport::RunDisconnects() {
Elliott Hughes65fe2512015-10-07 15:59:35 -07001229 for (const auto& disconnect : disconnects_) {
Yabin Cuib3298242015-08-28 15:09:44 -07001230 disconnect->func(disconnect->opaque, this);
1231 }
1232 disconnects_.clear();
1233}
1234
David Pursell3f902aa2016-03-01 08:58:26 -08001235bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001236 if (!serial.empty()) {
David Pursell3f902aa2016-03-01 08:58:26 -08001237 if (target == serial) {
1238 return true;
1239 } else if (type == kTransportLocal) {
1240 // Local transports can match [tcp:|udp:]<hostname>[:port].
1241 const char* local_target_ptr = target.c_str();
1242
1243 // For fastboot compatibility, ignore protocol prefixes.
1244 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao1290fbf2016-11-22 14:32:34 -08001245 android::base::StartsWith(target, "udp:")) {
David Pursell3f902aa2016-03-01 08:58:26 -08001246 local_target_ptr += 4;
1247 }
1248
1249 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1250 std::string serial_host, error;
1251 int serial_port = -1;
Josh Gao1290fbf2016-11-22 14:32:34 -08001252 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursell3f902aa2016-03-01 08:58:26 -08001253 // |target| may omit the port to default to ours.
1254 std::string target_host;
1255 int target_port = serial_port;
1256 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1257 nullptr, &error) &&
Josh Gao1290fbf2016-11-22 14:32:34 -08001258 serial_host == target_host && serial_port == target_port) {
David Pursell3f902aa2016-03-01 08:58:26 -08001259 return true;
1260 }
1261 }
1262 }
1263 }
1264
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001265 return (target == devpath) || qual_match(target, "product:", product, false) ||
1266 qual_match(target, "model:", model, true) ||
1267 qual_match(target, "device:", device, false);
David Pursell3f902aa2016-03-01 08:58:26 -08001268}
1269
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001270void atransport::SetConnectionEstablished(bool success) {
1271 connection_waitable_->SetConnectionEstablished(success);
1272}
1273
Josh Gaofc2e56f2018-08-30 11:37:00 -07001274ReconnectResult atransport::Reconnect() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001275 return reconnect_(this);
1276}
1277
Elliott Hughese67f1f82015-04-30 17:32:03 -07001278#if ADB_HOST
1279
Josh Gaob122b172017-08-16 16:57:01 -07001280// We use newline as our delimiter, make sure to never output it.
1281static std::string sanitize(std::string str, bool alphanumeric) {
1282 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1283 : [](const char c) { return c == '\n'; };
1284 std::replace_if(str.begin(), str.end(), pred, '_');
1285 return str;
1286}
1287
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001288static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob122b172017-08-16 16:57:01 -07001289 bool alphanumeric) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001290 if (value.empty()) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001291 return;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001292 }
1293
Elliott Hughese67f1f82015-04-30 17:32:03 -07001294 *result += ' ';
1295 *result += key;
Josh Gaob122b172017-08-16 16:57:01 -07001296 *result += sanitize(value, alphanumeric);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001297}
1298
Josh Gao1290fbf2016-11-22 14:32:34 -08001299static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001300 std::string serial = t->serial;
1301 if (serial.empty()) {
Dan Albertd99d9022015-05-06 16:48:52 -07001302 serial = "(no serial number)";
Elliott Hughese67f1f82015-04-30 17:32:03 -07001303 }
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001304
1305 if (!long_listing) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001306 *result += serial;
1307 *result += '\t';
1308 *result += t->connection_state_name();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001309 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001310 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1311 t->connection_state_name().c_str());
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001312
Elliott Hughese67f1f82015-04-30 17:32:03 -07001313 append_transport_info(result, "", t->devpath, false);
1314 append_transport_info(result, "product:", t->product, false);
1315 append_transport_info(result, "model:", t->model, true);
1316 append_transport_info(result, "device:", t->device, false);
Josh Gaob122b172017-08-16 16:57:01 -07001317
1318 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1319 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1320 *result += " transport_id:";
1321 *result += std::to_string(t->id);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001322 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001323 *result += '\n';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001324}
1325
Elliott Hughese67f1f82015-04-30 17:32:03 -07001326std::string list_transports(bool long_listing) {
Josh Gao1db71af2017-08-17 13:50:51 -07001327 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov04398a92017-12-17 10:56:07 +00001328
1329 auto sorted_transport_list = transport_list;
1330 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1331 if (x->type != y->type) {
1332 return x->type < y->type;
1333 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001334 return x->serial < y->serial;
Artem Iglikov04398a92017-12-17 10:56:07 +00001335 });
1336
1337 std::string result;
1338 for (const auto& t : sorted_transport_list) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001339 append_transport(t, &result, long_listing);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001340 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001341 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001342}
1343
Josh Gao3705b342019-03-28 15:47:44 -07001344void close_usb_devices(std::function<bool(const atransport*)> predicate, bool reset) {
Josh Gao1db71af2017-08-17 13:50:51 -07001345 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao22d2b3e2016-10-27 14:01:08 -07001346 for (auto& t : transport_list) {
1347 if (predicate(t)) {
Josh Gao3705b342019-03-28 15:47:44 -07001348 if (reset) {
1349 t->Reset();
1350 } else {
1351 t->Kick();
1352 }
Josh Gao22d2b3e2016-10-27 14:01:08 -07001353 }
1354 }
1355}
1356
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001357/* hack for osx */
Josh Gao3705b342019-03-28 15:47:44 -07001358void close_usb_devices(bool reset) {
1359 close_usb_devices([](const atransport*) { return true; }, reset);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001360}
Josh Gao1290fbf2016-11-22 14:32:34 -08001361#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001362
Josh Gao362e6962018-08-08 16:20:14 -07001363bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
Joshua Duong5cf78682020-01-21 13:19:42 -08001364 atransport::ReconnectCallback reconnect, bool use_tls, int* error) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001365 atransport* t = new atransport(std::move(reconnect), kCsOffline);
Joshua Duong5cf78682020-01-21 13:19:42 -08001366 t->use_tls = use_tls;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +01001367
Josh Gao3b4de3c2018-08-02 13:58:24 -07001368 D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
Josh Gao56300c92018-07-25 17:21:49 -07001369 if (init_socket_transport(t, std::move(s), port, local) < 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001370 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001371 if (error) *error = errno;
1372 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001373 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001374
Josh Gao1db71af2017-08-17 13:50:51 -07001375 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes65fe2512015-10-07 15:59:35 -07001376 for (const auto& transport : pending_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001377 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001378 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001379 << " is already in pending_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001380 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001381 if (error) *error = EALREADY;
1382 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001383 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001384 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001385
Elliott Hughes65fe2512015-10-07 15:59:35 -07001386 for (const auto& transport : transport_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001387 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001388 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001389 << " is already in transport_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001390 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001391 if (error) *error = EALREADY;
1392 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001393 }
1394 }
1395
Josh Gao3b4de3c2018-08-02 13:58:24 -07001396 t->serial = std::move(serial);
Dan Albertc7915a32015-05-18 16:46:31 -07001397 pending_list.push_front(t);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001398
1399 lock.unlock();
Benoit Goby1c45ee92013-03-29 18:22:36 -07001400
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001401 auto waitable = t->connection_waitable();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001402 register_transport(t);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001403
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001404 if (local == 1) {
1405 // Do not wait for emulator transports.
Josh Gao362e6962018-08-08 16:20:14 -07001406 return true;
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001407 }
1408
Josh Gao362e6962018-08-08 16:20:14 -07001409 if (!waitable->WaitForConnection(std::chrono::seconds(10))) {
1410 if (error) *error = ETIMEDOUT;
1411 return false;
1412 }
1413
1414 if (t->GetConnectionState() == kCsUnauthorized) {
1415 if (error) *error = EPERM;
1416 return false;
1417 }
1418
1419 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001420}
1421
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001422#if ADB_HOST
Josh Gao1290fbf2016-11-22 14:32:34 -08001423atransport* find_transport(const char* serial) {
Dan Albertc7915a32015-05-18 16:46:31 -07001424 atransport* result = nullptr;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001425
Josh Gao1db71af2017-08-17 13:50:51 -07001426 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001427 for (auto& t : transport_list) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001428 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001429 result = t;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001430 break;
1431 }
Dan Albertc7915a32015-05-18 16:46:31 -07001432 }
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001433
Dan Albertc7915a32015-05-18 16:46:31 -07001434 return result;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001435}
1436
Yabin Cuif4b99282015-08-27 12:03:11 -07001437void kick_all_tcp_devices() {
Josh Gao1db71af2017-08-17 13:50:51 -07001438 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001439 for (auto& t : transport_list) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001440 if (t->IsTcpDevice()) {
Yabin Cuid6ab3c22015-08-31 11:50:24 -07001441 // Kicking breaks the read_transport thread of this transport out of any read, then
1442 // the read_transport thread will notify the main thread to make this transport
1443 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cuif4b99282015-08-27 12:03:11 -07001444 // Finally, this transport will be closed and freed in the main thread.
Yabin Cui7f274902016-04-18 11:22:34 -07001445 t->Kick();
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001446 }
Dan Albertc7915a32015-05-18 16:46:31 -07001447 }
Josh Gao902dace2018-08-10 14:44:54 -07001448#if ADB_HOST
1449 reconnect_handler.CheckForKicked();
1450#endif
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001451}
1452
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001453#endif
1454
Josh Gao1290fbf2016-11-22 14:32:34 -08001455void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1456 unsigned writeable) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001457 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertc7915a32015-05-18 16:46:31 -07001458
Josh Gao1290fbf2016-11-22 14:32:34 -08001459 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cuib5e11412017-03-10 16:01:01 -08001460 init_usb_transport(t, usb);
Josh Gao1290fbf2016-11-22 14:32:34 -08001461 if (serial) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001462 t->serial = serial;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001463 }
Dan Albertc7915a32015-05-18 16:46:31 -07001464
1465 if (devpath) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001466 t->devpath = devpath;
Scott Andersone109d262012-04-20 11:21:14 -07001467 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001468
Josh Gao0cd3ae12016-09-21 12:37:10 -07001469 {
Josh Gao1db71af2017-08-17 13:50:51 -07001470 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001471 pending_list.push_front(t);
1472 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001473
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001474 register_transport(t);
1475}
1476
Josh Gaoc51726c2018-10-11 16:33:05 -07001477#if ADB_HOST
Dan Albertdcd78a12015-05-18 16:43:57 -07001478// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao1290fbf2016-11-22 14:32:34 -08001479void unregister_usb_transport(usb_handle* usb) {
Josh Gao1db71af2017-08-17 13:50:51 -07001480 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaob800d882018-01-28 20:32:46 -08001481 transport_list.remove_if([usb](atransport* t) {
Josh Gaoce5ce872018-12-11 13:11:52 -08001482 return t->GetUsbHandle() == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gaob800d882018-01-28 20:32:46 -08001483 });
Mike Lockwood0927bf92009-08-08 12:37:44 -04001484}
Josh Gaoc51726c2018-10-11 16:33:05 -07001485#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001486
Josh Gao36dadca2017-05-16 15:02:45 -07001487bool check_header(apacket* p, atransport* t) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001488 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cuib5e11412017-03-10 16:01:01 -08001489 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1490 << ", magic = " << p->msg.magic;
Josh Gao36dadca2017-05-16 15:02:45 -07001491 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001492 }
1493
Josh Gao1290fbf2016-11-22 14:32:34 -08001494 if (p->msg.data_length > t->get_max_payload()) {
1495 VLOG(RWX) << "check_header(): " << p->msg.data_length
1496 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao36dadca2017-05-16 15:02:45 -07001497 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001498 }
1499
Josh Gao36dadca2017-05-16 15:02:45 -07001500 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001501}
1502
Josh Gao3bd28792016-10-05 19:02:29 -07001503#if ADB_HOST
Joshua Duong5cf78682020-01-21 13:19:42 -08001504std::shared_ptr<RSA> atransport::Key() {
1505 if (keys_.empty()) {
1506 return nullptr;
1507 }
1508
1509 std::shared_ptr<RSA> result = keys_[0];
1510 return result;
1511}
1512
Josh Gao2e671202016-08-18 22:00:12 -07001513std::shared_ptr<RSA> atransport::NextKey() {
Josh Gao4414e4c2018-12-04 01:07:50 -08001514 if (keys_.empty()) {
1515 LOG(INFO) << "fetching keys for transport " << this->serial_name();
1516 keys_ = adb_auth_get_private_keys();
1517
1518 // We should have gotten at least one key: the one that's automatically generated.
1519 CHECK(!keys_.empty());
Joshua Duong5cf78682020-01-21 13:19:42 -08001520 } else {
1521 keys_.pop_front();
Josh Gao4414e4c2018-12-04 01:07:50 -08001522 }
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001523
Josh Gao2e671202016-08-18 22:00:12 -07001524 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001525 return result;
1526}
Josh Gao4414e4c2018-12-04 01:07:50 -08001527
1528void atransport::ResetKeys() {
1529 keys_.clear();
1530}
Josh Gao3bd28792016-10-05 19:02:29 -07001531#endif