blob: ae5359794d5da7d40eaedc889d98ce7d1d0965ae [file] [log] [blame]
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yabin Cui19bec5b2015-09-22 15:52:57 -070017#define TRACE_TAG TRANSPORT
Dan Albertb302d122015-02-24 15:51:19 -080018
Dan Albertdb6fe642015-03-19 15:21:08 -070019#include "sysdeps.h"
Josh Gaof2a988c2018-03-07 16:51:08 -080020
Dan Albertb302d122015-02-24 15:51:19 -080021#include "transport.h"
22
Dan Albert4895c522015-02-20 17:24:58 -080023#include <ctype.h>
Dan Albertb302d122015-02-24 15:51:19 -080024#include <errno.h>
Josh Gaob39e4152017-08-16 16:57:01 -070025#include <inttypes.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080026#include <stdio.h>
27#include <stdlib.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080028#include <string.h>
Dan Albertb302d122015-02-24 15:51:19 -080029#include <unistd.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080030
Spencer Low28bc2cb2015-11-07 18:51:54 -080031#include <algorithm>
Josh Gao715fe602018-02-16 13:24:58 -080032#include <deque>
Dan Albertecce5032015-05-18 16:46:31 -070033#include <list>
Pirama Arumuga Nainar5231aff2018-08-08 10:33:24 -070034#include <memory>
Josh Gaoe7daf572016-09-21 12:37:10 -070035#include <mutex>
Josh Gaod2ea0652018-08-10 14:28:24 -070036#include <set>
Josh Gao0f3312a2017-04-12 17:00:49 -070037#include <thread>
Dan Albertecce5032015-05-18 16:46:31 -070038
Elliott Hughesf55ead92015-12-04 22:00:26 -080039#include <android-base/logging.h>
David Pursellc929c6f2016-03-01 08:58:26 -080040#include <android-base/parsenetaddress.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080041#include <android-base/stringprintf.h>
42#include <android-base/strings.h>
Josh Gaob39e4152017-08-16 16:57:01 -070043#include <android-base/thread_annotations.h>
Elliott Hughes88b4c852015-04-30 17:32:03 -070044
Josh Gao361148b2018-01-02 12:01:43 -080045#include <diagnose_usb.h>
46
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080047#include "adb.h"
Elliott Hughes801066a2016-06-29 17:42:01 -070048#include "adb_auth.h"
Josh Gao395b86a2018-01-28 20:32:46 -080049#include "adb_io.h"
Josh Gao9e09a972016-11-29 09:40:29 -080050#include "adb_trace.h"
Elliott Hughes88b4c852015-04-30 17:32:03 -070051#include "adb_utils.h"
Yabin Cui3cf1b362017-03-10 16:01:01 -080052#include "fdevent.h"
Josh Gaob0182892018-07-31 14:12:59 -070053#include "sysdeps/chrono.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080054
Luis Hector Chavez0aeda102018-04-20 10:31:29 -070055static void remove_transport(atransport* transport);
56static void transport_unref(atransport* transport);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080057
Josh Gaob39e4152017-08-16 16:57:01 -070058// TODO: unordered_map<TransportId, atransport*>
Josh Gaoe3a87d02015-11-11 17:56:12 -080059static auto& transport_list = *new std::list<atransport*>();
60static auto& pending_list = *new std::list<atransport*>();
Benoit Goby3f9f9ce2013-03-29 18:22:36 -070061
Josh Gaoaaa82f72017-08-17 13:50:51 -070062static auto& transport_lock = *new std::recursive_mutex();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080063
Todd Kennedyaff9c672015-11-10 00:03:25 +000064const char* const kFeatureShell2 = "shell_v2";
65const char* const kFeatureCmd = "cmd";
Josh Gaoa2cf3752016-12-05 17:11:34 -080066const char* const kFeatureStat2 = "stat_v2";
Josh Gao210b63f2017-02-22 17:07:01 -080067const char* const kFeatureLibusb = "libusb";
Dan Albert27983bc2017-05-23 14:30:00 -070068const char* const kFeaturePushSync = "push_sync";
Dario Frenidcb4c362018-10-04 16:26:40 +010069const char* const kFeatureApex = "apex";
Josh Gao281aab72018-10-22 13:00:05 -070070const char* const kFeatureFixedPushMkdir = "fixed_push_mkdir";
Alex Buynytskyye1fa8142019-01-17 13:13:56 -080071const char* const kFeatureAbb = "abb";
Todd Kennedyaff9c672015-11-10 00:03:25 +000072
Luis Hector Chavezda74b902018-04-17 14:25:04 -070073namespace {
74
75// A class that helps the Clang Thread Safety Analysis deal with
76// std::unique_lock. Given that std::unique_lock is movable, and the analysis
77// can not currently perform alias analysis, it is not annotated. In order to
78// assert that the mutex is held, a ScopedAssumeLocked can be created just after
79// the std::unique_lock.
80class SCOPED_CAPABILITY ScopedAssumeLocked {
81 public:
82 ScopedAssumeLocked(std::mutex& mutex) ACQUIRE(mutex) {}
83 ~ScopedAssumeLocked() RELEASE() {}
84};
85
Josh Gao5c47e9f2018-07-31 18:28:32 -070086#if ADB_HOST
Luis Hector Chavez0aeda102018-04-20 10:31:29 -070087// Tracks and handles atransport*s that are attempting reconnection.
88class ReconnectHandler {
89 public:
90 ReconnectHandler() = default;
91 ~ReconnectHandler() = default;
92
93 // Starts the ReconnectHandler thread.
94 void Start();
95
96 // Requests the ReconnectHandler thread to stop.
97 void Stop();
98
99 // Adds the atransport* to the queue of reconnect attempts.
100 void TrackTransport(atransport* transport);
101
Josh Gao13cb8c02018-08-10 14:44:54 -0700102 // Wake up the ReconnectHandler thread to have it check for kicked transports.
103 void CheckForKicked();
104
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700105 private:
106 // The main thread loop.
107 void Run();
108
109 // Tracks a reconnection attempt.
110 struct ReconnectAttempt {
111 atransport* transport;
Josh Gaoc4deb392018-07-30 18:51:55 -0700112 std::chrono::steady_clock::time_point reconnect_time;
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700113 size_t attempts_left;
Josh Gaob0182892018-07-31 14:12:59 -0700114
115 bool operator<(const ReconnectAttempt& rhs) const {
Josh Gaod2ea0652018-08-10 14:28:24 -0700116 if (reconnect_time == rhs.reconnect_time) {
117 return reinterpret_cast<uintptr_t>(transport) <
118 reinterpret_cast<uintptr_t>(rhs.transport);
119 }
120 return reconnect_time < rhs.reconnect_time;
Josh Gaob0182892018-07-31 14:12:59 -0700121 }
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700122 };
123
124 // Only retry for up to one minute.
Josh Gaob0182892018-07-31 14:12:59 -0700125 static constexpr const std::chrono::seconds kDefaultTimeout = 10s;
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700126 static constexpr const size_t kMaxAttempts = 6;
127
128 // Protects all members.
129 std::mutex reconnect_mutex_;
130 bool running_ GUARDED_BY(reconnect_mutex_) = true;
131 std::thread handler_thread_;
132 std::condition_variable reconnect_cv_;
Josh Gaod2ea0652018-08-10 14:28:24 -0700133 std::set<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700134
135 DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
136};
137
138void ReconnectHandler::Start() {
139 check_main_thread();
140 handler_thread_ = std::thread(&ReconnectHandler::Run, this);
141}
142
143void ReconnectHandler::Stop() {
144 check_main_thread();
145 {
146 std::lock_guard<std::mutex> lock(reconnect_mutex_);
147 running_ = false;
148 }
149 reconnect_cv_.notify_one();
150 handler_thread_.join();
151
152 // Drain the queue to free all resources.
153 std::lock_guard<std::mutex> lock(reconnect_mutex_);
154 while (!reconnect_queue_.empty()) {
Josh Gaod2ea0652018-08-10 14:28:24 -0700155 ReconnectAttempt attempt = *reconnect_queue_.begin();
156 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700157 remove_transport(attempt.transport);
158 }
159}
160
161void ReconnectHandler::TrackTransport(atransport* transport) {
162 check_main_thread();
163 {
164 std::lock_guard<std::mutex> lock(reconnect_mutex_);
165 if (!running_) return;
Josh Gaob0182892018-07-31 14:12:59 -0700166 // Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
167 auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
168 reconnect_queue_.emplace(
169 ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700170 }
171 reconnect_cv_.notify_one();
172}
173
Josh Gao13cb8c02018-08-10 14:44:54 -0700174void ReconnectHandler::CheckForKicked() {
175 reconnect_cv_.notify_one();
176}
177
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700178void ReconnectHandler::Run() {
179 while (true) {
180 ReconnectAttempt attempt;
181 {
182 std::unique_lock<std::mutex> lock(reconnect_mutex_);
183 ScopedAssumeLocked assume_lock(reconnect_mutex_);
184
Josh Gaoc4deb392018-07-30 18:51:55 -0700185 if (!reconnect_queue_.empty()) {
186 // FIXME: libstdc++ (used on Windows) implements condition_variable with
187 // system_clock as its clock, so we're probably hosed if the clock changes,
188 // even if we use steady_clock throughout. This problem goes away once we
189 // switch to libc++.
Josh Gaod2ea0652018-08-10 14:28:24 -0700190 reconnect_cv_.wait_until(lock, reconnect_queue_.begin()->reconnect_time);
Josh Gaoc4deb392018-07-30 18:51:55 -0700191 } else {
192 reconnect_cv_.wait(lock);
193 }
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700194
195 if (!running_) return;
Josh Gao13cb8c02018-08-10 14:44:54 -0700196
197 // Scan the whole list for kicked transports, so that we immediately handle an explicit
198 // disconnect request.
199 bool kicked = false;
200 for (auto it = reconnect_queue_.begin(); it != reconnect_queue_.end();) {
201 if (it->transport->kicked()) {
202 D("transport %s was kicked. giving up on it.", it->transport->serial.c_str());
203 remove_transport(it->transport);
204 it = reconnect_queue_.erase(it);
205 } else {
206 ++it;
207 }
208 kicked = true;
209 }
210
Josh Gaoc4deb392018-07-30 18:51:55 -0700211 if (reconnect_queue_.empty()) continue;
212
Josh Gao13cb8c02018-08-10 14:44:54 -0700213 // Go back to sleep if we either woke up spuriously, or we were woken up to remove
214 // a kicked transport, and the first transport isn't ready for reconnection yet.
Josh Gaoc4deb392018-07-30 18:51:55 -0700215 auto now = std::chrono::steady_clock::now();
Josh Gaod2ea0652018-08-10 14:28:24 -0700216 if (reconnect_queue_.begin()->reconnect_time > now) {
Josh Gaoc4deb392018-07-30 18:51:55 -0700217 continue;
218 }
219
Josh Gaod2ea0652018-08-10 14:28:24 -0700220 attempt = *reconnect_queue_.begin();
221 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700222 }
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700223 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700224
Josh Gaod24580d2018-08-30 11:37:00 -0700225 switch (attempt.transport->Reconnect()) {
226 case ReconnectResult::Retry: {
227 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
228 if (attempt.attempts_left == 0) {
229 D("transport %s exceeded the number of retry attempts. giving up on it.",
230 attempt.transport->serial.c_str());
231 remove_transport(attempt.transport);
232 continue;
233 }
234
235 std::lock_guard<std::mutex> lock(reconnect_mutex_);
236 reconnect_queue_.emplace(ReconnectAttempt{
237 attempt.transport,
238 std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
239 attempt.attempts_left - 1});
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700240 continue;
241 }
242
Josh Gaod24580d2018-08-30 11:37:00 -0700243 case ReconnectResult::Success:
244 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
245 register_transport(attempt.transport);
246 continue;
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700247
Josh Gaod24580d2018-08-30 11:37:00 -0700248 case ReconnectResult::Abort:
249 D("cancelling reconnection attempt to %s.", attempt.transport->serial.c_str());
250 remove_transport(attempt.transport);
251 continue;
252 }
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700253 }
254}
255
256static auto& reconnect_handler = *new ReconnectHandler();
257
Josh Gao5c47e9f2018-07-31 18:28:32 -0700258#endif
259
Luis Hector Chavezda74b902018-04-17 14:25:04 -0700260} // namespace
261
Josh Gaob39e4152017-08-16 16:57:01 -0700262TransportId NextTransportId() {
263 static std::atomic<TransportId> next(1);
264 return next++;
265}
266
Josh Gao715fe602018-02-16 13:24:58 -0800267BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
268 : underlying_(std::move(connection)) {}
269
270BlockingConnectionAdapter::~BlockingConnectionAdapter() {
271 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
272 Stop();
273}
274
275void BlockingConnectionAdapter::Start() {
Josh Gao13781e82018-04-03 12:55:18 -0700276 std::lock_guard<std::mutex> lock(mutex_);
277 if (started_) {
278 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
279 << "): started multiple times";
280 }
281
Josh Gao715fe602018-02-16 13:24:58 -0800282 read_thread_ = std::thread([this]() {
283 LOG(INFO) << this->transport_name_ << ": read thread spawning";
284 while (true) {
Josh Gaof2a988c2018-03-07 16:51:08 -0800285 auto packet = std::make_unique<apacket>();
Josh Gao715fe602018-02-16 13:24:58 -0800286 if (!underlying_->Read(packet.get())) {
287 PLOG(INFO) << this->transport_name_ << ": read failed";
288 break;
289 }
290 read_callback_(this, std::move(packet));
291 }
292 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
293 });
294
295 write_thread_ = std::thread([this]() {
296 LOG(INFO) << this->transport_name_ << ": write thread spawning";
297 while (true) {
298 std::unique_lock<std::mutex> lock(mutex_);
Luis Hector Chavezda74b902018-04-17 14:25:04 -0700299 ScopedAssumeLocked assume_locked(mutex_);
Josh Gao13781e82018-04-03 12:55:18 -0700300 cv_.wait(lock, [this]() REQUIRES(mutex_) {
301 return this->stopped_ || !this->write_queue_.empty();
302 });
303
Josh Gao715fe602018-02-16 13:24:58 -0800304 if (this->stopped_) {
305 return;
306 }
307
308 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
309 this->write_queue_.pop_front();
310 lock.unlock();
311
312 if (!this->underlying_->Write(packet.get())) {
313 break;
314 }
315 }
316 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
317 });
Josh Gao13781e82018-04-03 12:55:18 -0700318
319 started_ = true;
Josh Gao715fe602018-02-16 13:24:58 -0800320}
321
322void BlockingConnectionAdapter::Stop() {
Josh Gao13781e82018-04-03 12:55:18 -0700323 {
324 std::lock_guard<std::mutex> lock(mutex_);
325 if (!started_) {
326 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
327 return;
328 }
Josh Gao715fe602018-02-16 13:24:58 -0800329
Josh Gao13781e82018-04-03 12:55:18 -0700330 if (stopped_) {
331 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
332 << "): already stopped";
333 return;
334 }
335
336 stopped_ = true;
337 }
Josh Gao715fe602018-02-16 13:24:58 -0800338
339 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
340
341 this->underlying_->Close();
Josh Gao715fe602018-02-16 13:24:58 -0800342 this->cv_.notify_one();
Josh Gao13781e82018-04-03 12:55:18 -0700343
344 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
345 std::thread read_thread;
346 std::thread write_thread;
347
348 {
349 std::lock_guard<std::mutex> lock(mutex_);
350 read_thread = std::move(read_thread_);
351 write_thread = std::move(write_thread_);
352 }
353
354 read_thread.join();
355 write_thread.join();
Josh Gao715fe602018-02-16 13:24:58 -0800356
357 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
358 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
359}
360
361bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
362 {
Josh Gao13781e82018-04-03 12:55:18 -0700363 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao715fe602018-02-16 13:24:58 -0800364 write_queue_.emplace_back(std::move(packet));
365 }
366
367 cv_.notify_one();
368 return true;
369}
370
Josh Gao395b86a2018-01-28 20:32:46 -0800371bool FdConnection::Read(apacket* packet) {
372 if (!ReadFdExactly(fd_.get(), &packet->msg, sizeof(amessage))) {
373 D("remote local: read terminated (message)");
374 return false;
375 }
376
Josh Gao839b9322018-02-05 18:49:10 -0800377 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gaob14756a2018-02-02 14:38:04 -0800378 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
379 return false;
380 }
381
Josh Gao839b9322018-02-05 18:49:10 -0800382 packet->payload.resize(packet->msg.data_length);
383
384 if (!ReadFdExactly(fd_.get(), &packet->payload[0], packet->payload.size())) {
Josh Gao395b86a2018-01-28 20:32:46 -0800385 D("remote local: terminated (data)");
386 return false;
387 }
388
389 return true;
390}
391
392bool FdConnection::Write(apacket* packet) {
Josh Gao839b9322018-02-05 18:49:10 -0800393 if (!WriteFdExactly(fd_.get(), &packet->msg, sizeof(packet->msg))) {
Josh Gao395b86a2018-01-28 20:32:46 -0800394 D("remote local: write terminated");
395 return false;
396 }
397
Josh Gao839b9322018-02-05 18:49:10 -0800398 if (packet->msg.data_length) {
399 if (!WriteFdExactly(fd_.get(), &packet->payload[0], packet->msg.data_length)) {
400 D("remote local: write terminated");
401 return false;
402 }
403 }
404
Josh Gao395b86a2018-01-28 20:32:46 -0800405 return true;
406}
407
408void FdConnection::Close() {
409 adb_shutdown(fd_.get());
410 fd_.reset();
411}
412
Josh Gao67ac3792016-10-06 13:31:44 -0700413void send_packet(apacket* p, atransport* t) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800414 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayee7b44d2017-12-07 11:40:00 -0800415 // compute a checksum for connection/auth packets for compatibility reasons
416 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
417 p->msg.data_check = 0;
418 } else {
419 p->msg.data_check = calculate_apacket_checksum(p);
420 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800421
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700422 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800423
Yi Kong86e67182018-07-13 18:15:16 -0700424 if (t == nullptr) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700425 LOG(FATAL) << "Transport is null";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800426 }
427
Josh Gao715fe602018-02-16 13:24:58 -0800428 if (t->Write(p) != 0) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700429 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao715fe602018-02-16 13:24:58 -0800430 t->Kick();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800431 }
432}
433
Yabin Cui4d64fd82015-08-27 12:03:11 -0700434void kick_transport(atransport* t) {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700435 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuid78ed222016-04-05 13:50:44 -0700436 // As kick_transport() can be called from threads without guarantee that t is valid,
437 // check if the transport is in transport_list first.
Josh Gaob39e4152017-08-16 16:57:01 -0700438 //
439 // TODO(jmgao): WTF? Is this actually true?
Yabin Cuid78ed222016-04-05 13:50:44 -0700440 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Yabin Cuif2a9f9b2016-04-18 11:22:34 -0700441 t->Kick();
Yabin Cuid78ed222016-04-05 13:50:44 -0700442 }
Josh Gao13cb8c02018-08-10 14:44:54 -0700443
444#if ADB_HOST
445 reconnect_handler.CheckForKicked();
446#endif
Yabin Cui4d64fd82015-08-27 12:03:11 -0700447}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800448
449static int transport_registration_send = -1;
450static int transport_registration_recv = -1;
Josh Gao9528df22018-05-14 11:14:33 -0700451static fdevent* transport_registration_fde;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800452
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800453#if ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800454
455/* this adds support required by the 'track-devices' service.
456 * this is used to send the content of "list_transport" to any
457 * number of client connections that want it through a single
458 * live TCP connection
459 */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800460struct device_tracker {
Josh Gao0d6aa992016-11-22 14:32:34 -0800461 asocket socket;
Josh Gao5cb76ce2018-02-12 17:24:00 -0800462 bool update_needed = false;
463 bool long_output = false;
464 device_tracker* next = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800465};
466
467/* linked list of all device trackers */
Josh Gao0d6aa992016-11-22 14:32:34 -0800468static device_tracker* device_tracker_list;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800469
Josh Gao0d6aa992016-11-22 14:32:34 -0800470static void device_tracker_remove(device_tracker* tracker) {
471 device_tracker** pnode = &device_tracker_list;
472 device_tracker* node = *pnode;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800473
Josh Gaoaaa82f72017-08-17 13:50:51 -0700474 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800475 while (node) {
476 if (node == tracker) {
477 *pnode = node->next;
478 break;
479 }
480 pnode = &node->next;
Josh Gao0d6aa992016-11-22 14:32:34 -0800481 node = *pnode;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800482 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800483}
484
Josh Gao0d6aa992016-11-22 14:32:34 -0800485static void device_tracker_close(asocket* socket) {
486 device_tracker* tracker = (device_tracker*)socket;
487 asocket* peer = socket->peer;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800488
Josh Gao0d6aa992016-11-22 14:32:34 -0800489 D("device tracker %p removed", tracker);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800490 if (peer) {
Yi Kong86e67182018-07-13 18:15:16 -0700491 peer->peer = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800492 peer->close(peer);
493 }
494 device_tracker_remove(tracker);
Josh Gao5cb76ce2018-02-12 17:24:00 -0800495 delete tracker;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800496}
497
Josh Gaocd2a5292018-03-07 16:52:28 -0800498static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800499 /* you can't read from a device tracker, close immediately */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800500 device_tracker_close(socket);
501 return -1;
502}
503
Elliott Hughes88b4c852015-04-30 17:32:03 -0700504static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughes88b4c852015-04-30 17:32:03 -0700505 asocket* peer = tracker->socket.peer;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800506
Josh Gaocd2a5292018-03-07 16:52:28 -0800507 apacket::payload_type data;
Josh Gaoa7d9d712018-02-01 13:17:50 -0800508 data.resize(4 + string.size());
509 char buf[5];
510 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
511 memcpy(&data[0], buf, 4);
512 memcpy(&data[4], string.data(), string.size());
513 return peer->enqueue(peer, std::move(data));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800514}
515
Elliott Hughes88b4c852015-04-30 17:32:03 -0700516static void device_tracker_ready(asocket* socket) {
517 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800518
Elliott Hughes88b4c852015-04-30 17:32:03 -0700519 // We want to send the device list when the tracker connects
520 // for the first time, even if no update occurred.
Josh Gao32124632017-08-14 18:57:54 -0700521 if (tracker->update_needed) {
522 tracker->update_needed = false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800523
Josh Gao32124632017-08-14 18:57:54 -0700524 std::string transports = list_transports(tracker->long_output);
Elliott Hughes88b4c852015-04-30 17:32:03 -0700525 device_tracker_send(tracker, transports);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800526 }
527}
528
Josh Gao32124632017-08-14 18:57:54 -0700529asocket* create_device_tracker(bool long_output) {
Josh Gao5cb76ce2018-02-12 17:24:00 -0800530 device_tracker* tracker = new device_tracker();
Elliott Hughese64126b2018-10-19 13:59:44 -0700531 if (tracker == nullptr) LOG(FATAL) << "cannot allocate device tracker";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800532
Josh Gao0d6aa992016-11-22 14:32:34 -0800533 D("device tracker %p created", tracker);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800534
535 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao0d6aa992016-11-22 14:32:34 -0800536 tracker->socket.ready = device_tracker_ready;
537 tracker->socket.close = device_tracker_close;
Josh Gao32124632017-08-14 18:57:54 -0700538 tracker->update_needed = true;
539 tracker->long_output = long_output;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800540
Josh Gao0d6aa992016-11-22 14:32:34 -0800541 tracker->next = device_tracker_list;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800542 device_tracker_list = tracker;
543
544 return &tracker->socket;
545}
546
Josh Gao1e3bf732017-05-03 22:37:10 -0700547// Check if all of the USB transports are connected.
548bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700549 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao1e3bf732017-05-03 22:37:10 -0700550 for (const auto& t : transport_list) {
551 if (!fn(t)) {
552 return false;
553 }
554 }
555 for (const auto& t : pending_list) {
556 if (!fn(t)) {
557 return false;
558 }
559 }
560 return true;
561}
562
Elliott Hughes88b4c852015-04-30 17:32:03 -0700563// Call this function each time the transport list has changed.
564void update_transports() {
Josh Gao1e3bf732017-05-03 22:37:10 -0700565 update_transport_status();
566
567 // Notify `adb track-devices` clients.
Elliott Hughes88b4c852015-04-30 17:32:03 -0700568 std::string transports = list_transports(false);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800569
Elliott Hughes88b4c852015-04-30 17:32:03 -0700570 device_tracker* tracker = device_tracker_list;
571 while (tracker != nullptr) {
572 device_tracker* next = tracker->next;
573 // This may destroy the tracker if the connection is closed.
574 device_tracker_send(tracker, transports);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800575 tracker = next;
576 }
577}
Elliott Hughes88b4c852015-04-30 17:32:03 -0700578
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800579#else
Elliott Hughes88b4c852015-04-30 17:32:03 -0700580
581void update_transports() {
582 // Nothing to do on the device side.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800583}
Elliott Hughes88b4c852015-04-30 17:32:03 -0700584
Josh Gao0d6aa992016-11-22 14:32:34 -0800585#endif // ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800586
Josh Gao0d6aa992016-11-22 14:32:34 -0800587struct tmsg {
588 atransport* transport;
589 int action;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800590};
591
Josh Gao0d6aa992016-11-22 14:32:34 -0800592static int transport_read_action(int fd, struct tmsg* m) {
593 char* p = (char*)m;
594 int len = sizeof(*m);
595 int r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800596
Josh Gao0d6aa992016-11-22 14:32:34 -0800597 while (len > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800598 r = adb_read(fd, p, len);
Josh Gao0d6aa992016-11-22 14:32:34 -0800599 if (r > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800600 len -= r;
Josh Gao0d6aa992016-11-22 14:32:34 -0800601 p += r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800602 } else {
Yabin Cui815ad882015-09-02 17:44:28 -0700603 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800604 return -1;
605 }
606 }
607 return 0;
608}
609
Josh Gao0d6aa992016-11-22 14:32:34 -0800610static int transport_write_action(int fd, struct tmsg* m) {
611 char* p = (char*)m;
612 int len = sizeof(*m);
613 int r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800614
Josh Gao0d6aa992016-11-22 14:32:34 -0800615 while (len > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800616 r = adb_write(fd, p, len);
Josh Gao0d6aa992016-11-22 14:32:34 -0800617 if (r > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800618 len -= r;
Josh Gao0d6aa992016-11-22 14:32:34 -0800619 p += r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800620 } else {
Yabin Cui815ad882015-09-02 17:44:28 -0700621 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800622 return -1;
623 }
624 }
625 return 0;
626}
627
Josh Gao715fe602018-02-16 13:24:58 -0800628static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800629 tmsg m;
Josh Gao0d6aa992016-11-22 14:32:34 -0800630 atransport* t;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800631
Josh Gao0d6aa992016-11-22 14:32:34 -0800632 if (!(ev & FDE_READ)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800633 return;
634 }
635
Josh Gao0d6aa992016-11-22 14:32:34 -0800636 if (transport_read_action(_fd, &m)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700637 PLOG(FATAL) << "cannot read transport registration socket";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800638 }
639
640 t = m.transport;
641
Dan Albertbe8e54b2015-05-18 13:06:53 -0700642 if (m.action == 0) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700643 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800644
Josh Gaoe7daf572016-09-21 12:37:10 -0700645 {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700646 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaoe7daf572016-09-21 12:37:10 -0700647 transport_list.remove(t);
648 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800649
Dan Albertecce5032015-05-18 16:46:31 -0700650 delete t;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800651
652 update_transports();
653 return;
654 }
655
Mike Lockwoode45583f2009-08-08 12:37:44 -0400656 /* don't create transport threads for inaccessible devices */
Yabin Cui3cf1b362017-03-10 16:01:01 -0800657 if (t->GetConnectionState() != kCsNoPerm) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700658 // The connection gets a reference to the atransport. It will release it
659 // upon a read/write error.
660 t->ref_count++;
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700661 t->connection()->SetTransportName(t->serial_name());
662 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao715fe602018-02-16 13:24:58 -0800663 if (!check_header(p.get(), t)) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700664 D("%s: remote read: bad header", t->serial.c_str());
Josh Gao715fe602018-02-16 13:24:58 -0800665 return false;
666 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800667
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700668 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "from remote", p.get());
Josh Gao715fe602018-02-16 13:24:58 -0800669 apacket* packet = p.release();
Mike Lockwoode45583f2009-08-08 12:37:44 -0400670
Josh Gao715fe602018-02-16 13:24:58 -0800671 // TODO: Does this need to run on the main thread?
672 fdevent_run_on_main_thread([packet, t]() { handle_packet(packet, t); });
673 return true;
674 });
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700675 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Josh Gao3a34bc52018-10-11 16:33:05 -0700676 LOG(INFO) << t->serial_name() << ": connection terminated: " << error;
Josh Gao715fe602018-02-16 13:24:58 -0800677 fdevent_run_on_main_thread([t]() {
678 handle_offline(t);
679 transport_unref(t);
680 });
681 });
Mike Lockwoode45583f2009-08-08 12:37:44 -0400682
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700683 t->connection()->Start();
Josh Gao715fe602018-02-16 13:24:58 -0800684#if ADB_HOST
685 send_connect(t);
686#endif
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800687 }
688
Josh Gaoe7daf572016-09-21 12:37:10 -0700689 {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700690 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700691 auto it = std::find(pending_list.begin(), pending_list.end(), t);
692 if (it != pending_list.end()) {
693 pending_list.remove(t);
694 transport_list.push_front(t);
695 }
Josh Gaoe7daf572016-09-21 12:37:10 -0700696 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800697
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800698 update_transports();
699}
700
Josh Gao5c47e9f2018-07-31 18:28:32 -0700701#if ADB_HOST
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700702void init_reconnect_handler(void) {
703 reconnect_handler.Start();
704}
Josh Gao5c47e9f2018-07-31 18:28:32 -0700705#endif
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700706
Josh Gao0d6aa992016-11-22 14:32:34 -0800707void init_transport_registration(void) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800708 int s[2];
709
Josh Gao0d6aa992016-11-22 14:32:34 -0800710 if (adb_socketpair(s)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700711 PLOG(FATAL) << "cannot open transport registration socketpair";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800712 }
Yabin Cui815ad882015-09-02 17:44:28 -0700713 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800714
715 transport_registration_send = s[0];
716 transport_registration_recv = s[1];
717
Josh Gao9528df22018-05-14 11:14:33 -0700718 transport_registration_fde =
Yi Kong86e67182018-07-13 18:15:16 -0700719 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao9528df22018-05-14 11:14:33 -0700720 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao165460f2017-05-09 13:43:35 -0700721}
722
723void kick_all_transports() {
Josh Gao5c47e9f2018-07-31 18:28:32 -0700724#if ADB_HOST
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700725 reconnect_handler.Stop();
Josh Gao5c47e9f2018-07-31 18:28:32 -0700726#endif
Josh Gao165460f2017-05-09 13:43:35 -0700727 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gaoaaa82f72017-08-17 13:50:51 -0700728 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao165460f2017-05-09 13:43:35 -0700729 for (auto t : transport_list) {
730 t->Kick();
731 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800732}
733
734/* the fdevent select pump is single threaded */
Josh Gao3a34bc52018-10-11 16:33:05 -0700735void register_transport(atransport* transport) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800736 tmsg m;
737 m.transport = transport;
738 m.action = 1;
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700739 D("transport: %s registered", transport->serial.c_str());
Josh Gao0d6aa992016-11-22 14:32:34 -0800740 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700741 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800742 }
743}
744
Josh Gao0d6aa992016-11-22 14:32:34 -0800745static void remove_transport(atransport* transport) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800746 tmsg m;
747 m.transport = transport;
748 m.action = 0;
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700749 D("transport: %s removed", transport->serial.c_str());
Josh Gao0d6aa992016-11-22 14:32:34 -0800750 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700751 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800752 }
753}
754
Yabin Cui4d64fd82015-08-27 12:03:11 -0700755static void transport_unref(atransport* t) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700756 check_main_thread();
Yabin Cui4d64fd82015-08-27 12:03:11 -0700757 CHECK(t != nullptr);
Josh Gaoe7daf572016-09-21 12:37:10 -0700758
Josh Gao4d299742017-09-13 13:40:57 -0700759 std::lock_guard<std::recursive_mutex> lock(transport_lock);
760 CHECK_GT(t->ref_count, 0u);
761 t->ref_count--;
762 if (t->ref_count == 0) {
Josh Gao3a34bc52018-10-11 16:33:05 -0700763 LOG(INFO) << "destroying transport " << t->serial_name();
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700764 t->connection()->Stop();
Josh Gao5c47e9f2018-07-31 18:28:32 -0700765#if ADB_HOST
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700766 if (t->IsTcpDevice() && !t->kicked()) {
Josh Gao5c47e9f2018-07-31 18:28:32 -0700767 D("transport: %s unref (attempting reconnection)", t->serial.c_str());
Josh Gaoeb656522018-12-04 01:07:50 -0800768
769 // We need to clear the transport's keys, so that on the next connection, it tries
770 // again from the beginning.
771 t->ResetKeys();
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700772 reconnect_handler.TrackTransport(t);
773 } else {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700774 D("transport: %s unref (kicking and closing)", t->serial.c_str());
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700775 remove_transport(t);
776 }
Josh Gao5c47e9f2018-07-31 18:28:32 -0700777#else
778 D("transport: %s unref (kicking and closing)", t->serial.c_str());
779 remove_transport(t);
780#endif
781
David 'Digit' Turner58f59682011-01-06 14:11:07 +0100782 } else {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700783 D("transport: %s unref (count=%zu)", t->serial.c_str(), t->ref_count);
Mike Lockwood01c2c302010-05-24 10:44:35 -0400784 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800785}
786
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700787static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao0d6aa992016-11-22 14:32:34 -0800788 bool sanitize_qual) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700789 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
790 return qual.empty();
Scott Anderson27042382012-05-30 18:11:27 -0700791
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700792 if (qual.empty()) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700793
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700794 const char* ptr = to_test.c_str();
Scott Anderson27042382012-05-30 18:11:27 -0700795 if (prefix) {
796 while (*prefix) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700797 if (*prefix++ != *ptr++) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700798 }
799 }
800
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700801 for (char ch : qual) {
Josh Gao0d6aa992016-11-22 14:32:34 -0800802 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700803 if (ch != *ptr++) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700804 }
805
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700806 /* Everything matched so far. Return true if *ptr is a NUL. */
807 return !*ptr;
Scott Anderson27042382012-05-30 18:11:27 -0700808}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800809
Josh Gaob39e4152017-08-16 16:57:01 -0700810atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
811 bool* is_ambiguous, std::string* error_out,
812 bool accept_any_state) {
Elliott Hughes67943d12015-10-07 14:55:10 -0700813 atransport* result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800814
Josh Gaob39e4152017-08-16 16:57:01 -0700815 if (transport_id != 0) {
816 *error_out =
817 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
818 } else if (serial) {
Elliott Hughes67943d12015-10-07 14:55:10 -0700819 *error_out = android::base::StringPrintf("device '%s' not found", serial);
820 } else if (type == kTransportLocal) {
821 *error_out = "no emulators found";
822 } else if (type == kTransportAny) {
823 *error_out = "no devices/emulators found";
824 } else {
825 *error_out = "no devices found";
826 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800827
Josh Gaoaaa82f72017-08-17 13:50:51 -0700828 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes67943d12015-10-07 14:55:10 -0700829 for (const auto& t : transport_list) {
Yabin Cui3cf1b362017-03-10 16:01:01 -0800830 if (t->GetConnectionState() == kCsNoPerm) {
David Pursell6e5c7eb2015-12-02 15:14:31 -0800831 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwoodadc16b32009-08-08 13:53:16 -0400832 continue;
833 }
Mike Lockwoode45583f2009-08-08 12:37:44 -0400834
Josh Gaob39e4152017-08-16 16:57:01 -0700835 if (transport_id) {
836 if (t->id == transport_id) {
837 result = t;
838 break;
839 }
840 } else if (serial) {
David Pursellc929c6f2016-03-01 08:58:26 -0800841 if (t->MatchesTarget(serial)) {
Scott Anderson27042382012-05-30 18:11:27 -0700842 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700843 *error_out = "more than one device";
Elliott Hughes67943d12015-10-07 14:55:10 -0700844 if (is_ambiguous) *is_ambiguous = true;
845 result = nullptr;
Scott Anderson27042382012-05-30 18:11:27 -0700846 break;
847 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800848 result = t;
Scott Anderson6dfaf4b2012-04-20 11:21:14 -0700849 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800850 } else {
Elliott Hughes3aec2ba2015-05-05 13:10:43 -0700851 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800852 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700853 *error_out = "more than one device";
Elliott Hughes67943d12015-10-07 14:55:10 -0700854 if (is_ambiguous) *is_ambiguous = true;
855 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800856 break;
857 }
858 result = t;
Elliott Hughes3aec2ba2015-05-05 13:10:43 -0700859 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800860 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700861 *error_out = "more than one emulator";
Elliott Hughes67943d12015-10-07 14:55:10 -0700862 if (is_ambiguous) *is_ambiguous = true;
863 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800864 break;
865 }
866 result = t;
Elliott Hughes3aec2ba2015-05-05 13:10:43 -0700867 } else if (type == kTransportAny) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800868 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700869 *error_out = "more than one device/emulator";
Elliott Hughes67943d12015-10-07 14:55:10 -0700870 if (is_ambiguous) *is_ambiguous = true;
871 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800872 break;
873 }
874 result = t;
875 }
876 }
877 }
Josh Gaoe7daf572016-09-21 12:37:10 -0700878 lock.unlock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800879
Josh Gao7a7c5cb2018-05-04 16:04:49 -0700880 if (result && !accept_any_state) {
881 // The caller requires an active transport.
882 // Make sure that we're actually connected.
883 ConnectionState state = result->GetConnectionState();
884 switch (state) {
885 case kCsConnecting:
886 *error_out = "device still connecting";
887 result = nullptr;
888 break;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -0700889
Josh Gao7a7c5cb2018-05-04 16:04:49 -0700890 case kCsAuthorizing:
891 *error_out = "device still authorizing";
892 result = nullptr;
893 break;
894
895 case kCsUnauthorized: {
896 *error_out = "device unauthorized.\n";
897 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
898 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
899 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
900 *error_out += "\n";
901 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
902 *error_out += "Otherwise check for a confirmation dialog on your device.";
903 result = nullptr;
904 break;
905 }
906
907 case kCsOffline:
908 *error_out = "device offline";
909 result = nullptr;
910 break;
911
912 default:
913 break;
914 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800915 }
916
917 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700918 *error_out = "success";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800919 }
920
921 return result;
922}
923
Luis Hector Chavezda74b902018-04-17 14:25:04 -0700924bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
925 std::unique_lock<std::mutex> lock(mutex_);
926 ScopedAssumeLocked assume_locked(mutex_);
927 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
928 return connection_established_ready_;
929 }) && connection_established_;
930}
931
932void ConnectionWaitable::SetConnectionEstablished(bool success) {
933 {
934 std::lock_guard<std::mutex> lock(mutex_);
935 if (connection_established_ready_) return;
936 connection_established_ready_ = true;
937 connection_established_ = success;
938 D("connection established with %d", success);
939 }
940 cv_.notify_one();
941}
942
943atransport::~atransport() {
944 // If the connection callback had not been run before, run it now.
945 SetConnectionEstablished(false);
946}
947
Yabin Cui3cf1b362017-03-10 16:01:01 -0800948int atransport::Write(apacket* p) {
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700949 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cui3cf1b362017-03-10 16:01:01 -0800950}
951
Yabin Cuif2a9f9b2016-04-18 11:22:34 -0700952void atransport::Kick() {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700953 if (!kicked_.exchange(true)) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700954 D("kicking transport %p %s", this, this->serial.c_str());
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700955 this->connection()->Stop();
Yabin Cuif2a9f9b2016-04-18 11:22:34 -0700956 }
957}
958
Yabin Cui3cf1b362017-03-10 16:01:01 -0800959ConnectionState atransport::GetConnectionState() const {
960 return connection_state_;
961}
962
963void atransport::SetConnectionState(ConnectionState state) {
964 check_main_thread();
965 connection_state_ = state;
966}
967
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700968void atransport::SetConnection(std::unique_ptr<Connection> connection) {
969 std::lock_guard<std::mutex> lock(mutex_);
970 connection_ = std::shared_ptr<Connection>(std::move(connection));
971}
972
Josh Gao3cd03be2018-02-28 14:44:23 -0800973std::string atransport::connection_state_name() const {
Yabin Cui3cf1b362017-03-10 16:01:01 -0800974 ConnectionState state = GetConnectionState();
975 switch (state) {
Josh Gao0d6aa992016-11-22 14:32:34 -0800976 case kCsOffline:
977 return "offline";
978 case kCsBootloader:
979 return "bootloader";
980 case kCsDevice:
981 return "device";
982 case kCsHost:
983 return "host";
984 case kCsRecovery:
985 return "recovery";
986 case kCsNoPerm:
987 return UsbNoPermissionsShortHelpText();
988 case kCsSideload:
989 return "sideload";
990 case kCsUnauthorized:
991 return "unauthorized";
Josh Gao7a7c5cb2018-05-04 16:04:49 -0700992 case kCsAuthorizing:
993 return "authorizing";
994 case kCsConnecting:
995 return "connecting";
Josh Gao0d6aa992016-11-22 14:32:34 -0800996 default:
997 return "unknown";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800998 }
999}
1000
Tamas Berghammera1c60c02015-07-13 19:12:28 +01001001void atransport::update_version(int version, size_t payload) {
1002 protocol_version = std::min(version, A_VERSION);
1003 max_payload = std::min(payload, MAX_PAYLOAD);
1004}
1005
1006int atransport::get_protocol_version() const {
1007 return protocol_version;
1008}
1009
1010size_t atransport::get_max_payload() const {
1011 return max_payload;
1012}
1013
Dan Albertbe8e54b2015-05-18 13:06:53 -07001014const FeatureSet& supported_features() {
David Pursella07dbad2015-09-22 10:43:08 -07001015 // Local static allocation to avoid global non-POD variables.
1016 static const FeatureSet* features = new FeatureSet{
Alex Buynytskyye1fa8142019-01-17 13:13:56 -08001017 kFeatureShell2, kFeatureCmd, kFeatureStat2,
1018 kFeatureFixedPushMkdir, kFeatureApex, kFeatureAbb,
Josh Gao62add5b2018-11-08 22:39:43 -08001019 // Increment ADB_SERVER_VERSION when adding a feature that adbd needs
1020 // to know about. Otherwise, the client can be stuck running an old
1021 // version of the server even after upgrading their copy of adb.
1022 // (http://b/24370690)
David Pursella07dbad2015-09-22 10:43:08 -07001023 };
1024
1025 return *features;
1026}
1027
1028std::string FeatureSetToString(const FeatureSet& features) {
Elliott Hughesc3462f42018-09-05 12:13:11 -07001029 return android::base::Join(features, ',');
David Pursella07dbad2015-09-22 10:43:08 -07001030}
1031
1032FeatureSet StringToFeatureSet(const std::string& features_string) {
David Pursell3d9072b2015-09-25 13:04:21 -07001033 if (features_string.empty()) {
1034 return FeatureSet();
1035 }
1036
Elliott Hughesc3462f42018-09-05 12:13:11 -07001037 auto names = android::base::Split(features_string, ",");
David Pursella07dbad2015-09-22 10:43:08 -07001038 return FeatureSet(names.begin(), names.end());
Dan Albertbe8e54b2015-05-18 13:06:53 -07001039}
1040
David Pursell22fc5e92015-09-30 13:35:42 -07001041bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao0d6aa992016-11-22 14:32:34 -08001042 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell22fc5e92015-09-30 13:35:42 -07001043}
1044
Dan Albertbe8e54b2015-05-18 13:06:53 -07001045bool atransport::has_feature(const std::string& feature) const {
1046 return features_.count(feature) > 0;
1047}
1048
David Pursella07dbad2015-09-22 10:43:08 -07001049void atransport::SetFeatures(const std::string& features_string) {
1050 features_ = StringToFeatureSet(features_string);
Dan Albertbe8e54b2015-05-18 13:06:53 -07001051}
1052
Yabin Cui2d4c1982015-08-28 15:09:44 -07001053void atransport::AddDisconnect(adisconnect* disconnect) {
1054 disconnects_.push_back(disconnect);
1055}
1056
1057void atransport::RemoveDisconnect(adisconnect* disconnect) {
1058 disconnects_.remove(disconnect);
1059}
1060
1061void atransport::RunDisconnects() {
Elliott Hughes85952832015-10-07 15:59:35 -07001062 for (const auto& disconnect : disconnects_) {
Yabin Cui2d4c1982015-08-28 15:09:44 -07001063 disconnect->func(disconnect->opaque, this);
1064 }
1065 disconnects_.clear();
1066}
1067
David Pursellc929c6f2016-03-01 08:58:26 -08001068bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001069 if (!serial.empty()) {
David Pursellc929c6f2016-03-01 08:58:26 -08001070 if (target == serial) {
1071 return true;
1072 } else if (type == kTransportLocal) {
1073 // Local transports can match [tcp:|udp:]<hostname>[:port].
1074 const char* local_target_ptr = target.c_str();
1075
1076 // For fastboot compatibility, ignore protocol prefixes.
1077 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao0d6aa992016-11-22 14:32:34 -08001078 android::base::StartsWith(target, "udp:")) {
David Pursellc929c6f2016-03-01 08:58:26 -08001079 local_target_ptr += 4;
1080 }
1081
1082 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1083 std::string serial_host, error;
1084 int serial_port = -1;
Josh Gao0d6aa992016-11-22 14:32:34 -08001085 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursellc929c6f2016-03-01 08:58:26 -08001086 // |target| may omit the port to default to ours.
1087 std::string target_host;
1088 int target_port = serial_port;
1089 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1090 nullptr, &error) &&
Josh Gao0d6aa992016-11-22 14:32:34 -08001091 serial_host == target_host && serial_port == target_port) {
David Pursellc929c6f2016-03-01 08:58:26 -08001092 return true;
1093 }
1094 }
1095 }
1096 }
1097
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001098 return (target == devpath) || qual_match(target, "product:", product, false) ||
1099 qual_match(target, "model:", model, true) ||
1100 qual_match(target, "device:", device, false);
David Pursellc929c6f2016-03-01 08:58:26 -08001101}
1102
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001103void atransport::SetConnectionEstablished(bool success) {
1104 connection_waitable_->SetConnectionEstablished(success);
1105}
1106
Josh Gaod24580d2018-08-30 11:37:00 -07001107ReconnectResult atransport::Reconnect() {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001108 return reconnect_(this);
1109}
1110
Elliott Hughes88b4c852015-04-30 17:32:03 -07001111#if ADB_HOST
1112
Josh Gaob39e4152017-08-16 16:57:01 -07001113// We use newline as our delimiter, make sure to never output it.
1114static std::string sanitize(std::string str, bool alphanumeric) {
1115 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1116 : [](const char c) { return c == '\n'; };
1117 std::replace_if(str.begin(), str.end(), pred, '_');
1118 return str;
1119}
1120
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001121static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob39e4152017-08-16 16:57:01 -07001122 bool alphanumeric) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001123 if (value.empty()) {
Scott Anderson27042382012-05-30 18:11:27 -07001124 return;
Scott Anderson27042382012-05-30 18:11:27 -07001125 }
1126
Elliott Hughes88b4c852015-04-30 17:32:03 -07001127 *result += ' ';
1128 *result += key;
Josh Gaob39e4152017-08-16 16:57:01 -07001129 *result += sanitize(value, alphanumeric);
Scott Anderson27042382012-05-30 18:11:27 -07001130}
1131
Josh Gao0d6aa992016-11-22 14:32:34 -08001132static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001133 std::string serial = t->serial;
1134 if (serial.empty()) {
Dan Alberta8c34142015-05-06 16:48:52 -07001135 serial = "(no serial number)";
Elliott Hughes88b4c852015-04-30 17:32:03 -07001136 }
Scott Anderson27042382012-05-30 18:11:27 -07001137
1138 if (!long_listing) {
Elliott Hughes88b4c852015-04-30 17:32:03 -07001139 *result += serial;
1140 *result += '\t';
1141 *result += t->connection_state_name();
Scott Anderson27042382012-05-30 18:11:27 -07001142 } else {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001143 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1144 t->connection_state_name().c_str());
Scott Anderson27042382012-05-30 18:11:27 -07001145
Elliott Hughes88b4c852015-04-30 17:32:03 -07001146 append_transport_info(result, "", t->devpath, false);
1147 append_transport_info(result, "product:", t->product, false);
1148 append_transport_info(result, "model:", t->model, true);
1149 append_transport_info(result, "device:", t->device, false);
Josh Gaob39e4152017-08-16 16:57:01 -07001150
1151 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1152 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1153 *result += " transport_id:";
1154 *result += std::to_string(t->id);
Scott Anderson27042382012-05-30 18:11:27 -07001155 }
Elliott Hughes88b4c852015-04-30 17:32:03 -07001156 *result += '\n';
Scott Anderson27042382012-05-30 18:11:27 -07001157}
1158
Elliott Hughes88b4c852015-04-30 17:32:03 -07001159std::string list_transports(bool long_listing) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001160 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov4dd35012017-12-17 10:56:07 +00001161
1162 auto sorted_transport_list = transport_list;
1163 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1164 if (x->type != y->type) {
1165 return x->type < y->type;
1166 }
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001167 return x->serial < y->serial;
Artem Iglikov4dd35012017-12-17 10:56:07 +00001168 });
1169
1170 std::string result;
1171 for (const auto& t : sorted_transport_list) {
Elliott Hughes88b4c852015-04-30 17:32:03 -07001172 append_transport(t, &result, long_listing);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001173 }
Elliott Hughes88b4c852015-04-30 17:32:03 -07001174 return result;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001175}
1176
Josh Gao4e562502016-10-27 14:01:08 -07001177void close_usb_devices(std::function<bool(const atransport*)> predicate) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001178 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao4e562502016-10-27 14:01:08 -07001179 for (auto& t : transport_list) {
1180 if (predicate(t)) {
1181 t->Kick();
1182 }
1183 }
1184}
1185
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001186/* hack for osx */
Dan Albertecce5032015-05-18 16:46:31 -07001187void close_usb_devices() {
Josh Gao4e562502016-10-27 14:01:08 -07001188 close_usb_devices([](const atransport*) { return true; });
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001189}
Josh Gao0d6aa992016-11-22 14:32:34 -08001190#endif // ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001191
Josh Gao597044d2018-08-08 16:20:14 -07001192bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
1193 atransport::ReconnectCallback reconnect, int* error) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001194 atransport* t = new atransport(std::move(reconnect), kCsOffline);
David 'Digit' Turner58f59682011-01-06 14:11:07 +01001195
Josh Gaoa3a71472018-08-02 13:58:24 -07001196 D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
Josh Gaofa3107e2018-07-25 17:21:49 -07001197 if (init_socket_transport(t, std::move(s), port, local) < 0) {
Dan Albertecce5032015-05-18 16:46:31 -07001198 delete t;
Josh Gao597044d2018-08-08 16:20:14 -07001199 if (error) *error = errno;
1200 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001201 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001202
Josh Gaoaaa82f72017-08-17 13:50:51 -07001203 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes85952832015-10-07 15:59:35 -07001204 for (const auto& transport : pending_list) {
Josh Gaoa3a71472018-08-02 13:58:24 -07001205 if (serial == transport->serial) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001206 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao0d6aa992016-11-22 14:32:34 -08001207 << " is already in pending_list and fails to register";
Dan Albertecce5032015-05-18 16:46:31 -07001208 delete t;
Josh Gao597044d2018-08-08 16:20:14 -07001209 if (error) *error = EALREADY;
1210 return false;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001211 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001212 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001213
Elliott Hughes85952832015-10-07 15:59:35 -07001214 for (const auto& transport : transport_list) {
Josh Gaoa3a71472018-08-02 13:58:24 -07001215 if (serial == transport->serial) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001216 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao0d6aa992016-11-22 14:32:34 -08001217 << " is already in transport_list and fails to register";
Dan Albertecce5032015-05-18 16:46:31 -07001218 delete t;
Josh Gao597044d2018-08-08 16:20:14 -07001219 if (error) *error = EALREADY;
1220 return false;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001221 }
1222 }
1223
Josh Gaoa3a71472018-08-02 13:58:24 -07001224 t->serial = std::move(serial);
Dan Albertecce5032015-05-18 16:46:31 -07001225 pending_list.push_front(t);
Josh Gaoe7daf572016-09-21 12:37:10 -07001226
1227 lock.unlock();
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001228
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001229 auto waitable = t->connection_waitable();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001230 register_transport(t);
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001231
Luis Hector Chavez25bc41c2018-05-01 17:12:16 -07001232 if (local == 1) {
1233 // Do not wait for emulator transports.
Josh Gao597044d2018-08-08 16:20:14 -07001234 return true;
Luis Hector Chavez25bc41c2018-05-01 17:12:16 -07001235 }
1236
Josh Gao597044d2018-08-08 16:20:14 -07001237 if (!waitable->WaitForConnection(std::chrono::seconds(10))) {
1238 if (error) *error = ETIMEDOUT;
1239 return false;
1240 }
1241
1242 if (t->GetConnectionState() == kCsUnauthorized) {
1243 if (error) *error = EPERM;
1244 return false;
1245 }
1246
1247 return true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001248}
1249
Mike Lockwood81ffe172009-10-11 23:04:18 -04001250#if ADB_HOST
Josh Gao0d6aa992016-11-22 14:32:34 -08001251atransport* find_transport(const char* serial) {
Dan Albertecce5032015-05-18 16:46:31 -07001252 atransport* result = nullptr;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001253
Josh Gaoaaa82f72017-08-17 13:50:51 -07001254 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui4d64fd82015-08-27 12:03:11 -07001255 for (auto& t : transport_list) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001256 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertecce5032015-05-18 16:46:31 -07001257 result = t;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001258 break;
1259 }
Dan Albertecce5032015-05-18 16:46:31 -07001260 }
Mike Lockwood81ffe172009-10-11 23:04:18 -04001261
Dan Albertecce5032015-05-18 16:46:31 -07001262 return result;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001263}
1264
Yabin Cui4d64fd82015-08-27 12:03:11 -07001265void kick_all_tcp_devices() {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001266 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui4d64fd82015-08-27 12:03:11 -07001267 for (auto& t : transport_list) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001268 if (t->IsTcpDevice()) {
Yabin Cui4e222292015-08-31 11:50:24 -07001269 // Kicking breaks the read_transport thread of this transport out of any read, then
1270 // the read_transport thread will notify the main thread to make this transport
1271 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cui4d64fd82015-08-27 12:03:11 -07001272 // Finally, this transport will be closed and freed in the main thread.
Yabin Cuif2a9f9b2016-04-18 11:22:34 -07001273 t->Kick();
Mike Lockwood01c2c302010-05-24 10:44:35 -04001274 }
Dan Albertecce5032015-05-18 16:46:31 -07001275 }
Josh Gao13cb8c02018-08-10 14:44:54 -07001276#if ADB_HOST
1277 reconnect_handler.CheckForKicked();
1278#endif
Mike Lockwood01c2c302010-05-24 10:44:35 -04001279}
1280
Mike Lockwood81ffe172009-10-11 23:04:18 -04001281#endif
1282
Josh Gao0d6aa992016-11-22 14:32:34 -08001283void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1284 unsigned writeable) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001285 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertecce5032015-05-18 16:46:31 -07001286
Josh Gao0d6aa992016-11-22 14:32:34 -08001287 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cui3cf1b362017-03-10 16:01:01 -08001288 init_usb_transport(t, usb);
Josh Gao0d6aa992016-11-22 14:32:34 -08001289 if (serial) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001290 t->serial = serial;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001291 }
Dan Albertecce5032015-05-18 16:46:31 -07001292
1293 if (devpath) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001294 t->devpath = devpath;
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001295 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001296
Josh Gaoe7daf572016-09-21 12:37:10 -07001297 {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001298 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaoe7daf572016-09-21 12:37:10 -07001299 pending_list.push_front(t);
1300 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001301
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001302 register_transport(t);
1303}
1304
Josh Gao3a34bc52018-10-11 16:33:05 -07001305#if ADB_HOST
Dan Albert9a50f4c2015-05-18 16:43:57 -07001306// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao0d6aa992016-11-22 14:32:34 -08001307void unregister_usb_transport(usb_handle* usb) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001308 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao395b86a2018-01-28 20:32:46 -08001309 transport_list.remove_if([usb](atransport* t) {
Josh Gao68f2c382018-12-11 13:11:52 -08001310 return t->GetUsbHandle() == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gao395b86a2018-01-28 20:32:46 -08001311 });
Mike Lockwoode45583f2009-08-08 12:37:44 -04001312}
Josh Gao3a34bc52018-10-11 16:33:05 -07001313#endif
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001314
Josh Gao67b683a2017-05-16 15:02:45 -07001315bool check_header(apacket* p, atransport* t) {
Josh Gao0d6aa992016-11-22 14:32:34 -08001316 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cui3cf1b362017-03-10 16:01:01 -08001317 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1318 << ", magic = " << p->msg.magic;
Josh Gao67b683a2017-05-16 15:02:45 -07001319 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001320 }
1321
Josh Gao0d6aa992016-11-22 14:32:34 -08001322 if (p->msg.data_length > t->get_max_payload()) {
1323 VLOG(RWX) << "check_header(): " << p->msg.data_length
1324 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao67b683a2017-05-16 15:02:45 -07001325 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001326 }
1327
Josh Gao67b683a2017-05-16 15:02:45 -07001328 return true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001329}
1330
Josh Gaoeac20582016-10-05 19:02:29 -07001331#if ADB_HOST
Josh Gao22cb70b2016-08-18 22:00:12 -07001332std::shared_ptr<RSA> atransport::NextKey() {
Josh Gaoeb656522018-12-04 01:07:50 -08001333 if (keys_.empty()) {
1334 LOG(INFO) << "fetching keys for transport " << this->serial_name();
1335 keys_ = adb_auth_get_private_keys();
1336
1337 // We should have gotten at least one key: the one that's automatically generated.
1338 CHECK(!keys_.empty());
1339 }
Elliott Hughes801066a2016-06-29 17:42:01 -07001340
Josh Gao22cb70b2016-08-18 22:00:12 -07001341 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes801066a2016-06-29 17:42:01 -07001342 keys_.pop_front();
1343 return result;
1344}
Josh Gaoeb656522018-12-04 01:07:50 -08001345
1346void atransport::ResetKeys() {
1347 keys_.clear();
1348}
Josh Gaoeac20582016-10-05 19:02:29 -07001349#endif