blob: 3c74c75910180f29ff9e2d230074755762fad060 [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>
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070036#include <queue>
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 {
111 // std::priority_queue returns the largest element first, so we want attempts that have
112 // less time remaining (i.e. smaller time_points) to compare greater.
113 return reconnect_time > rhs.reconnect_time;
114 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700115 };
116
117 // Only retry for up to one minute.
Josh Gaoe445a6d2018-07-31 14:12:59 -0700118 static constexpr const std::chrono::seconds kDefaultTimeout = 10s;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700119 static constexpr const size_t kMaxAttempts = 6;
120
121 // Protects all members.
122 std::mutex reconnect_mutex_;
123 bool running_ GUARDED_BY(reconnect_mutex_) = true;
124 std::thread handler_thread_;
125 std::condition_variable reconnect_cv_;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700126 std::priority_queue<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700127
128 DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
129};
130
131void ReconnectHandler::Start() {
132 check_main_thread();
133 handler_thread_ = std::thread(&ReconnectHandler::Run, this);
134}
135
136void ReconnectHandler::Stop() {
137 check_main_thread();
138 {
139 std::lock_guard<std::mutex> lock(reconnect_mutex_);
140 running_ = false;
141 }
142 reconnect_cv_.notify_one();
143 handler_thread_.join();
144
145 // Drain the queue to free all resources.
146 std::lock_guard<std::mutex> lock(reconnect_mutex_);
147 while (!reconnect_queue_.empty()) {
Josh Gaoe445a6d2018-07-31 14:12:59 -0700148 ReconnectAttempt attempt = reconnect_queue_.top();
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700149 reconnect_queue_.pop();
150 remove_transport(attempt.transport);
151 }
152}
153
154void ReconnectHandler::TrackTransport(atransport* transport) {
155 check_main_thread();
156 {
157 std::lock_guard<std::mutex> lock(reconnect_mutex_);
158 if (!running_) return;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700159 // Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
160 auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
161 reconnect_queue_.emplace(
162 ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700163 }
164 reconnect_cv_.notify_one();
165}
166
167void ReconnectHandler::Run() {
168 while (true) {
169 ReconnectAttempt attempt;
170 {
171 std::unique_lock<std::mutex> lock(reconnect_mutex_);
172 ScopedAssumeLocked assume_lock(reconnect_mutex_);
173
Josh Gao95af6412018-07-30 18:51:55 -0700174 if (!reconnect_queue_.empty()) {
175 // FIXME: libstdc++ (used on Windows) implements condition_variable with
176 // system_clock as its clock, so we're probably hosed if the clock changes,
177 // even if we use steady_clock throughout. This problem goes away once we
178 // switch to libc++.
Josh Gaoe445a6d2018-07-31 14:12:59 -0700179 reconnect_cv_.wait_until(lock, reconnect_queue_.top().reconnect_time);
Josh Gao95af6412018-07-30 18:51:55 -0700180 } else {
181 reconnect_cv_.wait(lock);
182 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700183
184 if (!running_) return;
Josh Gao95af6412018-07-30 18:51:55 -0700185 if (reconnect_queue_.empty()) continue;
186
187 // Go back to sleep in case |reconnect_cv_| woke up spuriously and we still
188 // have more time to wait for the current attempt.
189 auto now = std::chrono::steady_clock::now();
Josh Gaoe445a6d2018-07-31 14:12:59 -0700190 if (reconnect_queue_.top().reconnect_time > now) {
Josh Gao95af6412018-07-30 18:51:55 -0700191 continue;
192 }
193
Josh Gaoe445a6d2018-07-31 14:12:59 -0700194 attempt = reconnect_queue_.top();
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700195 reconnect_queue_.pop();
196 if (attempt.transport->kicked()) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700197 D("transport %s was kicked. giving up on it.", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700198 remove_transport(attempt.transport);
199 continue;
200 }
201 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700202 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700203
204 if (!attempt.transport->Reconnect()) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700205 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700206 if (attempt.attempts_left == 0) {
207 D("transport %s exceeded the number of retry attempts. giving up on it.",
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700208 attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700209 remove_transport(attempt.transport);
210 continue;
211 }
212
213 std::lock_guard<std::mutex> lock(reconnect_mutex_);
214 reconnect_queue_.emplace(ReconnectAttempt{
Josh Gao95af6412018-07-30 18:51:55 -0700215 attempt.transport,
216 std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
217 attempt.attempts_left - 1});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700218 continue;
219 }
220
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700221 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700222 register_transport(attempt.transport);
223 }
224}
225
226static auto& reconnect_handler = *new ReconnectHandler();
227
Josh Gaodef91c02018-07-31 18:28:32 -0700228#endif
229
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700230} // namespace
231
Josh Gaob122b172017-08-16 16:57:01 -0700232TransportId NextTransportId() {
233 static std::atomic<TransportId> next(1);
234 return next++;
235}
236
Josh Gao0bbf69c2018-02-16 13:24:58 -0800237BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
238 : underlying_(std::move(connection)) {}
239
240BlockingConnectionAdapter::~BlockingConnectionAdapter() {
241 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
242 Stop();
243}
244
245void BlockingConnectionAdapter::Start() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700246 std::lock_guard<std::mutex> lock(mutex_);
247 if (started_) {
248 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
249 << "): started multiple times";
250 }
251
Josh Gao0bbf69c2018-02-16 13:24:58 -0800252 read_thread_ = std::thread([this]() {
253 LOG(INFO) << this->transport_name_ << ": read thread spawning";
254 while (true) {
Josh Gao31b5be62018-03-07 16:51:08 -0800255 auto packet = std::make_unique<apacket>();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800256 if (!underlying_->Read(packet.get())) {
257 PLOG(INFO) << this->transport_name_ << ": read failed";
258 break;
259 }
260 read_callback_(this, std::move(packet));
261 }
262 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
263 });
264
265 write_thread_ = std::thread([this]() {
266 LOG(INFO) << this->transport_name_ << ": write thread spawning";
267 while (true) {
268 std::unique_lock<std::mutex> lock(mutex_);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700269 ScopedAssumeLocked assume_locked(mutex_);
Josh Gaoc251ec52018-04-03 12:55:18 -0700270 cv_.wait(lock, [this]() REQUIRES(mutex_) {
271 return this->stopped_ || !this->write_queue_.empty();
272 });
273
Josh Gao0bbf69c2018-02-16 13:24:58 -0800274 if (this->stopped_) {
275 return;
276 }
277
278 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
279 this->write_queue_.pop_front();
280 lock.unlock();
281
282 if (!this->underlying_->Write(packet.get())) {
283 break;
284 }
285 }
286 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
287 });
Josh Gaoc251ec52018-04-03 12:55:18 -0700288
289 started_ = true;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800290}
291
292void BlockingConnectionAdapter::Stop() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700293 {
294 std::lock_guard<std::mutex> lock(mutex_);
295 if (!started_) {
296 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
297 return;
298 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800299
Josh Gaoc251ec52018-04-03 12:55:18 -0700300 if (stopped_) {
301 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
302 << "): already stopped";
303 return;
304 }
305
306 stopped_ = true;
307 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800308
309 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
310
311 this->underlying_->Close();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800312 this->cv_.notify_one();
Josh Gaoc251ec52018-04-03 12:55:18 -0700313
314 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
315 std::thread read_thread;
316 std::thread write_thread;
317
318 {
319 std::lock_guard<std::mutex> lock(mutex_);
320 read_thread = std::move(read_thread_);
321 write_thread = std::move(write_thread_);
322 }
323
324 read_thread.join();
325 write_thread.join();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800326
327 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
328 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
329}
330
331bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
332 {
Josh Gaoc251ec52018-04-03 12:55:18 -0700333 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800334 write_queue_.emplace_back(std::move(packet));
335 }
336
337 cv_.notify_one();
338 return true;
339}
340
Josh Gaob800d882018-01-28 20:32:46 -0800341bool FdConnection::Read(apacket* packet) {
342 if (!ReadFdExactly(fd_.get(), &packet->msg, sizeof(amessage))) {
343 D("remote local: read terminated (message)");
344 return false;
345 }
346
Josh Gaof571fcb2018-02-05 18:49:10 -0800347 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gao5caaebd2018-02-02 14:38:04 -0800348 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
349 return false;
350 }
351
Josh Gaof571fcb2018-02-05 18:49:10 -0800352 packet->payload.resize(packet->msg.data_length);
353
354 if (!ReadFdExactly(fd_.get(), &packet->payload[0], packet->payload.size())) {
Josh Gaob800d882018-01-28 20:32:46 -0800355 D("remote local: terminated (data)");
356 return false;
357 }
358
359 return true;
360}
361
362bool FdConnection::Write(apacket* packet) {
Josh Gaof571fcb2018-02-05 18:49:10 -0800363 if (!WriteFdExactly(fd_.get(), &packet->msg, sizeof(packet->msg))) {
Josh Gaob800d882018-01-28 20:32:46 -0800364 D("remote local: write terminated");
365 return false;
366 }
367
Josh Gaof571fcb2018-02-05 18:49:10 -0800368 if (packet->msg.data_length) {
369 if (!WriteFdExactly(fd_.get(), &packet->payload[0], packet->msg.data_length)) {
370 D("remote local: write terminated");
371 return false;
372 }
373 }
374
Josh Gaob800d882018-01-28 20:32:46 -0800375 return true;
376}
377
378void FdConnection::Close() {
379 adb_shutdown(fd_.get());
380 fd_.reset();
381}
382
Yabin Cuiaed3c612015-09-22 15:52:57 -0700383static std::string dump_packet(const char* name, const char* func, apacket* p) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800384 unsigned command = p->msg.command;
385 int len = p->msg.data_length;
386 char cmd[9];
387 char arg0[12], arg1[12];
388 int n;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100389
390 for (n = 0; n < 4; n++) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800391 int b = (command >> (n * 8)) & 255;
392 if (b < 32 || b >= 127) break;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100393 cmd[n] = (char)b;
394 }
395 if (n == 4) {
396 cmd[4] = 0;
397 } else {
398 /* There is some non-ASCII name in the command, so dump
399 * the hexadecimal value instead */
400 snprintf(cmd, sizeof cmd, "%08x", command);
401 }
402
403 if (p->msg.arg0 < 256U)
404 snprintf(arg0, sizeof arg0, "%d", p->msg.arg0);
405 else
406 snprintf(arg0, sizeof arg0, "0x%x", p->msg.arg0);
407
408 if (p->msg.arg1 < 256U)
409 snprintf(arg1, sizeof arg1, "%d", p->msg.arg1);
410 else
411 snprintf(arg1, sizeof arg1, "0x%x", p->msg.arg1);
412
Josh Gao1290fbf2016-11-22 14:32:34 -0800413 std::string result = android::base::StringPrintf("%s: %s: [%s] arg0=%s arg1=%s (len=%d) ", name,
414 func, cmd, arg0, arg1, len);
Josh Gaof571fcb2018-02-05 18:49:10 -0800415 result += dump_hex(p->payload.data(), p->payload.size());
Yabin Cuiaed3c612015-09-22 15:52:57 -0700416 return result;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100417}
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100418
Josh Gao06d61d42016-10-06 13:31:44 -0700419void send_packet(apacket* p, atransport* t) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800420 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayde471942017-12-07 11:40:00 -0800421 // compute a checksum for connection/auth packets for compatibility reasons
422 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
423 p->msg.data_check = 0;
424 } else {
425 p->msg.data_check = calculate_apacket_checksum(p);
426 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800427
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700428 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800429
Yi Kongaed415c2018-07-13 18:15:16 -0700430 if (t == nullptr) {
Josh Gao06d61d42016-10-06 13:31:44 -0700431 fatal("Transport is null");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800432 }
433
Josh Gao0bbf69c2018-02-16 13:24:58 -0800434 if (t->Write(p) != 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700435 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800436 t->Kick();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800437 }
438}
439
Yabin Cuif4b99282015-08-27 12:03:11 -0700440void kick_transport(atransport* t) {
Josh Gao1db71af2017-08-17 13:50:51 -0700441 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui1f4ec192016-04-05 13:50:44 -0700442 // As kick_transport() can be called from threads without guarantee that t is valid,
443 // check if the transport is in transport_list first.
Josh Gaob122b172017-08-16 16:57:01 -0700444 //
445 // TODO(jmgao): WTF? Is this actually true?
Yabin Cui1f4ec192016-04-05 13:50:44 -0700446 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Yabin Cui7f274902016-04-18 11:22:34 -0700447 t->Kick();
Yabin Cui1f4ec192016-04-05 13:50:44 -0700448 }
Yabin Cuif4b99282015-08-27 12:03:11 -0700449}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800450
451static int transport_registration_send = -1;
452static int transport_registration_recv = -1;
Josh Gao71f775a2018-05-14 11:14:33 -0700453static fdevent* transport_registration_fde;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800454
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800455#if ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800456
457/* this adds support required by the 'track-devices' service.
458 * this is used to send the content of "list_transport" to any
459 * number of client connections that want it through a single
460 * live TCP connection
461 */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800462struct device_tracker {
Josh Gao1290fbf2016-11-22 14:32:34 -0800463 asocket socket;
Josh Gaoe0361d12018-02-12 17:24:00 -0800464 bool update_needed = false;
465 bool long_output = false;
466 device_tracker* next = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800467};
468
469/* linked list of all device trackers */
Josh Gao1290fbf2016-11-22 14:32:34 -0800470static device_tracker* device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800471
Josh Gao1290fbf2016-11-22 14:32:34 -0800472static void device_tracker_remove(device_tracker* tracker) {
473 device_tracker** pnode = &device_tracker_list;
474 device_tracker* node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800475
Josh Gao1db71af2017-08-17 13:50:51 -0700476 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800477 while (node) {
478 if (node == tracker) {
479 *pnode = node->next;
480 break;
481 }
482 pnode = &node->next;
Josh Gao1290fbf2016-11-22 14:32:34 -0800483 node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800484 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800485}
486
Josh Gao1290fbf2016-11-22 14:32:34 -0800487static void device_tracker_close(asocket* socket) {
488 device_tracker* tracker = (device_tracker*)socket;
489 asocket* peer = socket->peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800490
Josh Gao1290fbf2016-11-22 14:32:34 -0800491 D("device tracker %p removed", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800492 if (peer) {
Yi Kongaed415c2018-07-13 18:15:16 -0700493 peer->peer = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800494 peer->close(peer);
495 }
496 device_tracker_remove(tracker);
Josh Gaoe0361d12018-02-12 17:24:00 -0800497 delete tracker;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800498}
499
Josh Gao1ce99572018-03-07 16:52:28 -0800500static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800501 /* you can't read from a device tracker, close immediately */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800502 device_tracker_close(socket);
503 return -1;
504}
505
Elliott Hughese67f1f82015-04-30 17:32:03 -0700506static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700507 asocket* peer = tracker->socket.peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800508
Josh Gao1ce99572018-03-07 16:52:28 -0800509 apacket::payload_type data;
Josh Gao27cb7dc2018-02-01 13:17:50 -0800510 data.resize(4 + string.size());
511 char buf[5];
512 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
513 memcpy(&data[0], buf, 4);
514 memcpy(&data[4], string.data(), string.size());
515 return peer->enqueue(peer, std::move(data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800516}
517
Elliott Hughese67f1f82015-04-30 17:32:03 -0700518static void device_tracker_ready(asocket* socket) {
519 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800520
Elliott Hughese67f1f82015-04-30 17:32:03 -0700521 // We want to send the device list when the tracker connects
522 // for the first time, even if no update occurred.
Josh Gaob0c18022017-08-14 18:57:54 -0700523 if (tracker->update_needed) {
524 tracker->update_needed = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800525
Josh Gaob0c18022017-08-14 18:57:54 -0700526 std::string transports = list_transports(tracker->long_output);
Elliott Hughese67f1f82015-04-30 17:32:03 -0700527 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800528 }
529}
530
Josh Gaob0c18022017-08-14 18:57:54 -0700531asocket* create_device_tracker(bool long_output) {
Josh Gaoe0361d12018-02-12 17:24:00 -0800532 device_tracker* tracker = new device_tracker();
Elliott Hughesdc3b4592015-04-21 19:39:52 -0700533 if (tracker == nullptr) fatal("cannot allocate device tracker");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800534
Josh Gao1290fbf2016-11-22 14:32:34 -0800535 D("device tracker %p created", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800536
537 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao1290fbf2016-11-22 14:32:34 -0800538 tracker->socket.ready = device_tracker_ready;
539 tracker->socket.close = device_tracker_close;
Josh Gaob0c18022017-08-14 18:57:54 -0700540 tracker->update_needed = true;
541 tracker->long_output = long_output;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800542
Josh Gao1290fbf2016-11-22 14:32:34 -0800543 tracker->next = device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800544 device_tracker_list = tracker;
545
546 return &tracker->socket;
547}
548
Josh Gaofd713e52017-05-03 22:37:10 -0700549// Check if all of the USB transports are connected.
550bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gao1db71af2017-08-17 13:50:51 -0700551 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaofd713e52017-05-03 22:37:10 -0700552 for (const auto& t : transport_list) {
553 if (!fn(t)) {
554 return false;
555 }
556 }
557 for (const auto& t : pending_list) {
558 if (!fn(t)) {
559 return false;
560 }
561 }
562 return true;
563}
564
Elliott Hughese67f1f82015-04-30 17:32:03 -0700565// Call this function each time the transport list has changed.
566void update_transports() {
Josh Gaofd713e52017-05-03 22:37:10 -0700567 update_transport_status();
568
569 // Notify `adb track-devices` clients.
Elliott Hughese67f1f82015-04-30 17:32:03 -0700570 std::string transports = list_transports(false);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800571
Elliott Hughese67f1f82015-04-30 17:32:03 -0700572 device_tracker* tracker = device_tracker_list;
573 while (tracker != nullptr) {
574 device_tracker* next = tracker->next;
575 // This may destroy the tracker if the connection is closed.
576 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800577 tracker = next;
578 }
579}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700580
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800581#else
Elliott Hughese67f1f82015-04-30 17:32:03 -0700582
583void update_transports() {
584 // Nothing to do on the device side.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800585}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700586
Josh Gao1290fbf2016-11-22 14:32:34 -0800587#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800588
Josh Gao1290fbf2016-11-22 14:32:34 -0800589struct tmsg {
590 atransport* transport;
591 int action;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800592};
593
Josh Gao1290fbf2016-11-22 14:32:34 -0800594static int transport_read_action(int fd, struct tmsg* m) {
595 char* p = (char*)m;
596 int len = sizeof(*m);
597 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800598
Josh Gao1290fbf2016-11-22 14:32:34 -0800599 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800600 r = adb_read(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800601 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800602 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800603 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800604 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700605 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800606 return -1;
607 }
608 }
609 return 0;
610}
611
Josh Gao1290fbf2016-11-22 14:32:34 -0800612static int transport_write_action(int fd, struct tmsg* m) {
613 char* p = (char*)m;
614 int len = sizeof(*m);
615 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800616
Josh Gao1290fbf2016-11-22 14:32:34 -0800617 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800618 r = adb_write(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800619 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800620 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800621 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800622 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700623 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800624 return -1;
625 }
626 }
627 return 0;
628}
629
Josh Gao0bbf69c2018-02-16 13:24:58 -0800630static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800631 tmsg m;
Josh Gao1290fbf2016-11-22 14:32:34 -0800632 atransport* t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800633
Josh Gao1290fbf2016-11-22 14:32:34 -0800634 if (!(ev & FDE_READ)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800635 return;
636 }
637
Josh Gao1290fbf2016-11-22 14:32:34 -0800638 if (transport_read_action(_fd, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800639 fatal_errno("cannot read transport registration socket");
640 }
641
642 t = m.transport;
643
Dan Albert1792c232015-05-18 13:06:53 -0700644 if (m.action == 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700645 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800646
Josh Gao0cd3ae12016-09-21 12:37:10 -0700647 {
Josh Gao1db71af2017-08-17 13:50:51 -0700648 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700649 transport_list.remove(t);
650 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800651
Dan Albertc7915a32015-05-18 16:46:31 -0700652 delete t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800653
654 update_transports();
655 return;
656 }
657
Mike Lockwood0927bf92009-08-08 12:37:44 -0400658 /* don't create transport threads for inaccessible devices */
Yabin Cuib5e11412017-03-10 16:01:01 -0800659 if (t->GetConnectionState() != kCsNoPerm) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700660 // The connection gets a reference to the atransport. It will release it
661 // upon a read/write error.
662 t->ref_count++;
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700663 t->connection()->SetTransportName(t->serial_name());
664 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao0bbf69c2018-02-16 13:24:58 -0800665 if (!check_header(p.get(), t)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700666 D("%s: remote read: bad header", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800667 return false;
668 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800669
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700670 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "from remote", p.get());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800671 apacket* packet = p.release();
Mike Lockwood0927bf92009-08-08 12:37:44 -0400672
Josh Gao0bbf69c2018-02-16 13:24:58 -0800673 // TODO: Does this need to run on the main thread?
674 fdevent_run_on_main_thread([packet, t]() { handle_packet(packet, t); });
675 return true;
676 });
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700677 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700678 D("%s: connection terminated: %s", t->serial.c_str(), error.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800679 fdevent_run_on_main_thread([t]() {
680 handle_offline(t);
681 transport_unref(t);
682 });
683 });
Mike Lockwood0927bf92009-08-08 12:37:44 -0400684
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700685 t->connection()->Start();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800686#if ADB_HOST
687 send_connect(t);
688#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800689 }
690
Josh Gao0cd3ae12016-09-21 12:37:10 -0700691 {
Josh Gao1db71af2017-08-17 13:50:51 -0700692 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700693 auto it = std::find(pending_list.begin(), pending_list.end(), t);
694 if (it != pending_list.end()) {
695 pending_list.remove(t);
696 transport_list.push_front(t);
697 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700698 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800699
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800700 update_transports();
701}
702
Josh Gaodef91c02018-07-31 18:28:32 -0700703#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700704void init_reconnect_handler(void) {
705 reconnect_handler.Start();
706}
Josh Gaodef91c02018-07-31 18:28:32 -0700707#endif
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700708
Josh Gao1290fbf2016-11-22 14:32:34 -0800709void init_transport_registration(void) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800710 int s[2];
711
Josh Gao1290fbf2016-11-22 14:32:34 -0800712 if (adb_socketpair(s)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800713 fatal_errno("cannot open transport registration socketpair");
714 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700715 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800716
717 transport_registration_send = s[0];
718 transport_registration_recv = s[1];
719
Josh Gao71f775a2018-05-14 11:14:33 -0700720 transport_registration_fde =
Yi Kongaed415c2018-07-13 18:15:16 -0700721 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao71f775a2018-05-14 11:14:33 -0700722 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao01b7bc42017-05-09 13:43:35 -0700723}
724
725void kick_all_transports() {
Josh Gaodef91c02018-07-31 18:28:32 -0700726#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700727 reconnect_handler.Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700728#endif
Josh Gao01b7bc42017-05-09 13:43:35 -0700729 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gao1db71af2017-08-17 13:50:51 -0700730 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao01b7bc42017-05-09 13:43:35 -0700731 for (auto t : transport_list) {
732 t->Kick();
733 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800734}
735
736/* the fdevent select pump is single threaded */
Josh Gao1290fbf2016-11-22 14:32:34 -0800737static void register_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800738 tmsg m;
739 m.transport = transport;
740 m.action = 1;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700741 D("transport: %s registered", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800742 if (transport_write_action(transport_registration_send, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800743 fatal_errno("cannot write transport registration socket\n");
744 }
745}
746
Josh Gao1290fbf2016-11-22 14:32:34 -0800747static void remove_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800748 tmsg m;
749 m.transport = transport;
750 m.action = 0;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700751 D("transport: %s removed", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800752 if (transport_write_action(transport_registration_send, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800753 fatal_errno("cannot write transport registration socket\n");
754 }
755}
756
Yabin Cuif4b99282015-08-27 12:03:11 -0700757static void transport_unref(atransport* t) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700758 check_main_thread();
Yabin Cuif4b99282015-08-27 12:03:11 -0700759 CHECK(t != nullptr);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700760
Josh Gaoe48ecce2017-09-13 13:40:57 -0700761 std::lock_guard<std::recursive_mutex> lock(transport_lock);
762 CHECK_GT(t->ref_count, 0u);
763 t->ref_count--;
764 if (t->ref_count == 0) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700765 t->connection()->Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700766#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700767 if (t->IsTcpDevice() && !t->kicked()) {
Josh Gaodef91c02018-07-31 18:28:32 -0700768 D("transport: %s unref (attempting reconnection)", t->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700769 reconnect_handler.TrackTransport(t);
770 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700771 D("transport: %s unref (kicking and closing)", t->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700772 remove_transport(t);
773 }
Josh Gaodef91c02018-07-31 18:28:32 -0700774#else
775 D("transport: %s unref (kicking and closing)", t->serial.c_str());
776 remove_transport(t);
777#endif
778
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100779 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700780 D("transport: %s unref (count=%zu)", t->serial.c_str(), t->ref_count);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -0400781 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800782}
783
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700784static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao1290fbf2016-11-22 14:32:34 -0800785 bool sanitize_qual) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700786 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
787 return qual.empty();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700788
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700789 if (qual.empty()) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700790
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700791 const char* ptr = to_test.c_str();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700792 if (prefix) {
793 while (*prefix) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700794 if (*prefix++ != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700795 }
796 }
797
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700798 for (char ch : qual) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800799 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700800 if (ch != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700801 }
802
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700803 /* Everything matched so far. Return true if *ptr is a NUL. */
804 return !*ptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700805}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800806
Josh Gaob122b172017-08-16 16:57:01 -0700807atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
808 bool* is_ambiguous, std::string* error_out,
809 bool accept_any_state) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700810 atransport* result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800811
Josh Gaob122b172017-08-16 16:57:01 -0700812 if (transport_id != 0) {
813 *error_out =
814 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
815 } else if (serial) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700816 *error_out = android::base::StringPrintf("device '%s' not found", serial);
817 } else if (type == kTransportLocal) {
818 *error_out = "no emulators found";
819 } else if (type == kTransportAny) {
820 *error_out = "no devices/emulators found";
821 } else {
822 *error_out = "no devices found";
823 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800824
Josh Gao1db71af2017-08-17 13:50:51 -0700825 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes8d28e192015-10-07 14:55:10 -0700826 for (const auto& t : transport_list) {
Yabin Cuib5e11412017-03-10 16:01:01 -0800827 if (t->GetConnectionState() == kCsNoPerm) {
David Purselld2acbd12015-12-02 15:14:31 -0800828 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwood37d31112009-08-08 13:53:16 -0400829 continue;
830 }
Mike Lockwood0927bf92009-08-08 12:37:44 -0400831
Josh Gaob122b172017-08-16 16:57:01 -0700832 if (transport_id) {
833 if (t->id == transport_id) {
834 result = t;
835 break;
836 }
837 } else if (serial) {
David Pursell3f902aa2016-03-01 08:58:26 -0800838 if (t->MatchesTarget(serial)) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700839 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700840 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700841 if (is_ambiguous) *is_ambiguous = true;
842 result = nullptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700843 break;
844 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800845 result = t;
Scott Andersone109d262012-04-20 11:21:14 -0700846 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800847 } else {
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700848 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800849 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700850 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700851 if (is_ambiguous) *is_ambiguous = true;
852 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800853 break;
854 }
855 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700856 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800857 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700858 *error_out = "more than one emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700859 if (is_ambiguous) *is_ambiguous = true;
860 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800861 break;
862 }
863 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700864 } else if (type == kTransportAny) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800865 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700866 *error_out = "more than one device/emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700867 if (is_ambiguous) *is_ambiguous = true;
868 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800869 break;
870 }
871 result = t;
872 }
873 }
874 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700875 lock.unlock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800876
Josh Gao704494b2018-05-04 16:04:49 -0700877 if (result && !accept_any_state) {
878 // The caller requires an active transport.
879 // Make sure that we're actually connected.
880 ConnectionState state = result->GetConnectionState();
881 switch (state) {
882 case kCsConnecting:
883 *error_out = "device still connecting";
884 result = nullptr;
885 break;
Benoit Goby77e8e582013-01-15 12:36:47 -0800886
Josh Gao704494b2018-05-04 16:04:49 -0700887 case kCsAuthorizing:
888 *error_out = "device still authorizing";
889 result = nullptr;
890 break;
891
892 case kCsUnauthorized: {
893 *error_out = "device unauthorized.\n";
894 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
895 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
896 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
897 *error_out += "\n";
898 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
899 *error_out += "Otherwise check for a confirmation dialog on your device.";
900 result = nullptr;
901 break;
902 }
903
904 case kCsOffline:
905 *error_out = "device offline";
906 result = nullptr;
907 break;
908
909 default:
910 break;
911 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800912 }
913
914 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700915 *error_out = "success";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800916 }
917
918 return result;
919}
920
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700921bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
922 std::unique_lock<std::mutex> lock(mutex_);
923 ScopedAssumeLocked assume_locked(mutex_);
924 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
925 return connection_established_ready_;
926 }) && connection_established_;
927}
928
929void ConnectionWaitable::SetConnectionEstablished(bool success) {
930 {
931 std::lock_guard<std::mutex> lock(mutex_);
932 if (connection_established_ready_) return;
933 connection_established_ready_ = true;
934 connection_established_ = success;
935 D("connection established with %d", success);
936 }
937 cv_.notify_one();
938}
939
940atransport::~atransport() {
941 // If the connection callback had not been run before, run it now.
942 SetConnectionEstablished(false);
943}
944
Yabin Cuib5e11412017-03-10 16:01:01 -0800945int atransport::Write(apacket* p) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700946 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cuib5e11412017-03-10 16:01:01 -0800947}
948
Yabin Cui7f274902016-04-18 11:22:34 -0700949void atransport::Kick() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700950 if (!kicked_.exchange(true)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700951 D("kicking transport %p %s", this, this->serial.c_str());
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700952 this->connection()->Stop();
Yabin Cui7f274902016-04-18 11:22:34 -0700953 }
954}
955
Yabin Cuib5e11412017-03-10 16:01:01 -0800956ConnectionState atransport::GetConnectionState() const {
957 return connection_state_;
958}
959
960void atransport::SetConnectionState(ConnectionState state) {
961 check_main_thread();
962 connection_state_ = state;
963}
964
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700965void atransport::SetConnection(std::unique_ptr<Connection> connection) {
966 std::lock_guard<std::mutex> lock(mutex_);
967 connection_ = std::shared_ptr<Connection>(std::move(connection));
968}
969
Josh Gaoffbd3362018-02-28 14:44:23 -0800970std::string atransport::connection_state_name() const {
Yabin Cuib5e11412017-03-10 16:01:01 -0800971 ConnectionState state = GetConnectionState();
972 switch (state) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800973 case kCsOffline:
974 return "offline";
975 case kCsBootloader:
976 return "bootloader";
977 case kCsDevice:
978 return "device";
979 case kCsHost:
980 return "host";
981 case kCsRecovery:
982 return "recovery";
983 case kCsNoPerm:
984 return UsbNoPermissionsShortHelpText();
985 case kCsSideload:
986 return "sideload";
987 case kCsUnauthorized:
988 return "unauthorized";
Josh Gao704494b2018-05-04 16:04:49 -0700989 case kCsAuthorizing:
990 return "authorizing";
991 case kCsConnecting:
992 return "connecting";
Josh Gao1290fbf2016-11-22 14:32:34 -0800993 default:
994 return "unknown";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800995 }
996}
997
Tamas Berghammer3d2904c2015-07-13 19:12:28 +0100998void atransport::update_version(int version, size_t payload) {
999 protocol_version = std::min(version, A_VERSION);
1000 max_payload = std::min(payload, MAX_PAYLOAD);
1001}
1002
1003int atransport::get_protocol_version() const {
1004 return protocol_version;
1005}
1006
1007size_t atransport::get_max_payload() const {
1008 return max_payload;
1009}
1010
David Pursell4e2fd362015-09-22 10:43:08 -07001011namespace {
David Pursell0955c662015-08-31 10:42:13 -07001012
David Pursell4e2fd362015-09-22 10:43:08 -07001013constexpr char kFeatureStringDelimiter = ',';
1014
1015} // namespace
Dan Albert1792c232015-05-18 13:06:53 -07001016
1017const FeatureSet& supported_features() {
David Pursell4e2fd362015-09-22 10:43:08 -07001018 // Local static allocation to avoid global non-POD variables.
1019 static const FeatureSet* features = new FeatureSet{
Josh Gao1290fbf2016-11-22 14:32:34 -08001020 kFeatureShell2, kFeatureCmd, kFeatureStat2,
David Pursellbbe3d212015-09-25 08:37:13 -07001021 // Increment ADB_SERVER_VERSION whenever the feature list changes to
1022 // make sure that the adb client and server features stay in sync
1023 // (http://b/24370690).
David Pursell4e2fd362015-09-22 10:43:08 -07001024 };
1025
1026 return *features;
1027}
1028
1029std::string FeatureSetToString(const FeatureSet& features) {
1030 return android::base::Join(features, kFeatureStringDelimiter);
1031}
1032
1033FeatureSet StringToFeatureSet(const std::string& features_string) {
David Purselld2b588e2015-09-25 13:04:21 -07001034 if (features_string.empty()) {
1035 return FeatureSet();
1036 }
1037
Josh Gao1290fbf2016-11-22 14:32:34 -08001038 auto names = android::base::Split(features_string, {kFeatureStringDelimiter});
David Pursell4e2fd362015-09-22 10:43:08 -07001039 return FeatureSet(names.begin(), names.end());
Dan Albert1792c232015-05-18 13:06:53 -07001040}
1041
David Pursell70ef7b42015-09-30 13:35:42 -07001042bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001043 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell70ef7b42015-09-30 13:35:42 -07001044}
1045
Dan Albert1792c232015-05-18 13:06:53 -07001046bool atransport::has_feature(const std::string& feature) const {
1047 return features_.count(feature) > 0;
1048}
1049
David Pursell4e2fd362015-09-22 10:43:08 -07001050void atransport::SetFeatures(const std::string& features_string) {
1051 features_ = StringToFeatureSet(features_string);
Dan Albert1792c232015-05-18 13:06:53 -07001052}
1053
Yabin Cuib3298242015-08-28 15:09:44 -07001054void atransport::AddDisconnect(adisconnect* disconnect) {
1055 disconnects_.push_back(disconnect);
1056}
1057
1058void atransport::RemoveDisconnect(adisconnect* disconnect) {
1059 disconnects_.remove(disconnect);
1060}
1061
1062void atransport::RunDisconnects() {
Elliott Hughes65fe2512015-10-07 15:59:35 -07001063 for (const auto& disconnect : disconnects_) {
Yabin Cuib3298242015-08-28 15:09:44 -07001064 disconnect->func(disconnect->opaque, this);
1065 }
1066 disconnects_.clear();
1067}
1068
David Pursell3f902aa2016-03-01 08:58:26 -08001069bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001070 if (!serial.empty()) {
David Pursell3f902aa2016-03-01 08:58:26 -08001071 if (target == serial) {
1072 return true;
1073 } else if (type == kTransportLocal) {
1074 // Local transports can match [tcp:|udp:]<hostname>[:port].
1075 const char* local_target_ptr = target.c_str();
1076
1077 // For fastboot compatibility, ignore protocol prefixes.
1078 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao1290fbf2016-11-22 14:32:34 -08001079 android::base::StartsWith(target, "udp:")) {
David Pursell3f902aa2016-03-01 08:58:26 -08001080 local_target_ptr += 4;
1081 }
1082
1083 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1084 std::string serial_host, error;
1085 int serial_port = -1;
Josh Gao1290fbf2016-11-22 14:32:34 -08001086 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursell3f902aa2016-03-01 08:58:26 -08001087 // |target| may omit the port to default to ours.
1088 std::string target_host;
1089 int target_port = serial_port;
1090 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1091 nullptr, &error) &&
Josh Gao1290fbf2016-11-22 14:32:34 -08001092 serial_host == target_host && serial_port == target_port) {
David Pursell3f902aa2016-03-01 08:58:26 -08001093 return true;
1094 }
1095 }
1096 }
1097 }
1098
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001099 return (target == devpath) || qual_match(target, "product:", product, false) ||
1100 qual_match(target, "model:", model, true) ||
1101 qual_match(target, "device:", device, false);
David Pursell3f902aa2016-03-01 08:58:26 -08001102}
1103
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001104void atransport::SetConnectionEstablished(bool success) {
1105 connection_waitable_->SetConnectionEstablished(success);
1106}
1107
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001108bool atransport::Reconnect() {
1109 return reconnect_(this);
1110}
1111
Elliott Hughese67f1f82015-04-30 17:32:03 -07001112#if ADB_HOST
1113
Josh Gaob122b172017-08-16 16:57:01 -07001114// We use newline as our delimiter, make sure to never output it.
1115static std::string sanitize(std::string str, bool alphanumeric) {
1116 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1117 : [](const char c) { return c == '\n'; };
1118 std::replace_if(str.begin(), str.end(), pred, '_');
1119 return str;
1120}
1121
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001122static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob122b172017-08-16 16:57:01 -07001123 bool alphanumeric) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001124 if (value.empty()) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001125 return;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001126 }
1127
Elliott Hughese67f1f82015-04-30 17:32:03 -07001128 *result += ' ';
1129 *result += key;
Josh Gaob122b172017-08-16 16:57:01 -07001130 *result += sanitize(value, alphanumeric);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001131}
1132
Josh Gao1290fbf2016-11-22 14:32:34 -08001133static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001134 std::string serial = t->serial;
1135 if (serial.empty()) {
Dan Albertd99d9022015-05-06 16:48:52 -07001136 serial = "(no serial number)";
Elliott Hughese67f1f82015-04-30 17:32:03 -07001137 }
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001138
1139 if (!long_listing) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001140 *result += serial;
1141 *result += '\t';
1142 *result += t->connection_state_name();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001143 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001144 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1145 t->connection_state_name().c_str());
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001146
Elliott Hughese67f1f82015-04-30 17:32:03 -07001147 append_transport_info(result, "", t->devpath, false);
1148 append_transport_info(result, "product:", t->product, false);
1149 append_transport_info(result, "model:", t->model, true);
1150 append_transport_info(result, "device:", t->device, false);
Josh Gaob122b172017-08-16 16:57:01 -07001151
1152 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1153 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1154 *result += " transport_id:";
1155 *result += std::to_string(t->id);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001156 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001157 *result += '\n';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001158}
1159
Elliott Hughese67f1f82015-04-30 17:32:03 -07001160std::string list_transports(bool long_listing) {
Josh Gao1db71af2017-08-17 13:50:51 -07001161 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov04398a92017-12-17 10:56:07 +00001162
1163 auto sorted_transport_list = transport_list;
1164 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1165 if (x->type != y->type) {
1166 return x->type < y->type;
1167 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001168 return x->serial < y->serial;
Artem Iglikov04398a92017-12-17 10:56:07 +00001169 });
1170
1171 std::string result;
1172 for (const auto& t : sorted_transport_list) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001173 append_transport(t, &result, long_listing);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001174 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001175 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001176}
1177
Josh Gao22d2b3e2016-10-27 14:01:08 -07001178void close_usb_devices(std::function<bool(const atransport*)> predicate) {
Josh Gao1db71af2017-08-17 13:50:51 -07001179 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao22d2b3e2016-10-27 14:01:08 -07001180 for (auto& t : transport_list) {
1181 if (predicate(t)) {
1182 t->Kick();
1183 }
1184 }
1185}
1186
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001187/* hack for osx */
Dan Albertc7915a32015-05-18 16:46:31 -07001188void close_usb_devices() {
Josh Gao22d2b3e2016-10-27 14:01:08 -07001189 close_usb_devices([](const atransport*) { return true; });
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001190}
Josh Gao1290fbf2016-11-22 14:32:34 -08001191#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001192
Josh Gao3b4de3c2018-08-02 13:58:24 -07001193int register_socket_transport(unique_fd s, std::string serial, int port, int local,
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001194 atransport::ReconnectCallback reconnect) {
1195 atransport* t = new atransport(std::move(reconnect), kCsOffline);
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +01001196
Josh Gao3b4de3c2018-08-02 13:58:24 -07001197 D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
Josh Gao56300c92018-07-25 17:21:49 -07001198 if (init_socket_transport(t, std::move(s), port, local) < 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001199 delete t;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001200 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001201 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001202
Josh Gao1db71af2017-08-17 13:50:51 -07001203 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes65fe2512015-10-07 15:59:35 -07001204 for (const auto& transport : pending_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001205 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001206 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001207 << " is already in pending_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001208 delete t;
Luis Hector Chavez5d395852018-04-17 14:09:21 -07001209 return -EALREADY;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001210 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001211 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001212
Elliott Hughes65fe2512015-10-07 15:59:35 -07001213 for (const auto& transport : transport_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001214 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001215 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001216 << " is already in transport_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001217 delete t;
Luis Hector Chavez5d395852018-04-17 14:09:21 -07001218 return -EALREADY;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001219 }
1220 }
1221
Josh Gao3b4de3c2018-08-02 13:58:24 -07001222 t->serial = std::move(serial);
Dan Albertc7915a32015-05-18 16:46:31 -07001223 pending_list.push_front(t);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001224
1225 lock.unlock();
Benoit Goby1c45ee92013-03-29 18:22:36 -07001226
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001227 auto waitable = t->connection_waitable();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001228 register_transport(t);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001229
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001230 if (local == 1) {
1231 // Do not wait for emulator transports.
1232 return 0;
1233 }
1234
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001235 return waitable->WaitForConnection(std::chrono::seconds(10)) ? 0 : -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001236}
1237
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001238#if ADB_HOST
Josh Gao1290fbf2016-11-22 14:32:34 -08001239atransport* find_transport(const char* serial) {
Dan Albertc7915a32015-05-18 16:46:31 -07001240 atransport* result = nullptr;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001241
Josh Gao1db71af2017-08-17 13:50:51 -07001242 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001243 for (auto& t : transport_list) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001244 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001245 result = t;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001246 break;
1247 }
Dan Albertc7915a32015-05-18 16:46:31 -07001248 }
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001249
Dan Albertc7915a32015-05-18 16:46:31 -07001250 return result;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001251}
1252
Yabin Cuif4b99282015-08-27 12:03:11 -07001253void kick_all_tcp_devices() {
Josh Gao1db71af2017-08-17 13:50:51 -07001254 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001255 for (auto& t : transport_list) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001256 if (t->IsTcpDevice()) {
Yabin Cuid6ab3c22015-08-31 11:50:24 -07001257 // Kicking breaks the read_transport thread of this transport out of any read, then
1258 // the read_transport thread will notify the main thread to make this transport
1259 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cuif4b99282015-08-27 12:03:11 -07001260 // Finally, this transport will be closed and freed in the main thread.
Yabin Cui7f274902016-04-18 11:22:34 -07001261 t->Kick();
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001262 }
Dan Albertc7915a32015-05-18 16:46:31 -07001263 }
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001264}
1265
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001266#endif
1267
Josh Gao1290fbf2016-11-22 14:32:34 -08001268void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1269 unsigned writeable) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001270 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertc7915a32015-05-18 16:46:31 -07001271
Josh Gao1290fbf2016-11-22 14:32:34 -08001272 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cuib5e11412017-03-10 16:01:01 -08001273 init_usb_transport(t, usb);
Josh Gao1290fbf2016-11-22 14:32:34 -08001274 if (serial) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001275 t->serial = serial;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001276 }
Dan Albertc7915a32015-05-18 16:46:31 -07001277
1278 if (devpath) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001279 t->devpath = devpath;
Scott Andersone109d262012-04-20 11:21:14 -07001280 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001281
Josh Gao0cd3ae12016-09-21 12:37:10 -07001282 {
Josh Gao1db71af2017-08-17 13:50:51 -07001283 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001284 pending_list.push_front(t);
1285 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001286
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001287 register_transport(t);
1288}
1289
Dan Albertdcd78a12015-05-18 16:43:57 -07001290// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao1290fbf2016-11-22 14:32:34 -08001291void unregister_usb_transport(usb_handle* usb) {
Josh Gao1db71af2017-08-17 13:50:51 -07001292 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaob800d882018-01-28 20:32:46 -08001293 transport_list.remove_if([usb](atransport* t) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -07001294 auto connection = t->connection();
1295 if (auto usb_connection = dynamic_cast<UsbConnection*>(connection.get())) {
1296 return usb_connection->handle_ == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gaob800d882018-01-28 20:32:46 -08001297 }
1298 return false;
1299 });
Mike Lockwood0927bf92009-08-08 12:37:44 -04001300}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001301
Josh Gao36dadca2017-05-16 15:02:45 -07001302bool check_header(apacket* p, atransport* t) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001303 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cuib5e11412017-03-10 16:01:01 -08001304 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1305 << ", magic = " << p->msg.magic;
Josh Gao36dadca2017-05-16 15:02:45 -07001306 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001307 }
1308
Josh Gao1290fbf2016-11-22 14:32:34 -08001309 if (p->msg.data_length > t->get_max_payload()) {
1310 VLOG(RWX) << "check_header(): " << p->msg.data_length
1311 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao36dadca2017-05-16 15:02:45 -07001312 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001313 }
1314
Josh Gao36dadca2017-05-16 15:02:45 -07001315 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001316}
1317
Josh Gao3bd28792016-10-05 19:02:29 -07001318#if ADB_HOST
Josh Gao2e671202016-08-18 22:00:12 -07001319std::shared_ptr<RSA> atransport::NextKey() {
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001320 if (keys_.empty()) keys_ = adb_auth_get_private_keys();
1321
Josh Gao2e671202016-08-18 22:00:12 -07001322 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001323 keys_.pop_front();
1324 return result;
1325}
Josh Gao3bd28792016-10-05 19:02:29 -07001326#endif