blob: 4cd19f9788d9283d06147182edeac466b6fa603d [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#include "sysdeps/memory.h"
21
Dan Albert76649012015-02-24 15:51:19 -080022#include "transport.h"
23
Dan Albert055f1aa2015-02-20 17:24:58 -080024#include <ctype.h>
Dan Albert76649012015-02-24 15:51:19 -080025#include <errno.h>
Josh Gaob122b172017-08-16 16:57:01 -070026#include <inttypes.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080027#include <stdio.h>
28#include <stdlib.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080029#include <string.h>
Dan Albert76649012015-02-24 15:51:19 -080030#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080031
Spencer Low363af562015-11-07 18:51:54 -080032#include <algorithm>
Josh Gao0bbf69c2018-02-16 13:24:58 -080033#include <deque>
Dan Albertc7915a32015-05-18 16:46:31 -070034#include <list>
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
Elliott Hughes4f713192015-12-04 22:00:26 -080039#include <android-base/logging.h>
David Pursell3f902aa2016-03-01 08:58:26 -080040#include <android-base/parsenetaddress.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080041#include <android-base/stringprintf.h>
42#include <android-base/strings.h>
Josh Gaob122b172017-08-16 16:57:01 -070043#include <android-base/thread_annotations.h>
Elliott Hughese67f1f82015-04-30 17:32:03 -070044
Josh Gao27768452018-01-02 12:01:43 -080045#include <diagnose_usb.h>
46
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080047#include "adb.h"
Elliott Hughes0aeb5052016-06-29 17:42:01 -070048#include "adb_auth.h"
Josh Gaob800d882018-01-28 20:32:46 -080049#include "adb_io.h"
Josh Gaocfe72e22016-11-29 09:40:29 -080050#include "adb_trace.h"
Elliott Hughese67f1f82015-04-30 17:32:03 -070051#include "adb_utils.h"
Yabin Cuib5e11412017-03-10 16:01:01 -080052#include "fdevent.h"
Josh Gaoe445a6d2018-07-31 14:12:59 -070053#include "sysdeps/chrono.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080054
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070055static void register_transport(atransport* transport);
56static void remove_transport(atransport* transport);
57static void transport_unref(atransport* transport);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080058
Josh Gaob122b172017-08-16 16:57:01 -070059// TODO: unordered_map<TransportId, atransport*>
Josh Gaob7b1edf2015-11-11 17:56:12 -080060static auto& transport_list = *new std::list<atransport*>();
61static auto& pending_list = *new std::list<atransport*>();
Benoit Goby1c45ee92013-03-29 18:22:36 -070062
Josh Gao1db71af2017-08-17 13:50:51 -070063static auto& transport_lock = *new std::recursive_mutex();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080064
Todd Kennedy51c05ec2015-11-10 00:03:25 +000065const char* const kFeatureShell2 = "shell_v2";
66const char* const kFeatureCmd = "cmd";
Josh Gao5a1e3fd2016-12-05 17:11:34 -080067const char* const kFeatureStat2 = "stat_v2";
Josh Gao5d1756c2017-02-22 17:07:01 -080068const char* const kFeatureLibusb = "libusb";
Dan Albert5176df82017-05-23 14:30:00 -070069const char* const kFeaturePushSync = "push_sync";
Todd Kennedy51c05ec2015-11-10 00:03:25 +000070
Luis Hector Chavez56fe7532018-04-17 14:25:04 -070071namespace {
72
73// A class that helps the Clang Thread Safety Analysis deal with
74// std::unique_lock. Given that std::unique_lock is movable, and the analysis
75// can not currently perform alias analysis, it is not annotated. In order to
76// assert that the mutex is held, a ScopedAssumeLocked can be created just after
77// the std::unique_lock.
78class SCOPED_CAPABILITY ScopedAssumeLocked {
79 public:
80 ScopedAssumeLocked(std::mutex& mutex) ACQUIRE(mutex) {}
81 ~ScopedAssumeLocked() RELEASE() {}
82};
83
Josh Gaodef91c02018-07-31 18:28:32 -070084#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070085// Tracks and handles atransport*s that are attempting reconnection.
86class ReconnectHandler {
87 public:
88 ReconnectHandler() = default;
89 ~ReconnectHandler() = default;
90
91 // Starts the ReconnectHandler thread.
92 void Start();
93
94 // Requests the ReconnectHandler thread to stop.
95 void Stop();
96
97 // Adds the atransport* to the queue of reconnect attempts.
98 void TrackTransport(atransport* transport);
99
100 private:
101 // The main thread loop.
102 void Run();
103
104 // Tracks a reconnection attempt.
105 struct ReconnectAttempt {
106 atransport* transport;
Josh Gao95af6412018-07-30 18:51:55 -0700107 std::chrono::steady_clock::time_point reconnect_time;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700108 size_t attempts_left;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700109
110 bool operator<(const ReconnectAttempt& rhs) const {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700111 if (reconnect_time == rhs.reconnect_time) {
112 return reinterpret_cast<uintptr_t>(transport) <
113 reinterpret_cast<uintptr_t>(rhs.transport);
114 }
115 return reconnect_time < rhs.reconnect_time;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700116 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700117 };
118
119 // Only retry for up to one minute.
Josh Gaoe445a6d2018-07-31 14:12:59 -0700120 static constexpr const std::chrono::seconds kDefaultTimeout = 10s;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700121 static constexpr const size_t kMaxAttempts = 6;
122
123 // Protects all members.
124 std::mutex reconnect_mutex_;
125 bool running_ GUARDED_BY(reconnect_mutex_) = true;
126 std::thread handler_thread_;
127 std::condition_variable reconnect_cv_;
Josh Gao8a40c8a2018-08-10 14:28:24 -0700128 std::set<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700129
130 DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
131};
132
133void ReconnectHandler::Start() {
134 check_main_thread();
135 handler_thread_ = std::thread(&ReconnectHandler::Run, this);
136}
137
138void ReconnectHandler::Stop() {
139 check_main_thread();
140 {
141 std::lock_guard<std::mutex> lock(reconnect_mutex_);
142 running_ = false;
143 }
144 reconnect_cv_.notify_one();
145 handler_thread_.join();
146
147 // Drain the queue to free all resources.
148 std::lock_guard<std::mutex> lock(reconnect_mutex_);
149 while (!reconnect_queue_.empty()) {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700150 ReconnectAttempt attempt = *reconnect_queue_.begin();
151 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700152 remove_transport(attempt.transport);
153 }
154}
155
156void ReconnectHandler::TrackTransport(atransport* transport) {
157 check_main_thread();
158 {
159 std::lock_guard<std::mutex> lock(reconnect_mutex_);
160 if (!running_) return;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700161 // Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
162 auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
163 reconnect_queue_.emplace(
164 ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700165 }
166 reconnect_cv_.notify_one();
167}
168
169void ReconnectHandler::Run() {
170 while (true) {
171 ReconnectAttempt attempt;
172 {
173 std::unique_lock<std::mutex> lock(reconnect_mutex_);
174 ScopedAssumeLocked assume_lock(reconnect_mutex_);
175
Josh Gao95af6412018-07-30 18:51:55 -0700176 if (!reconnect_queue_.empty()) {
177 // FIXME: libstdc++ (used on Windows) implements condition_variable with
178 // system_clock as its clock, so we're probably hosed if the clock changes,
179 // even if we use steady_clock throughout. This problem goes away once we
180 // switch to libc++.
Josh Gao8a40c8a2018-08-10 14:28:24 -0700181 reconnect_cv_.wait_until(lock, reconnect_queue_.begin()->reconnect_time);
Josh Gao95af6412018-07-30 18:51:55 -0700182 } else {
183 reconnect_cv_.wait(lock);
184 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700185
186 if (!running_) return;
Josh Gao95af6412018-07-30 18:51:55 -0700187 if (reconnect_queue_.empty()) continue;
188
189 // Go back to sleep in case |reconnect_cv_| woke up spuriously and we still
190 // have more time to wait for the current attempt.
191 auto now = std::chrono::steady_clock::now();
Josh Gao8a40c8a2018-08-10 14:28:24 -0700192 if (reconnect_queue_.begin()->reconnect_time > now) {
Josh Gao95af6412018-07-30 18:51:55 -0700193 continue;
194 }
195
Josh Gao8a40c8a2018-08-10 14:28:24 -0700196 attempt = *reconnect_queue_.begin();
197 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700198 if (attempt.transport->kicked()) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700199 D("transport %s was kicked. giving up on it.", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700200 remove_transport(attempt.transport);
201 continue;
202 }
203 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700204 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700205
206 if (!attempt.transport->Reconnect()) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700207 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700208 if (attempt.attempts_left == 0) {
209 D("transport %s exceeded the number of retry attempts. giving up on it.",
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700210 attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700211 remove_transport(attempt.transport);
212 continue;
213 }
214
215 std::lock_guard<std::mutex> lock(reconnect_mutex_);
216 reconnect_queue_.emplace(ReconnectAttempt{
Josh Gao95af6412018-07-30 18:51:55 -0700217 attempt.transport,
218 std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
219 attempt.attempts_left - 1});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700220 continue;
221 }
222
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700223 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700224 register_transport(attempt.transport);
225 }
226}
227
228static auto& reconnect_handler = *new ReconnectHandler();
229
Josh Gaodef91c02018-07-31 18:28:32 -0700230#endif
231
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700232} // namespace
233
Josh Gaob122b172017-08-16 16:57:01 -0700234TransportId NextTransportId() {
235 static std::atomic<TransportId> next(1);
236 return next++;
237}
238
Josh Gao0bbf69c2018-02-16 13:24:58 -0800239BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
240 : underlying_(std::move(connection)) {}
241
242BlockingConnectionAdapter::~BlockingConnectionAdapter() {
243 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
244 Stop();
245}
246
247void BlockingConnectionAdapter::Start() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700248 std::lock_guard<std::mutex> lock(mutex_);
249 if (started_) {
250 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
251 << "): started multiple times";
252 }
253
Josh Gao0bbf69c2018-02-16 13:24:58 -0800254 read_thread_ = std::thread([this]() {
255 LOG(INFO) << this->transport_name_ << ": read thread spawning";
256 while (true) {
Josh Gao31b5be62018-03-07 16:51:08 -0800257 auto packet = std::make_unique<apacket>();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800258 if (!underlying_->Read(packet.get())) {
259 PLOG(INFO) << this->transport_name_ << ": read failed";
260 break;
261 }
262 read_callback_(this, std::move(packet));
263 }
264 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
265 });
266
267 write_thread_ = std::thread([this]() {
268 LOG(INFO) << this->transport_name_ << ": write thread spawning";
269 while (true) {
270 std::unique_lock<std::mutex> lock(mutex_);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700271 ScopedAssumeLocked assume_locked(mutex_);
Josh Gaoc251ec52018-04-03 12:55:18 -0700272 cv_.wait(lock, [this]() REQUIRES(mutex_) {
273 return this->stopped_ || !this->write_queue_.empty();
274 });
275
Josh Gao0bbf69c2018-02-16 13:24:58 -0800276 if (this->stopped_) {
277 return;
278 }
279
280 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
281 this->write_queue_.pop_front();
282 lock.unlock();
283
284 if (!this->underlying_->Write(packet.get())) {
285 break;
286 }
287 }
288 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
289 });
Josh Gaoc251ec52018-04-03 12:55:18 -0700290
291 started_ = true;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800292}
293
294void BlockingConnectionAdapter::Stop() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700295 {
296 std::lock_guard<std::mutex> lock(mutex_);
297 if (!started_) {
298 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
299 return;
300 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800301
Josh Gaoc251ec52018-04-03 12:55:18 -0700302 if (stopped_) {
303 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
304 << "): already stopped";
305 return;
306 }
307
308 stopped_ = true;
309 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800310
311 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
312
313 this->underlying_->Close();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800314 this->cv_.notify_one();
Josh Gaoc251ec52018-04-03 12:55:18 -0700315
316 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
317 std::thread read_thread;
318 std::thread write_thread;
319
320 {
321 std::lock_guard<std::mutex> lock(mutex_);
322 read_thread = std::move(read_thread_);
323 write_thread = std::move(write_thread_);
324 }
325
326 read_thread.join();
327 write_thread.join();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800328
329 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
330 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
331}
332
333bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
334 {
Josh Gaoc251ec52018-04-03 12:55:18 -0700335 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800336 write_queue_.emplace_back(std::move(packet));
337 }
338
339 cv_.notify_one();
340 return true;
341}
342
Josh Gaob800d882018-01-28 20:32:46 -0800343bool FdConnection::Read(apacket* packet) {
344 if (!ReadFdExactly(fd_.get(), &packet->msg, sizeof(amessage))) {
345 D("remote local: read terminated (message)");
346 return false;
347 }
348
Josh Gaof571fcb2018-02-05 18:49:10 -0800349 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gao5caaebd2018-02-02 14:38:04 -0800350 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
351 return false;
352 }
353
Josh Gaof571fcb2018-02-05 18:49:10 -0800354 packet->payload.resize(packet->msg.data_length);
355
356 if (!ReadFdExactly(fd_.get(), &packet->payload[0], packet->payload.size())) {
Josh Gaob800d882018-01-28 20:32:46 -0800357 D("remote local: terminated (data)");
358 return false;
359 }
360
361 return true;
362}
363
364bool FdConnection::Write(apacket* packet) {
Josh Gaof571fcb2018-02-05 18:49:10 -0800365 if (!WriteFdExactly(fd_.get(), &packet->msg, sizeof(packet->msg))) {
Josh Gaob800d882018-01-28 20:32:46 -0800366 D("remote local: write terminated");
367 return false;
368 }
369
Josh Gaof571fcb2018-02-05 18:49:10 -0800370 if (packet->msg.data_length) {
371 if (!WriteFdExactly(fd_.get(), &packet->payload[0], packet->msg.data_length)) {
372 D("remote local: write terminated");
373 return false;
374 }
375 }
376
Josh Gaob800d882018-01-28 20:32:46 -0800377 return true;
378}
379
380void FdConnection::Close() {
381 adb_shutdown(fd_.get());
382 fd_.reset();
383}
384
Yabin Cuiaed3c612015-09-22 15:52:57 -0700385static std::string dump_packet(const char* name, const char* func, apacket* p) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800386 unsigned command = p->msg.command;
387 int len = p->msg.data_length;
388 char cmd[9];
389 char arg0[12], arg1[12];
390 int n;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100391
392 for (n = 0; n < 4; n++) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800393 int b = (command >> (n * 8)) & 255;
394 if (b < 32 || b >= 127) break;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100395 cmd[n] = (char)b;
396 }
397 if (n == 4) {
398 cmd[4] = 0;
399 } else {
400 /* There is some non-ASCII name in the command, so dump
401 * the hexadecimal value instead */
402 snprintf(cmd, sizeof cmd, "%08x", command);
403 }
404
405 if (p->msg.arg0 < 256U)
406 snprintf(arg0, sizeof arg0, "%d", p->msg.arg0);
407 else
408 snprintf(arg0, sizeof arg0, "0x%x", p->msg.arg0);
409
410 if (p->msg.arg1 < 256U)
411 snprintf(arg1, sizeof arg1, "%d", p->msg.arg1);
412 else
413 snprintf(arg1, sizeof arg1, "0x%x", p->msg.arg1);
414
Josh Gao1290fbf2016-11-22 14:32:34 -0800415 std::string result = android::base::StringPrintf("%s: %s: [%s] arg0=%s arg1=%s (len=%d) ", name,
416 func, cmd, arg0, arg1, len);
Josh Gaof571fcb2018-02-05 18:49:10 -0800417 result += dump_hex(p->payload.data(), p->payload.size());
Yabin Cuiaed3c612015-09-22 15:52:57 -0700418 return result;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100419}
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100420
Josh Gao06d61d42016-10-06 13:31:44 -0700421void send_packet(apacket* p, atransport* t) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800422 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayde471942017-12-07 11:40:00 -0800423 // compute a checksum for connection/auth packets for compatibility reasons
424 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
425 p->msg.data_check = 0;
426 } else {
427 p->msg.data_check = calculate_apacket_checksum(p);
428 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800429
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700430 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800431
Yi Kongaed415c2018-07-13 18:15:16 -0700432 if (t == nullptr) {
Josh Gao06d61d42016-10-06 13:31:44 -0700433 fatal("Transport is null");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800434 }
435
Josh Gao0bbf69c2018-02-16 13:24:58 -0800436 if (t->Write(p) != 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700437 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800438 t->Kick();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800439 }
440}
441
Yabin Cuif4b99282015-08-27 12:03:11 -0700442void kick_transport(atransport* t) {
Josh Gao1db71af2017-08-17 13:50:51 -0700443 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui1f4ec192016-04-05 13:50:44 -0700444 // As kick_transport() can be called from threads without guarantee that t is valid,
445 // check if the transport is in transport_list first.
Josh Gaob122b172017-08-16 16:57:01 -0700446 //
447 // TODO(jmgao): WTF? Is this actually true?
Yabin Cui1f4ec192016-04-05 13:50:44 -0700448 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Yabin Cui7f274902016-04-18 11:22:34 -0700449 t->Kick();
Yabin Cui1f4ec192016-04-05 13:50:44 -0700450 }
Yabin Cuif4b99282015-08-27 12:03:11 -0700451}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800452
453static int transport_registration_send = -1;
454static int transport_registration_recv = -1;
Josh Gao71f775a2018-05-14 11:14:33 -0700455static fdevent* transport_registration_fde;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800456
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800457#if ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800458
459/* this adds support required by the 'track-devices' service.
460 * this is used to send the content of "list_transport" to any
461 * number of client connections that want it through a single
462 * live TCP connection
463 */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800464struct device_tracker {
Josh Gao1290fbf2016-11-22 14:32:34 -0800465 asocket socket;
Josh Gaoe0361d12018-02-12 17:24:00 -0800466 bool update_needed = false;
467 bool long_output = false;
468 device_tracker* next = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800469};
470
471/* linked list of all device trackers */
Josh Gao1290fbf2016-11-22 14:32:34 -0800472static device_tracker* device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800473
Josh Gao1290fbf2016-11-22 14:32:34 -0800474static void device_tracker_remove(device_tracker* tracker) {
475 device_tracker** pnode = &device_tracker_list;
476 device_tracker* node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800477
Josh Gao1db71af2017-08-17 13:50:51 -0700478 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800479 while (node) {
480 if (node == tracker) {
481 *pnode = node->next;
482 break;
483 }
484 pnode = &node->next;
Josh Gao1290fbf2016-11-22 14:32:34 -0800485 node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800486 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800487}
488
Josh Gao1290fbf2016-11-22 14:32:34 -0800489static void device_tracker_close(asocket* socket) {
490 device_tracker* tracker = (device_tracker*)socket;
491 asocket* peer = socket->peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800492
Josh Gao1290fbf2016-11-22 14:32:34 -0800493 D("device tracker %p removed", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800494 if (peer) {
Yi Kongaed415c2018-07-13 18:15:16 -0700495 peer->peer = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800496 peer->close(peer);
497 }
498 device_tracker_remove(tracker);
Josh Gaoe0361d12018-02-12 17:24:00 -0800499 delete tracker;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800500}
501
Josh Gao1ce99572018-03-07 16:52:28 -0800502static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800503 /* you can't read from a device tracker, close immediately */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800504 device_tracker_close(socket);
505 return -1;
506}
507
Elliott Hughese67f1f82015-04-30 17:32:03 -0700508static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700509 asocket* peer = tracker->socket.peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800510
Josh Gao1ce99572018-03-07 16:52:28 -0800511 apacket::payload_type data;
Josh Gao27cb7dc2018-02-01 13:17:50 -0800512 data.resize(4 + string.size());
513 char buf[5];
514 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
515 memcpy(&data[0], buf, 4);
516 memcpy(&data[4], string.data(), string.size());
517 return peer->enqueue(peer, std::move(data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800518}
519
Elliott Hughese67f1f82015-04-30 17:32:03 -0700520static void device_tracker_ready(asocket* socket) {
521 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800522
Elliott Hughese67f1f82015-04-30 17:32:03 -0700523 // We want to send the device list when the tracker connects
524 // for the first time, even if no update occurred.
Josh Gaob0c18022017-08-14 18:57:54 -0700525 if (tracker->update_needed) {
526 tracker->update_needed = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800527
Josh Gaob0c18022017-08-14 18:57:54 -0700528 std::string transports = list_transports(tracker->long_output);
Elliott Hughese67f1f82015-04-30 17:32:03 -0700529 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800530 }
531}
532
Josh Gaob0c18022017-08-14 18:57:54 -0700533asocket* create_device_tracker(bool long_output) {
Josh Gaoe0361d12018-02-12 17:24:00 -0800534 device_tracker* tracker = new device_tracker();
Elliott Hughesdc3b4592015-04-21 19:39:52 -0700535 if (tracker == nullptr) fatal("cannot allocate device tracker");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800536
Josh Gao1290fbf2016-11-22 14:32:34 -0800537 D("device tracker %p created", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800538
539 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao1290fbf2016-11-22 14:32:34 -0800540 tracker->socket.ready = device_tracker_ready;
541 tracker->socket.close = device_tracker_close;
Josh Gaob0c18022017-08-14 18:57:54 -0700542 tracker->update_needed = true;
543 tracker->long_output = long_output;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800544
Josh Gao1290fbf2016-11-22 14:32:34 -0800545 tracker->next = device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800546 device_tracker_list = tracker;
547
548 return &tracker->socket;
549}
550
Josh Gaofd713e52017-05-03 22:37:10 -0700551// Check if all of the USB transports are connected.
552bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gao1db71af2017-08-17 13:50:51 -0700553 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaofd713e52017-05-03 22:37:10 -0700554 for (const auto& t : transport_list) {
555 if (!fn(t)) {
556 return false;
557 }
558 }
559 for (const auto& t : pending_list) {
560 if (!fn(t)) {
561 return false;
562 }
563 }
564 return true;
565}
566
Elliott Hughese67f1f82015-04-30 17:32:03 -0700567// Call this function each time the transport list has changed.
568void update_transports() {
Josh Gaofd713e52017-05-03 22:37:10 -0700569 update_transport_status();
570
571 // Notify `adb track-devices` clients.
Elliott Hughese67f1f82015-04-30 17:32:03 -0700572 std::string transports = list_transports(false);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800573
Elliott Hughese67f1f82015-04-30 17:32:03 -0700574 device_tracker* tracker = device_tracker_list;
575 while (tracker != nullptr) {
576 device_tracker* next = tracker->next;
577 // This may destroy the tracker if the connection is closed.
578 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800579 tracker = next;
580 }
581}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700582
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800583#else
Elliott Hughese67f1f82015-04-30 17:32:03 -0700584
585void update_transports() {
586 // Nothing to do on the device side.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800587}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700588
Josh Gao1290fbf2016-11-22 14:32:34 -0800589#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800590
Josh Gao1290fbf2016-11-22 14:32:34 -0800591struct tmsg {
592 atransport* transport;
593 int action;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800594};
595
Josh Gao1290fbf2016-11-22 14:32:34 -0800596static int transport_read_action(int fd, struct tmsg* m) {
597 char* p = (char*)m;
598 int len = sizeof(*m);
599 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800600
Josh Gao1290fbf2016-11-22 14:32:34 -0800601 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800602 r = adb_read(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800603 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800604 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800605 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800606 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700607 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800608 return -1;
609 }
610 }
611 return 0;
612}
613
Josh Gao1290fbf2016-11-22 14:32:34 -0800614static int transport_write_action(int fd, struct tmsg* m) {
615 char* p = (char*)m;
616 int len = sizeof(*m);
617 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800618
Josh Gao1290fbf2016-11-22 14:32:34 -0800619 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800620 r = adb_write(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800621 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800622 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800623 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800624 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700625 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800626 return -1;
627 }
628 }
629 return 0;
630}
631
Josh Gao0bbf69c2018-02-16 13:24:58 -0800632static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800633 tmsg m;
Josh Gao1290fbf2016-11-22 14:32:34 -0800634 atransport* t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800635
Josh Gao1290fbf2016-11-22 14:32:34 -0800636 if (!(ev & FDE_READ)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800637 return;
638 }
639
Josh Gao1290fbf2016-11-22 14:32:34 -0800640 if (transport_read_action(_fd, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800641 fatal_errno("cannot read transport registration socket");
642 }
643
644 t = m.transport;
645
Dan Albert1792c232015-05-18 13:06:53 -0700646 if (m.action == 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700647 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800648
Josh Gao0cd3ae12016-09-21 12:37:10 -0700649 {
Josh Gao1db71af2017-08-17 13:50:51 -0700650 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700651 transport_list.remove(t);
652 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800653
Dan Albertc7915a32015-05-18 16:46:31 -0700654 delete t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800655
656 update_transports();
657 return;
658 }
659
Mike Lockwood0927bf92009-08-08 12:37:44 -0400660 /* don't create transport threads for inaccessible devices */
Yabin Cuib5e11412017-03-10 16:01:01 -0800661 if (t->GetConnectionState() != kCsNoPerm) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700662 // The connection gets a reference to the atransport. It will release it
663 // upon a read/write error.
664 t->ref_count++;
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700665 t->connection()->SetTransportName(t->serial_name());
666 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao0bbf69c2018-02-16 13:24:58 -0800667 if (!check_header(p.get(), t)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700668 D("%s: remote read: bad header", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800669 return false;
670 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800671
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700672 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "from remote", p.get());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800673 apacket* packet = p.release();
Mike Lockwood0927bf92009-08-08 12:37:44 -0400674
Josh Gao0bbf69c2018-02-16 13:24:58 -0800675 // TODO: Does this need to run on the main thread?
676 fdevent_run_on_main_thread([packet, t]() { handle_packet(packet, t); });
677 return true;
678 });
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700679 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700680 D("%s: connection terminated: %s", t->serial.c_str(), error.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800681 fdevent_run_on_main_thread([t]() {
682 handle_offline(t);
683 transport_unref(t);
684 });
685 });
Mike Lockwood0927bf92009-08-08 12:37:44 -0400686
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700687 t->connection()->Start();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800688#if ADB_HOST
689 send_connect(t);
690#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800691 }
692
Josh Gao0cd3ae12016-09-21 12:37:10 -0700693 {
Josh Gao1db71af2017-08-17 13:50:51 -0700694 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700695 auto it = std::find(pending_list.begin(), pending_list.end(), t);
696 if (it != pending_list.end()) {
697 pending_list.remove(t);
698 transport_list.push_front(t);
699 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700700 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800701
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800702 update_transports();
703}
704
Josh Gaodef91c02018-07-31 18:28:32 -0700705#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700706void init_reconnect_handler(void) {
707 reconnect_handler.Start();
708}
Josh Gaodef91c02018-07-31 18:28:32 -0700709#endif
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700710
Josh Gao1290fbf2016-11-22 14:32:34 -0800711void init_transport_registration(void) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800712 int s[2];
713
Josh Gao1290fbf2016-11-22 14:32:34 -0800714 if (adb_socketpair(s)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800715 fatal_errno("cannot open transport registration socketpair");
716 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700717 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800718
719 transport_registration_send = s[0];
720 transport_registration_recv = s[1];
721
Josh Gao71f775a2018-05-14 11:14:33 -0700722 transport_registration_fde =
Yi Kongaed415c2018-07-13 18:15:16 -0700723 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao71f775a2018-05-14 11:14:33 -0700724 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao01b7bc42017-05-09 13:43:35 -0700725}
726
727void kick_all_transports() {
Josh Gaodef91c02018-07-31 18:28:32 -0700728#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700729 reconnect_handler.Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700730#endif
Josh Gao01b7bc42017-05-09 13:43:35 -0700731 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gao1db71af2017-08-17 13:50:51 -0700732 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao01b7bc42017-05-09 13:43:35 -0700733 for (auto t : transport_list) {
734 t->Kick();
735 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800736}
737
738/* the fdevent select pump is single threaded */
Josh Gao1290fbf2016-11-22 14:32:34 -0800739static void register_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800740 tmsg m;
741 m.transport = transport;
742 m.action = 1;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700743 D("transport: %s registered", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800744 if (transport_write_action(transport_registration_send, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800745 fatal_errno("cannot write transport registration socket\n");
746 }
747}
748
Josh Gao1290fbf2016-11-22 14:32:34 -0800749static void remove_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800750 tmsg m;
751 m.transport = transport;
752 m.action = 0;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700753 D("transport: %s removed", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800754 if (transport_write_action(transport_registration_send, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800755 fatal_errno("cannot write transport registration socket\n");
756 }
757}
758
Yabin Cuif4b99282015-08-27 12:03:11 -0700759static void transport_unref(atransport* t) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700760 check_main_thread();
Yabin Cuif4b99282015-08-27 12:03:11 -0700761 CHECK(t != nullptr);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700762
Josh Gaoe48ecce2017-09-13 13:40:57 -0700763 std::lock_guard<std::recursive_mutex> lock(transport_lock);
764 CHECK_GT(t->ref_count, 0u);
765 t->ref_count--;
766 if (t->ref_count == 0) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700767 t->connection()->Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700768#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700769 if (t->IsTcpDevice() && !t->kicked()) {
Josh Gaodef91c02018-07-31 18:28:32 -0700770 D("transport: %s unref (attempting reconnection)", t->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700771 reconnect_handler.TrackTransport(t);
772 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700773 D("transport: %s unref (kicking and closing)", t->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700774 remove_transport(t);
775 }
Josh Gaodef91c02018-07-31 18:28:32 -0700776#else
777 D("transport: %s unref (kicking and closing)", t->serial.c_str());
778 remove_transport(t);
779#endif
780
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100781 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700782 D("transport: %s unref (count=%zu)", t->serial.c_str(), t->ref_count);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -0400783 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800784}
785
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700786static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao1290fbf2016-11-22 14:32:34 -0800787 bool sanitize_qual) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700788 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
789 return qual.empty();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700790
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700791 if (qual.empty()) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700792
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700793 const char* ptr = to_test.c_str();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700794 if (prefix) {
795 while (*prefix) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700796 if (*prefix++ != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700797 }
798 }
799
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700800 for (char ch : qual) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800801 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700802 if (ch != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700803 }
804
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700805 /* Everything matched so far. Return true if *ptr is a NUL. */
806 return !*ptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700807}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800808
Josh Gaob122b172017-08-16 16:57:01 -0700809atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
810 bool* is_ambiguous, std::string* error_out,
811 bool accept_any_state) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700812 atransport* result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800813
Josh Gaob122b172017-08-16 16:57:01 -0700814 if (transport_id != 0) {
815 *error_out =
816 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
817 } else if (serial) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700818 *error_out = android::base::StringPrintf("device '%s' not found", serial);
819 } else if (type == kTransportLocal) {
820 *error_out = "no emulators found";
821 } else if (type == kTransportAny) {
822 *error_out = "no devices/emulators found";
823 } else {
824 *error_out = "no devices found";
825 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800826
Josh Gao1db71af2017-08-17 13:50:51 -0700827 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes8d28e192015-10-07 14:55:10 -0700828 for (const auto& t : transport_list) {
Yabin Cuib5e11412017-03-10 16:01:01 -0800829 if (t->GetConnectionState() == kCsNoPerm) {
David Purselld2acbd12015-12-02 15:14:31 -0800830 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwood37d31112009-08-08 13:53:16 -0400831 continue;
832 }
Mike Lockwood0927bf92009-08-08 12:37:44 -0400833
Josh Gaob122b172017-08-16 16:57:01 -0700834 if (transport_id) {
835 if (t->id == transport_id) {
836 result = t;
837 break;
838 }
839 } else if (serial) {
David Pursell3f902aa2016-03-01 08:58:26 -0800840 if (t->MatchesTarget(serial)) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700841 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700842 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700843 if (is_ambiguous) *is_ambiguous = true;
844 result = nullptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700845 break;
846 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800847 result = t;
Scott Andersone109d262012-04-20 11:21:14 -0700848 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800849 } else {
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700850 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800851 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700852 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700853 if (is_ambiguous) *is_ambiguous = true;
854 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800855 break;
856 }
857 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700858 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800859 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700860 *error_out = "more than one emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700861 if (is_ambiguous) *is_ambiguous = true;
862 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800863 break;
864 }
865 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700866 } else if (type == kTransportAny) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800867 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700868 *error_out = "more than one device/emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700869 if (is_ambiguous) *is_ambiguous = true;
870 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800871 break;
872 }
873 result = t;
874 }
875 }
876 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700877 lock.unlock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800878
Josh Gao704494b2018-05-04 16:04:49 -0700879 if (result && !accept_any_state) {
880 // The caller requires an active transport.
881 // Make sure that we're actually connected.
882 ConnectionState state = result->GetConnectionState();
883 switch (state) {
884 case kCsConnecting:
885 *error_out = "device still connecting";
886 result = nullptr;
887 break;
Benoit Goby77e8e582013-01-15 12:36:47 -0800888
Josh Gao704494b2018-05-04 16:04:49 -0700889 case kCsAuthorizing:
890 *error_out = "device still authorizing";
891 result = nullptr;
892 break;
893
894 case kCsUnauthorized: {
895 *error_out = "device unauthorized.\n";
896 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
897 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
898 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
899 *error_out += "\n";
900 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
901 *error_out += "Otherwise check for a confirmation dialog on your device.";
902 result = nullptr;
903 break;
904 }
905
906 case kCsOffline:
907 *error_out = "device offline";
908 result = nullptr;
909 break;
910
911 default:
912 break;
913 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800914 }
915
916 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700917 *error_out = "success";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800918 }
919
920 return result;
921}
922
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700923bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
924 std::unique_lock<std::mutex> lock(mutex_);
925 ScopedAssumeLocked assume_locked(mutex_);
926 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
927 return connection_established_ready_;
928 }) && connection_established_;
929}
930
931void ConnectionWaitable::SetConnectionEstablished(bool success) {
932 {
933 std::lock_guard<std::mutex> lock(mutex_);
934 if (connection_established_ready_) return;
935 connection_established_ready_ = true;
936 connection_established_ = success;
937 D("connection established with %d", success);
938 }
939 cv_.notify_one();
940}
941
942atransport::~atransport() {
943 // If the connection callback had not been run before, run it now.
944 SetConnectionEstablished(false);
945}
946
Yabin Cuib5e11412017-03-10 16:01:01 -0800947int atransport::Write(apacket* p) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700948 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cuib5e11412017-03-10 16:01:01 -0800949}
950
Yabin Cui7f274902016-04-18 11:22:34 -0700951void atransport::Kick() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700952 if (!kicked_.exchange(true)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700953 D("kicking transport %p %s", this, this->serial.c_str());
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700954 this->connection()->Stop();
Yabin Cui7f274902016-04-18 11:22:34 -0700955 }
956}
957
Yabin Cuib5e11412017-03-10 16:01:01 -0800958ConnectionState atransport::GetConnectionState() const {
959 return connection_state_;
960}
961
962void atransport::SetConnectionState(ConnectionState state) {
963 check_main_thread();
964 connection_state_ = state;
965}
966
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700967void atransport::SetConnection(std::unique_ptr<Connection> connection) {
968 std::lock_guard<std::mutex> lock(mutex_);
969 connection_ = std::shared_ptr<Connection>(std::move(connection));
970}
971
Josh Gaoffbd3362018-02-28 14:44:23 -0800972std::string atransport::connection_state_name() const {
Yabin Cuib5e11412017-03-10 16:01:01 -0800973 ConnectionState state = GetConnectionState();
974 switch (state) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800975 case kCsOffline:
976 return "offline";
977 case kCsBootloader:
978 return "bootloader";
979 case kCsDevice:
980 return "device";
981 case kCsHost:
982 return "host";
983 case kCsRecovery:
984 return "recovery";
985 case kCsNoPerm:
986 return UsbNoPermissionsShortHelpText();
987 case kCsSideload:
988 return "sideload";
989 case kCsUnauthorized:
990 return "unauthorized";
Josh Gao704494b2018-05-04 16:04:49 -0700991 case kCsAuthorizing:
992 return "authorizing";
993 case kCsConnecting:
994 return "connecting";
Josh Gao1290fbf2016-11-22 14:32:34 -0800995 default:
996 return "unknown";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800997 }
998}
999
Tamas Berghammer3d2904c2015-07-13 19:12:28 +01001000void atransport::update_version(int version, size_t payload) {
1001 protocol_version = std::min(version, A_VERSION);
1002 max_payload = std::min(payload, MAX_PAYLOAD);
1003}
1004
1005int atransport::get_protocol_version() const {
1006 return protocol_version;
1007}
1008
1009size_t atransport::get_max_payload() const {
1010 return max_payload;
1011}
1012
David Pursell4e2fd362015-09-22 10:43:08 -07001013namespace {
David Pursell0955c662015-08-31 10:42:13 -07001014
David Pursell4e2fd362015-09-22 10:43:08 -07001015constexpr char kFeatureStringDelimiter = ',';
1016
1017} // namespace
Dan Albert1792c232015-05-18 13:06:53 -07001018
1019const FeatureSet& supported_features() {
David Pursell4e2fd362015-09-22 10:43:08 -07001020 // Local static allocation to avoid global non-POD variables.
1021 static const FeatureSet* features = new FeatureSet{
Josh Gao1290fbf2016-11-22 14:32:34 -08001022 kFeatureShell2, kFeatureCmd, kFeatureStat2,
David Pursellbbe3d212015-09-25 08:37:13 -07001023 // Increment ADB_SERVER_VERSION whenever the feature list changes to
1024 // make sure that the adb client and server features stay in sync
1025 // (http://b/24370690).
David Pursell4e2fd362015-09-22 10:43:08 -07001026 };
1027
1028 return *features;
1029}
1030
1031std::string FeatureSetToString(const FeatureSet& features) {
1032 return android::base::Join(features, kFeatureStringDelimiter);
1033}
1034
1035FeatureSet StringToFeatureSet(const std::string& features_string) {
David Purselld2b588e2015-09-25 13:04:21 -07001036 if (features_string.empty()) {
1037 return FeatureSet();
1038 }
1039
Josh Gao1290fbf2016-11-22 14:32:34 -08001040 auto names = android::base::Split(features_string, {kFeatureStringDelimiter});
David Pursell4e2fd362015-09-22 10:43:08 -07001041 return FeatureSet(names.begin(), names.end());
Dan Albert1792c232015-05-18 13:06:53 -07001042}
1043
David Pursell70ef7b42015-09-30 13:35:42 -07001044bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001045 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell70ef7b42015-09-30 13:35:42 -07001046}
1047
Dan Albert1792c232015-05-18 13:06:53 -07001048bool atransport::has_feature(const std::string& feature) const {
1049 return features_.count(feature) > 0;
1050}
1051
David Pursell4e2fd362015-09-22 10:43:08 -07001052void atransport::SetFeatures(const std::string& features_string) {
1053 features_ = StringToFeatureSet(features_string);
Dan Albert1792c232015-05-18 13:06:53 -07001054}
1055
Yabin Cuib3298242015-08-28 15:09:44 -07001056void atransport::AddDisconnect(adisconnect* disconnect) {
1057 disconnects_.push_back(disconnect);
1058}
1059
1060void atransport::RemoveDisconnect(adisconnect* disconnect) {
1061 disconnects_.remove(disconnect);
1062}
1063
1064void atransport::RunDisconnects() {
Elliott Hughes65fe2512015-10-07 15:59:35 -07001065 for (const auto& disconnect : disconnects_) {
Yabin Cuib3298242015-08-28 15:09:44 -07001066 disconnect->func(disconnect->opaque, this);
1067 }
1068 disconnects_.clear();
1069}
1070
David Pursell3f902aa2016-03-01 08:58:26 -08001071bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001072 if (!serial.empty()) {
David Pursell3f902aa2016-03-01 08:58:26 -08001073 if (target == serial) {
1074 return true;
1075 } else if (type == kTransportLocal) {
1076 // Local transports can match [tcp:|udp:]<hostname>[:port].
1077 const char* local_target_ptr = target.c_str();
1078
1079 // For fastboot compatibility, ignore protocol prefixes.
1080 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao1290fbf2016-11-22 14:32:34 -08001081 android::base::StartsWith(target, "udp:")) {
David Pursell3f902aa2016-03-01 08:58:26 -08001082 local_target_ptr += 4;
1083 }
1084
1085 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1086 std::string serial_host, error;
1087 int serial_port = -1;
Josh Gao1290fbf2016-11-22 14:32:34 -08001088 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursell3f902aa2016-03-01 08:58:26 -08001089 // |target| may omit the port to default to ours.
1090 std::string target_host;
1091 int target_port = serial_port;
1092 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1093 nullptr, &error) &&
Josh Gao1290fbf2016-11-22 14:32:34 -08001094 serial_host == target_host && serial_port == target_port) {
David Pursell3f902aa2016-03-01 08:58:26 -08001095 return true;
1096 }
1097 }
1098 }
1099 }
1100
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001101 return (target == devpath) || qual_match(target, "product:", product, false) ||
1102 qual_match(target, "model:", model, true) ||
1103 qual_match(target, "device:", device, false);
David Pursell3f902aa2016-03-01 08:58:26 -08001104}
1105
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001106void atransport::SetConnectionEstablished(bool success) {
1107 connection_waitable_->SetConnectionEstablished(success);
1108}
1109
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001110bool atransport::Reconnect() {
1111 return reconnect_(this);
1112}
1113
Elliott Hughese67f1f82015-04-30 17:32:03 -07001114#if ADB_HOST
1115
Josh Gaob122b172017-08-16 16:57:01 -07001116// We use newline as our delimiter, make sure to never output it.
1117static std::string sanitize(std::string str, bool alphanumeric) {
1118 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1119 : [](const char c) { return c == '\n'; };
1120 std::replace_if(str.begin(), str.end(), pred, '_');
1121 return str;
1122}
1123
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001124static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob122b172017-08-16 16:57:01 -07001125 bool alphanumeric) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001126 if (value.empty()) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001127 return;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001128 }
1129
Elliott Hughese67f1f82015-04-30 17:32:03 -07001130 *result += ' ';
1131 *result += key;
Josh Gaob122b172017-08-16 16:57:01 -07001132 *result += sanitize(value, alphanumeric);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001133}
1134
Josh Gao1290fbf2016-11-22 14:32:34 -08001135static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001136 std::string serial = t->serial;
1137 if (serial.empty()) {
Dan Albertd99d9022015-05-06 16:48:52 -07001138 serial = "(no serial number)";
Elliott Hughese67f1f82015-04-30 17:32:03 -07001139 }
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001140
1141 if (!long_listing) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001142 *result += serial;
1143 *result += '\t';
1144 *result += t->connection_state_name();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001145 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001146 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1147 t->connection_state_name().c_str());
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001148
Elliott Hughese67f1f82015-04-30 17:32:03 -07001149 append_transport_info(result, "", t->devpath, false);
1150 append_transport_info(result, "product:", t->product, false);
1151 append_transport_info(result, "model:", t->model, true);
1152 append_transport_info(result, "device:", t->device, false);
Josh Gaob122b172017-08-16 16:57:01 -07001153
1154 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1155 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1156 *result += " transport_id:";
1157 *result += std::to_string(t->id);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001158 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001159 *result += '\n';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001160}
1161
Elliott Hughese67f1f82015-04-30 17:32:03 -07001162std::string list_transports(bool long_listing) {
Josh Gao1db71af2017-08-17 13:50:51 -07001163 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov04398a92017-12-17 10:56:07 +00001164
1165 auto sorted_transport_list = transport_list;
1166 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1167 if (x->type != y->type) {
1168 return x->type < y->type;
1169 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001170 return x->serial < y->serial;
Artem Iglikov04398a92017-12-17 10:56:07 +00001171 });
1172
1173 std::string result;
1174 for (const auto& t : sorted_transport_list) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001175 append_transport(t, &result, long_listing);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001176 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001177 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001178}
1179
Josh Gao22d2b3e2016-10-27 14:01:08 -07001180void close_usb_devices(std::function<bool(const atransport*)> predicate) {
Josh Gao1db71af2017-08-17 13:50:51 -07001181 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao22d2b3e2016-10-27 14:01:08 -07001182 for (auto& t : transport_list) {
1183 if (predicate(t)) {
1184 t->Kick();
1185 }
1186 }
1187}
1188
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001189/* hack for osx */
Dan Albertc7915a32015-05-18 16:46:31 -07001190void close_usb_devices() {
Josh Gao22d2b3e2016-10-27 14:01:08 -07001191 close_usb_devices([](const atransport*) { return true; });
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001192}
Josh Gao1290fbf2016-11-22 14:32:34 -08001193#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001194
Josh Gao362e6962018-08-08 16:20:14 -07001195bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
1196 atransport::ReconnectCallback reconnect, int* error) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001197 atransport* t = new atransport(std::move(reconnect), kCsOffline);
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +01001198
Josh Gao3b4de3c2018-08-02 13:58:24 -07001199 D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
Josh Gao56300c92018-07-25 17:21:49 -07001200 if (init_socket_transport(t, std::move(s), port, local) < 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001201 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001202 if (error) *error = errno;
1203 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001204 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001205
Josh Gao1db71af2017-08-17 13:50:51 -07001206 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes65fe2512015-10-07 15:59:35 -07001207 for (const auto& transport : pending_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001208 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001209 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001210 << " is already in pending_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001211 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001212 if (error) *error = EALREADY;
1213 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001214 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001215 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001216
Elliott Hughes65fe2512015-10-07 15:59:35 -07001217 for (const auto& transport : transport_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001218 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001219 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001220 << " is already in transport_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001221 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001222 if (error) *error = EALREADY;
1223 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001224 }
1225 }
1226
Josh Gao3b4de3c2018-08-02 13:58:24 -07001227 t->serial = std::move(serial);
Dan Albertc7915a32015-05-18 16:46:31 -07001228 pending_list.push_front(t);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001229
1230 lock.unlock();
Benoit Goby1c45ee92013-03-29 18:22:36 -07001231
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001232 auto waitable = t->connection_waitable();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001233 register_transport(t);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001234
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001235 if (local == 1) {
1236 // Do not wait for emulator transports.
Josh Gao362e6962018-08-08 16:20:14 -07001237 return true;
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001238 }
1239
Josh Gao362e6962018-08-08 16:20:14 -07001240 if (!waitable->WaitForConnection(std::chrono::seconds(10))) {
1241 if (error) *error = ETIMEDOUT;
1242 return false;
1243 }
1244
1245 if (t->GetConnectionState() == kCsUnauthorized) {
1246 if (error) *error = EPERM;
1247 return false;
1248 }
1249
1250 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001251}
1252
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001253#if ADB_HOST
Josh Gao1290fbf2016-11-22 14:32:34 -08001254atransport* find_transport(const char* serial) {
Dan Albertc7915a32015-05-18 16:46:31 -07001255 atransport* result = nullptr;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001256
Josh Gao1db71af2017-08-17 13:50:51 -07001257 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001258 for (auto& t : transport_list) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001259 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001260 result = t;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001261 break;
1262 }
Dan Albertc7915a32015-05-18 16:46:31 -07001263 }
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001264
Dan Albertc7915a32015-05-18 16:46:31 -07001265 return result;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001266}
1267
Yabin Cuif4b99282015-08-27 12:03:11 -07001268void kick_all_tcp_devices() {
Josh Gao1db71af2017-08-17 13:50:51 -07001269 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001270 for (auto& t : transport_list) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001271 if (t->IsTcpDevice()) {
Yabin Cuid6ab3c22015-08-31 11:50:24 -07001272 // Kicking breaks the read_transport thread of this transport out of any read, then
1273 // the read_transport thread will notify the main thread to make this transport
1274 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cuif4b99282015-08-27 12:03:11 -07001275 // Finally, this transport will be closed and freed in the main thread.
Yabin Cui7f274902016-04-18 11:22:34 -07001276 t->Kick();
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001277 }
Dan Albertc7915a32015-05-18 16:46:31 -07001278 }
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001279}
1280
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001281#endif
1282
Josh Gao1290fbf2016-11-22 14:32:34 -08001283void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1284 unsigned writeable) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001285 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertc7915a32015-05-18 16:46:31 -07001286
Josh Gao1290fbf2016-11-22 14:32:34 -08001287 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cuib5e11412017-03-10 16:01:01 -08001288 init_usb_transport(t, usb);
Josh Gao1290fbf2016-11-22 14:32:34 -08001289 if (serial) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001290 t->serial = serial;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001291 }
Dan Albertc7915a32015-05-18 16:46:31 -07001292
1293 if (devpath) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001294 t->devpath = devpath;
Scott Andersone109d262012-04-20 11:21:14 -07001295 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001296
Josh Gao0cd3ae12016-09-21 12:37:10 -07001297 {
Josh Gao1db71af2017-08-17 13:50:51 -07001298 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001299 pending_list.push_front(t);
1300 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001301
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001302 register_transport(t);
1303}
1304
Dan Albertdcd78a12015-05-18 16:43:57 -07001305// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao1290fbf2016-11-22 14:32:34 -08001306void unregister_usb_transport(usb_handle* usb) {
Josh Gao1db71af2017-08-17 13:50:51 -07001307 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaob800d882018-01-28 20:32:46 -08001308 transport_list.remove_if([usb](atransport* t) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -07001309 auto connection = t->connection();
1310 if (auto usb_connection = dynamic_cast<UsbConnection*>(connection.get())) {
1311 return usb_connection->handle_ == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gaob800d882018-01-28 20:32:46 -08001312 }
1313 return false;
1314 });
Mike Lockwood0927bf92009-08-08 12:37:44 -04001315}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001316
Josh Gao36dadca2017-05-16 15:02:45 -07001317bool check_header(apacket* p, atransport* t) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001318 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cuib5e11412017-03-10 16:01:01 -08001319 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1320 << ", magic = " << p->msg.magic;
Josh Gao36dadca2017-05-16 15:02:45 -07001321 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001322 }
1323
Josh Gao1290fbf2016-11-22 14:32:34 -08001324 if (p->msg.data_length > t->get_max_payload()) {
1325 VLOG(RWX) << "check_header(): " << p->msg.data_length
1326 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao36dadca2017-05-16 15:02:45 -07001327 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001328 }
1329
Josh Gao36dadca2017-05-16 15:02:45 -07001330 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001331}
1332
Josh Gao3bd28792016-10-05 19:02:29 -07001333#if ADB_HOST
Josh Gao2e671202016-08-18 22:00:12 -07001334std::shared_ptr<RSA> atransport::NextKey() {
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001335 if (keys_.empty()) keys_ = adb_auth_get_private_keys();
1336
Josh Gao2e671202016-08-18 22:00:12 -07001337 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001338 keys_.pop_front();
1339 return result;
1340}
Josh Gao3bd28792016-10-05 19:02:29 -07001341#endif