blob: 95df49006d9d03aa4aff500068493210b8f9610f [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
Josh Gao902dace2018-08-10 14:44:54 -0700100 // Wake up the ReconnectHandler thread to have it check for kicked transports.
101 void CheckForKicked();
102
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700103 private:
104 // The main thread loop.
105 void Run();
106
107 // Tracks a reconnection attempt.
108 struct ReconnectAttempt {
109 atransport* transport;
Josh Gao95af6412018-07-30 18:51:55 -0700110 std::chrono::steady_clock::time_point reconnect_time;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700111 size_t attempts_left;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700112
113 bool operator<(const ReconnectAttempt& rhs) const {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700114 if (reconnect_time == rhs.reconnect_time) {
115 return reinterpret_cast<uintptr_t>(transport) <
116 reinterpret_cast<uintptr_t>(rhs.transport);
117 }
118 return reconnect_time < rhs.reconnect_time;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700119 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700120 };
121
122 // Only retry for up to one minute.
Josh Gaoe445a6d2018-07-31 14:12:59 -0700123 static constexpr const std::chrono::seconds kDefaultTimeout = 10s;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700124 static constexpr const size_t kMaxAttempts = 6;
125
126 // Protects all members.
127 std::mutex reconnect_mutex_;
128 bool running_ GUARDED_BY(reconnect_mutex_) = true;
129 std::thread handler_thread_;
130 std::condition_variable reconnect_cv_;
Josh Gao8a40c8a2018-08-10 14:28:24 -0700131 std::set<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700132
133 DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
134};
135
136void ReconnectHandler::Start() {
137 check_main_thread();
138 handler_thread_ = std::thread(&ReconnectHandler::Run, this);
139}
140
141void ReconnectHandler::Stop() {
142 check_main_thread();
143 {
144 std::lock_guard<std::mutex> lock(reconnect_mutex_);
145 running_ = false;
146 }
147 reconnect_cv_.notify_one();
148 handler_thread_.join();
149
150 // Drain the queue to free all resources.
151 std::lock_guard<std::mutex> lock(reconnect_mutex_);
152 while (!reconnect_queue_.empty()) {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700153 ReconnectAttempt attempt = *reconnect_queue_.begin();
154 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700155 remove_transport(attempt.transport);
156 }
157}
158
159void ReconnectHandler::TrackTransport(atransport* transport) {
160 check_main_thread();
161 {
162 std::lock_guard<std::mutex> lock(reconnect_mutex_);
163 if (!running_) return;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700164 // Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
165 auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
166 reconnect_queue_.emplace(
167 ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700168 }
169 reconnect_cv_.notify_one();
170}
171
Josh Gao902dace2018-08-10 14:44:54 -0700172void ReconnectHandler::CheckForKicked() {
173 reconnect_cv_.notify_one();
174}
175
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700176void ReconnectHandler::Run() {
177 while (true) {
178 ReconnectAttempt attempt;
179 {
180 std::unique_lock<std::mutex> lock(reconnect_mutex_);
181 ScopedAssumeLocked assume_lock(reconnect_mutex_);
182
Josh Gao95af6412018-07-30 18:51:55 -0700183 if (!reconnect_queue_.empty()) {
184 // FIXME: libstdc++ (used on Windows) implements condition_variable with
185 // system_clock as its clock, so we're probably hosed if the clock changes,
186 // even if we use steady_clock throughout. This problem goes away once we
187 // switch to libc++.
Josh Gao8a40c8a2018-08-10 14:28:24 -0700188 reconnect_cv_.wait_until(lock, reconnect_queue_.begin()->reconnect_time);
Josh Gao95af6412018-07-30 18:51:55 -0700189 } else {
190 reconnect_cv_.wait(lock);
191 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700192
193 if (!running_) return;
Josh Gao902dace2018-08-10 14:44:54 -0700194
195 // Scan the whole list for kicked transports, so that we immediately handle an explicit
196 // disconnect request.
197 bool kicked = false;
198 for (auto it = reconnect_queue_.begin(); it != reconnect_queue_.end();) {
199 if (it->transport->kicked()) {
200 D("transport %s was kicked. giving up on it.", it->transport->serial.c_str());
201 remove_transport(it->transport);
202 it = reconnect_queue_.erase(it);
203 } else {
204 ++it;
205 }
206 kicked = true;
207 }
208
Josh Gao95af6412018-07-30 18:51:55 -0700209 if (reconnect_queue_.empty()) continue;
210
Josh Gao902dace2018-08-10 14:44:54 -0700211 // Go back to sleep if we either woke up spuriously, or we were woken up to remove
212 // a kicked transport, and the first transport isn't ready for reconnection yet.
Josh Gao95af6412018-07-30 18:51:55 -0700213 auto now = std::chrono::steady_clock::now();
Josh Gao8a40c8a2018-08-10 14:28:24 -0700214 if (reconnect_queue_.begin()->reconnect_time > now) {
Josh Gao95af6412018-07-30 18:51:55 -0700215 continue;
216 }
217
Josh Gao8a40c8a2018-08-10 14:28:24 -0700218 attempt = *reconnect_queue_.begin();
219 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700220 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700221 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700222
Josh Gaofc2e56f2018-08-30 11:37:00 -0700223 switch (attempt.transport->Reconnect()) {
224 case ReconnectResult::Retry: {
225 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
226 if (attempt.attempts_left == 0) {
227 D("transport %s exceeded the number of retry attempts. giving up on it.",
228 attempt.transport->serial.c_str());
229 remove_transport(attempt.transport);
230 continue;
231 }
232
233 std::lock_guard<std::mutex> lock(reconnect_mutex_);
234 reconnect_queue_.emplace(ReconnectAttempt{
235 attempt.transport,
236 std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
237 attempt.attempts_left - 1});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700238 continue;
239 }
240
Josh Gaofc2e56f2018-08-30 11:37:00 -0700241 case ReconnectResult::Success:
242 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
243 register_transport(attempt.transport);
244 continue;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700245
Josh Gaofc2e56f2018-08-30 11:37:00 -0700246 case ReconnectResult::Abort:
247 D("cancelling reconnection attempt to %s.", attempt.transport->serial.c_str());
248 remove_transport(attempt.transport);
249 continue;
250 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700251 }
252}
253
254static auto& reconnect_handler = *new ReconnectHandler();
255
Josh Gaodef91c02018-07-31 18:28:32 -0700256#endif
257
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700258} // namespace
259
Josh Gaob122b172017-08-16 16:57:01 -0700260TransportId NextTransportId() {
261 static std::atomic<TransportId> next(1);
262 return next++;
263}
264
Josh Gao0bbf69c2018-02-16 13:24:58 -0800265BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
266 : underlying_(std::move(connection)) {}
267
268BlockingConnectionAdapter::~BlockingConnectionAdapter() {
269 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
270 Stop();
271}
272
273void BlockingConnectionAdapter::Start() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700274 std::lock_guard<std::mutex> lock(mutex_);
275 if (started_) {
276 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
277 << "): started multiple times";
278 }
279
Josh Gao0bbf69c2018-02-16 13:24:58 -0800280 read_thread_ = std::thread([this]() {
281 LOG(INFO) << this->transport_name_ << ": read thread spawning";
282 while (true) {
Josh Gao31b5be62018-03-07 16:51:08 -0800283 auto packet = std::make_unique<apacket>();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800284 if (!underlying_->Read(packet.get())) {
285 PLOG(INFO) << this->transport_name_ << ": read failed";
286 break;
287 }
288 read_callback_(this, std::move(packet));
289 }
290 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
291 });
292
293 write_thread_ = std::thread([this]() {
294 LOG(INFO) << this->transport_name_ << ": write thread spawning";
295 while (true) {
296 std::unique_lock<std::mutex> lock(mutex_);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700297 ScopedAssumeLocked assume_locked(mutex_);
Josh Gaoc251ec52018-04-03 12:55:18 -0700298 cv_.wait(lock, [this]() REQUIRES(mutex_) {
299 return this->stopped_ || !this->write_queue_.empty();
300 });
301
Josh Gao0bbf69c2018-02-16 13:24:58 -0800302 if (this->stopped_) {
303 return;
304 }
305
306 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
307 this->write_queue_.pop_front();
308 lock.unlock();
309
310 if (!this->underlying_->Write(packet.get())) {
311 break;
312 }
313 }
314 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
315 });
Josh Gaoc251ec52018-04-03 12:55:18 -0700316
317 started_ = true;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800318}
319
320void BlockingConnectionAdapter::Stop() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700321 {
322 std::lock_guard<std::mutex> lock(mutex_);
323 if (!started_) {
324 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
325 return;
326 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800327
Josh Gaoc251ec52018-04-03 12:55:18 -0700328 if (stopped_) {
329 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
330 << "): already stopped";
331 return;
332 }
333
334 stopped_ = true;
335 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800336
337 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
338
339 this->underlying_->Close();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800340 this->cv_.notify_one();
Josh Gaoc251ec52018-04-03 12:55:18 -0700341
342 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
343 std::thread read_thread;
344 std::thread write_thread;
345
346 {
347 std::lock_guard<std::mutex> lock(mutex_);
348 read_thread = std::move(read_thread_);
349 write_thread = std::move(write_thread_);
350 }
351
352 read_thread.join();
353 write_thread.join();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800354
355 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
356 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
357}
358
359bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
360 {
Josh Gaoc251ec52018-04-03 12:55:18 -0700361 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800362 write_queue_.emplace_back(std::move(packet));
363 }
364
365 cv_.notify_one();
366 return true;
367}
368
Josh Gaob800d882018-01-28 20:32:46 -0800369bool FdConnection::Read(apacket* packet) {
370 if (!ReadFdExactly(fd_.get(), &packet->msg, sizeof(amessage))) {
371 D("remote local: read terminated (message)");
372 return false;
373 }
374
Josh Gaof571fcb2018-02-05 18:49:10 -0800375 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gao5caaebd2018-02-02 14:38:04 -0800376 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
377 return false;
378 }
379
Josh Gaof571fcb2018-02-05 18:49:10 -0800380 packet->payload.resize(packet->msg.data_length);
381
382 if (!ReadFdExactly(fd_.get(), &packet->payload[0], packet->payload.size())) {
Josh Gaob800d882018-01-28 20:32:46 -0800383 D("remote local: terminated (data)");
384 return false;
385 }
386
387 return true;
388}
389
390bool FdConnection::Write(apacket* packet) {
Josh Gaof571fcb2018-02-05 18:49:10 -0800391 if (!WriteFdExactly(fd_.get(), &packet->msg, sizeof(packet->msg))) {
Josh Gaob800d882018-01-28 20:32:46 -0800392 D("remote local: write terminated");
393 return false;
394 }
395
Josh Gaof571fcb2018-02-05 18:49:10 -0800396 if (packet->msg.data_length) {
397 if (!WriteFdExactly(fd_.get(), &packet->payload[0], packet->msg.data_length)) {
398 D("remote local: write terminated");
399 return false;
400 }
401 }
402
Josh Gaob800d882018-01-28 20:32:46 -0800403 return true;
404}
405
406void FdConnection::Close() {
407 adb_shutdown(fd_.get());
408 fd_.reset();
409}
410
Yabin Cuiaed3c612015-09-22 15:52:57 -0700411static std::string dump_packet(const char* name, const char* func, apacket* p) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800412 unsigned command = p->msg.command;
413 int len = p->msg.data_length;
414 char cmd[9];
415 char arg0[12], arg1[12];
416 int n;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100417
418 for (n = 0; n < 4; n++) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800419 int b = (command >> (n * 8)) & 255;
420 if (b < 32 || b >= 127) break;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100421 cmd[n] = (char)b;
422 }
423 if (n == 4) {
424 cmd[4] = 0;
425 } else {
426 /* There is some non-ASCII name in the command, so dump
427 * the hexadecimal value instead */
428 snprintf(cmd, sizeof cmd, "%08x", command);
429 }
430
431 if (p->msg.arg0 < 256U)
432 snprintf(arg0, sizeof arg0, "%d", p->msg.arg0);
433 else
434 snprintf(arg0, sizeof arg0, "0x%x", p->msg.arg0);
435
436 if (p->msg.arg1 < 256U)
437 snprintf(arg1, sizeof arg1, "%d", p->msg.arg1);
438 else
439 snprintf(arg1, sizeof arg1, "0x%x", p->msg.arg1);
440
Josh Gao1290fbf2016-11-22 14:32:34 -0800441 std::string result = android::base::StringPrintf("%s: %s: [%s] arg0=%s arg1=%s (len=%d) ", name,
442 func, cmd, arg0, arg1, len);
Josh Gaof571fcb2018-02-05 18:49:10 -0800443 result += dump_hex(p->payload.data(), p->payload.size());
Yabin Cuiaed3c612015-09-22 15:52:57 -0700444 return result;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100445}
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100446
Josh Gao06d61d42016-10-06 13:31:44 -0700447void send_packet(apacket* p, atransport* t) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800448 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayde471942017-12-07 11:40:00 -0800449 // compute a checksum for connection/auth packets for compatibility reasons
450 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
451 p->msg.data_check = 0;
452 } else {
453 p->msg.data_check = calculate_apacket_checksum(p);
454 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800455
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700456 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800457
Yi Kongaed415c2018-07-13 18:15:16 -0700458 if (t == nullptr) {
Josh Gao06d61d42016-10-06 13:31:44 -0700459 fatal("Transport is null");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800460 }
461
Josh Gao0bbf69c2018-02-16 13:24:58 -0800462 if (t->Write(p) != 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700463 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800464 t->Kick();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800465 }
466}
467
Yabin Cuif4b99282015-08-27 12:03:11 -0700468void kick_transport(atransport* t) {
Josh Gao1db71af2017-08-17 13:50:51 -0700469 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui1f4ec192016-04-05 13:50:44 -0700470 // As kick_transport() can be called from threads without guarantee that t is valid,
471 // check if the transport is in transport_list first.
Josh Gaob122b172017-08-16 16:57:01 -0700472 //
473 // TODO(jmgao): WTF? Is this actually true?
Yabin Cui1f4ec192016-04-05 13:50:44 -0700474 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Yabin Cui7f274902016-04-18 11:22:34 -0700475 t->Kick();
Yabin Cui1f4ec192016-04-05 13:50:44 -0700476 }
Josh Gao902dace2018-08-10 14:44:54 -0700477
478#if ADB_HOST
479 reconnect_handler.CheckForKicked();
480#endif
Yabin Cuif4b99282015-08-27 12:03:11 -0700481}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800482
483static int transport_registration_send = -1;
484static int transport_registration_recv = -1;
Josh Gao71f775a2018-05-14 11:14:33 -0700485static fdevent* transport_registration_fde;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800486
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800487#if ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800488
489/* this adds support required by the 'track-devices' service.
490 * this is used to send the content of "list_transport" to any
491 * number of client connections that want it through a single
492 * live TCP connection
493 */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800494struct device_tracker {
Josh Gao1290fbf2016-11-22 14:32:34 -0800495 asocket socket;
Josh Gaoe0361d12018-02-12 17:24:00 -0800496 bool update_needed = false;
497 bool long_output = false;
498 device_tracker* next = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800499};
500
501/* linked list of all device trackers */
Josh Gao1290fbf2016-11-22 14:32:34 -0800502static device_tracker* device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800503
Josh Gao1290fbf2016-11-22 14:32:34 -0800504static void device_tracker_remove(device_tracker* tracker) {
505 device_tracker** pnode = &device_tracker_list;
506 device_tracker* node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800507
Josh Gao1db71af2017-08-17 13:50:51 -0700508 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800509 while (node) {
510 if (node == tracker) {
511 *pnode = node->next;
512 break;
513 }
514 pnode = &node->next;
Josh Gao1290fbf2016-11-22 14:32:34 -0800515 node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800516 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800517}
518
Josh Gao1290fbf2016-11-22 14:32:34 -0800519static void device_tracker_close(asocket* socket) {
520 device_tracker* tracker = (device_tracker*)socket;
521 asocket* peer = socket->peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800522
Josh Gao1290fbf2016-11-22 14:32:34 -0800523 D("device tracker %p removed", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800524 if (peer) {
Yi Kongaed415c2018-07-13 18:15:16 -0700525 peer->peer = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800526 peer->close(peer);
527 }
528 device_tracker_remove(tracker);
Josh Gaoe0361d12018-02-12 17:24:00 -0800529 delete tracker;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800530}
531
Josh Gao1ce99572018-03-07 16:52:28 -0800532static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800533 /* you can't read from a device tracker, close immediately */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800534 device_tracker_close(socket);
535 return -1;
536}
537
Elliott Hughese67f1f82015-04-30 17:32:03 -0700538static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700539 asocket* peer = tracker->socket.peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800540
Josh Gao1ce99572018-03-07 16:52:28 -0800541 apacket::payload_type data;
Josh Gao27cb7dc2018-02-01 13:17:50 -0800542 data.resize(4 + string.size());
543 char buf[5];
544 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
545 memcpy(&data[0], buf, 4);
546 memcpy(&data[4], string.data(), string.size());
547 return peer->enqueue(peer, std::move(data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800548}
549
Elliott Hughese67f1f82015-04-30 17:32:03 -0700550static void device_tracker_ready(asocket* socket) {
551 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800552
Elliott Hughese67f1f82015-04-30 17:32:03 -0700553 // We want to send the device list when the tracker connects
554 // for the first time, even if no update occurred.
Josh Gaob0c18022017-08-14 18:57:54 -0700555 if (tracker->update_needed) {
556 tracker->update_needed = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800557
Josh Gaob0c18022017-08-14 18:57:54 -0700558 std::string transports = list_transports(tracker->long_output);
Elliott Hughese67f1f82015-04-30 17:32:03 -0700559 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800560 }
561}
562
Josh Gaob0c18022017-08-14 18:57:54 -0700563asocket* create_device_tracker(bool long_output) {
Josh Gaoe0361d12018-02-12 17:24:00 -0800564 device_tracker* tracker = new device_tracker();
Elliott Hughesdc3b4592015-04-21 19:39:52 -0700565 if (tracker == nullptr) fatal("cannot allocate device tracker");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800566
Josh Gao1290fbf2016-11-22 14:32:34 -0800567 D("device tracker %p created", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800568
569 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao1290fbf2016-11-22 14:32:34 -0800570 tracker->socket.ready = device_tracker_ready;
571 tracker->socket.close = device_tracker_close;
Josh Gaob0c18022017-08-14 18:57:54 -0700572 tracker->update_needed = true;
573 tracker->long_output = long_output;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800574
Josh Gao1290fbf2016-11-22 14:32:34 -0800575 tracker->next = device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800576 device_tracker_list = tracker;
577
578 return &tracker->socket;
579}
580
Josh Gaofd713e52017-05-03 22:37:10 -0700581// Check if all of the USB transports are connected.
582bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gao1db71af2017-08-17 13:50:51 -0700583 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaofd713e52017-05-03 22:37:10 -0700584 for (const auto& t : transport_list) {
585 if (!fn(t)) {
586 return false;
587 }
588 }
589 for (const auto& t : pending_list) {
590 if (!fn(t)) {
591 return false;
592 }
593 }
594 return true;
595}
596
Elliott Hughese67f1f82015-04-30 17:32:03 -0700597// Call this function each time the transport list has changed.
598void update_transports() {
Josh Gaofd713e52017-05-03 22:37:10 -0700599 update_transport_status();
600
601 // Notify `adb track-devices` clients.
Elliott Hughese67f1f82015-04-30 17:32:03 -0700602 std::string transports = list_transports(false);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800603
Elliott Hughese67f1f82015-04-30 17:32:03 -0700604 device_tracker* tracker = device_tracker_list;
605 while (tracker != nullptr) {
606 device_tracker* next = tracker->next;
607 // This may destroy the tracker if the connection is closed.
608 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800609 tracker = next;
610 }
611}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700612
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800613#else
Elliott Hughese67f1f82015-04-30 17:32:03 -0700614
615void update_transports() {
616 // Nothing to do on the device side.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800617}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700618
Josh Gao1290fbf2016-11-22 14:32:34 -0800619#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800620
Josh Gao1290fbf2016-11-22 14:32:34 -0800621struct tmsg {
622 atransport* transport;
623 int action;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800624};
625
Josh Gao1290fbf2016-11-22 14:32:34 -0800626static int transport_read_action(int fd, struct tmsg* m) {
627 char* p = (char*)m;
628 int len = sizeof(*m);
629 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800630
Josh Gao1290fbf2016-11-22 14:32:34 -0800631 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800632 r = adb_read(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800633 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800634 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800635 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800636 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700637 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800638 return -1;
639 }
640 }
641 return 0;
642}
643
Josh Gao1290fbf2016-11-22 14:32:34 -0800644static int transport_write_action(int fd, struct tmsg* m) {
645 char* p = (char*)m;
646 int len = sizeof(*m);
647 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800648
Josh Gao1290fbf2016-11-22 14:32:34 -0800649 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800650 r = adb_write(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800651 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800652 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800653 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800654 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700655 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800656 return -1;
657 }
658 }
659 return 0;
660}
661
Josh Gao0bbf69c2018-02-16 13:24:58 -0800662static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800663 tmsg m;
Josh Gao1290fbf2016-11-22 14:32:34 -0800664 atransport* t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800665
Josh Gao1290fbf2016-11-22 14:32:34 -0800666 if (!(ev & FDE_READ)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800667 return;
668 }
669
Josh Gao1290fbf2016-11-22 14:32:34 -0800670 if (transport_read_action(_fd, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800671 fatal_errno("cannot read transport registration socket");
672 }
673
674 t = m.transport;
675
Dan Albert1792c232015-05-18 13:06:53 -0700676 if (m.action == 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700677 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800678
Josh Gao0cd3ae12016-09-21 12:37:10 -0700679 {
Josh Gao1db71af2017-08-17 13:50:51 -0700680 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700681 transport_list.remove(t);
682 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800683
Dan Albertc7915a32015-05-18 16:46:31 -0700684 delete t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800685
686 update_transports();
687 return;
688 }
689
Mike Lockwood0927bf92009-08-08 12:37:44 -0400690 /* don't create transport threads for inaccessible devices */
Yabin Cuib5e11412017-03-10 16:01:01 -0800691 if (t->GetConnectionState() != kCsNoPerm) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700692 // The connection gets a reference to the atransport. It will release it
693 // upon a read/write error.
694 t->ref_count++;
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700695 t->connection()->SetTransportName(t->serial_name());
696 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao0bbf69c2018-02-16 13:24:58 -0800697 if (!check_header(p.get(), t)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700698 D("%s: remote read: bad header", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800699 return false;
700 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800701
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700702 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "from remote", p.get());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800703 apacket* packet = p.release();
Mike Lockwood0927bf92009-08-08 12:37:44 -0400704
Josh Gao0bbf69c2018-02-16 13:24:58 -0800705 // TODO: Does this need to run on the main thread?
706 fdevent_run_on_main_thread([packet, t]() { handle_packet(packet, t); });
707 return true;
708 });
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700709 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700710 D("%s: connection terminated: %s", t->serial.c_str(), error.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800711 fdevent_run_on_main_thread([t]() {
712 handle_offline(t);
713 transport_unref(t);
714 });
715 });
Mike Lockwood0927bf92009-08-08 12:37:44 -0400716
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700717 t->connection()->Start();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800718#if ADB_HOST
719 send_connect(t);
720#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800721 }
722
Josh Gao0cd3ae12016-09-21 12:37:10 -0700723 {
Josh Gao1db71af2017-08-17 13:50:51 -0700724 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700725 auto it = std::find(pending_list.begin(), pending_list.end(), t);
726 if (it != pending_list.end()) {
727 pending_list.remove(t);
728 transport_list.push_front(t);
729 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700730 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800731
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800732 update_transports();
733}
734
Josh Gaodef91c02018-07-31 18:28:32 -0700735#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700736void init_reconnect_handler(void) {
737 reconnect_handler.Start();
738}
Josh Gaodef91c02018-07-31 18:28:32 -0700739#endif
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700740
Josh Gao1290fbf2016-11-22 14:32:34 -0800741void init_transport_registration(void) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800742 int s[2];
743
Josh Gao1290fbf2016-11-22 14:32:34 -0800744 if (adb_socketpair(s)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800745 fatal_errno("cannot open transport registration socketpair");
746 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700747 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800748
749 transport_registration_send = s[0];
750 transport_registration_recv = s[1];
751
Josh Gao71f775a2018-05-14 11:14:33 -0700752 transport_registration_fde =
Yi Kongaed415c2018-07-13 18:15:16 -0700753 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao71f775a2018-05-14 11:14:33 -0700754 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao01b7bc42017-05-09 13:43:35 -0700755}
756
757void kick_all_transports() {
Josh Gaodef91c02018-07-31 18:28:32 -0700758#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700759 reconnect_handler.Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700760#endif
Josh Gao01b7bc42017-05-09 13:43:35 -0700761 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gao1db71af2017-08-17 13:50:51 -0700762 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao01b7bc42017-05-09 13:43:35 -0700763 for (auto t : transport_list) {
764 t->Kick();
765 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800766}
767
768/* the fdevent select pump is single threaded */
Josh Gao1290fbf2016-11-22 14:32:34 -0800769static void register_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800770 tmsg m;
771 m.transport = transport;
772 m.action = 1;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700773 D("transport: %s registered", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800774 if (transport_write_action(transport_registration_send, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800775 fatal_errno("cannot write transport registration socket\n");
776 }
777}
778
Josh Gao1290fbf2016-11-22 14:32:34 -0800779static void remove_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800780 tmsg m;
781 m.transport = transport;
782 m.action = 0;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700783 D("transport: %s removed", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800784 if (transport_write_action(transport_registration_send, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800785 fatal_errno("cannot write transport registration socket\n");
786 }
787}
788
Yabin Cuif4b99282015-08-27 12:03:11 -0700789static void transport_unref(atransport* t) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700790 check_main_thread();
Yabin Cuif4b99282015-08-27 12:03:11 -0700791 CHECK(t != nullptr);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700792
Josh Gaoe48ecce2017-09-13 13:40:57 -0700793 std::lock_guard<std::recursive_mutex> lock(transport_lock);
794 CHECK_GT(t->ref_count, 0u);
795 t->ref_count--;
796 if (t->ref_count == 0) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700797 t->connection()->Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700798#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700799 if (t->IsTcpDevice() && !t->kicked()) {
Josh Gaodef91c02018-07-31 18:28:32 -0700800 D("transport: %s unref (attempting reconnection)", t->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700801 reconnect_handler.TrackTransport(t);
802 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700803 D("transport: %s unref (kicking and closing)", t->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700804 remove_transport(t);
805 }
Josh Gaodef91c02018-07-31 18:28:32 -0700806#else
807 D("transport: %s unref (kicking and closing)", t->serial.c_str());
808 remove_transport(t);
809#endif
810
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100811 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700812 D("transport: %s unref (count=%zu)", t->serial.c_str(), t->ref_count);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -0400813 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800814}
815
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700816static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao1290fbf2016-11-22 14:32:34 -0800817 bool sanitize_qual) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700818 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
819 return qual.empty();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700820
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700821 if (qual.empty()) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700822
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700823 const char* ptr = to_test.c_str();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700824 if (prefix) {
825 while (*prefix) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700826 if (*prefix++ != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700827 }
828 }
829
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700830 for (char ch : qual) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800831 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700832 if (ch != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700833 }
834
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700835 /* Everything matched so far. Return true if *ptr is a NUL. */
836 return !*ptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700837}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800838
Josh Gaob122b172017-08-16 16:57:01 -0700839atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
840 bool* is_ambiguous, std::string* error_out,
841 bool accept_any_state) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700842 atransport* result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800843
Josh Gaob122b172017-08-16 16:57:01 -0700844 if (transport_id != 0) {
845 *error_out =
846 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
847 } else if (serial) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700848 *error_out = android::base::StringPrintf("device '%s' not found", serial);
849 } else if (type == kTransportLocal) {
850 *error_out = "no emulators found";
851 } else if (type == kTransportAny) {
852 *error_out = "no devices/emulators found";
853 } else {
854 *error_out = "no devices found";
855 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800856
Josh Gao1db71af2017-08-17 13:50:51 -0700857 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes8d28e192015-10-07 14:55:10 -0700858 for (const auto& t : transport_list) {
Yabin Cuib5e11412017-03-10 16:01:01 -0800859 if (t->GetConnectionState() == kCsNoPerm) {
David Purselld2acbd12015-12-02 15:14:31 -0800860 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwood37d31112009-08-08 13:53:16 -0400861 continue;
862 }
Mike Lockwood0927bf92009-08-08 12:37:44 -0400863
Josh Gaob122b172017-08-16 16:57:01 -0700864 if (transport_id) {
865 if (t->id == transport_id) {
866 result = t;
867 break;
868 }
869 } else if (serial) {
David Pursell3f902aa2016-03-01 08:58:26 -0800870 if (t->MatchesTarget(serial)) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700871 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700872 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700873 if (is_ambiguous) *is_ambiguous = true;
874 result = nullptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700875 break;
876 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800877 result = t;
Scott Andersone109d262012-04-20 11:21:14 -0700878 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800879 } else {
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700880 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800881 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700882 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700883 if (is_ambiguous) *is_ambiguous = true;
884 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800885 break;
886 }
887 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700888 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800889 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700890 *error_out = "more than one emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700891 if (is_ambiguous) *is_ambiguous = true;
892 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800893 break;
894 }
895 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700896 } else if (type == kTransportAny) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800897 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700898 *error_out = "more than one device/emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700899 if (is_ambiguous) *is_ambiguous = true;
900 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800901 break;
902 }
903 result = t;
904 }
905 }
906 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700907 lock.unlock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800908
Josh Gao704494b2018-05-04 16:04:49 -0700909 if (result && !accept_any_state) {
910 // The caller requires an active transport.
911 // Make sure that we're actually connected.
912 ConnectionState state = result->GetConnectionState();
913 switch (state) {
914 case kCsConnecting:
915 *error_out = "device still connecting";
916 result = nullptr;
917 break;
Benoit Goby77e8e582013-01-15 12:36:47 -0800918
Josh Gao704494b2018-05-04 16:04:49 -0700919 case kCsAuthorizing:
920 *error_out = "device still authorizing";
921 result = nullptr;
922 break;
923
924 case kCsUnauthorized: {
925 *error_out = "device unauthorized.\n";
926 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
927 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
928 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
929 *error_out += "\n";
930 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
931 *error_out += "Otherwise check for a confirmation dialog on your device.";
932 result = nullptr;
933 break;
934 }
935
936 case kCsOffline:
937 *error_out = "device offline";
938 result = nullptr;
939 break;
940
941 default:
942 break;
943 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800944 }
945
946 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700947 *error_out = "success";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800948 }
949
950 return result;
951}
952
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700953bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
954 std::unique_lock<std::mutex> lock(mutex_);
955 ScopedAssumeLocked assume_locked(mutex_);
956 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
957 return connection_established_ready_;
958 }) && connection_established_;
959}
960
961void ConnectionWaitable::SetConnectionEstablished(bool success) {
962 {
963 std::lock_guard<std::mutex> lock(mutex_);
964 if (connection_established_ready_) return;
965 connection_established_ready_ = true;
966 connection_established_ = success;
967 D("connection established with %d", success);
968 }
969 cv_.notify_one();
970}
971
972atransport::~atransport() {
973 // If the connection callback had not been run before, run it now.
974 SetConnectionEstablished(false);
975}
976
Yabin Cuib5e11412017-03-10 16:01:01 -0800977int atransport::Write(apacket* p) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700978 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cuib5e11412017-03-10 16:01:01 -0800979}
980
Yabin Cui7f274902016-04-18 11:22:34 -0700981void atransport::Kick() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700982 if (!kicked_.exchange(true)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700983 D("kicking transport %p %s", this, this->serial.c_str());
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700984 this->connection()->Stop();
Yabin Cui7f274902016-04-18 11:22:34 -0700985 }
986}
987
Yabin Cuib5e11412017-03-10 16:01:01 -0800988ConnectionState atransport::GetConnectionState() const {
989 return connection_state_;
990}
991
992void atransport::SetConnectionState(ConnectionState state) {
993 check_main_thread();
994 connection_state_ = state;
995}
996
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700997void atransport::SetConnection(std::unique_ptr<Connection> connection) {
998 std::lock_guard<std::mutex> lock(mutex_);
999 connection_ = std::shared_ptr<Connection>(std::move(connection));
1000}
1001
Josh Gaoffbd3362018-02-28 14:44:23 -08001002std::string atransport::connection_state_name() const {
Yabin Cuib5e11412017-03-10 16:01:01 -08001003 ConnectionState state = GetConnectionState();
1004 switch (state) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001005 case kCsOffline:
1006 return "offline";
1007 case kCsBootloader:
1008 return "bootloader";
1009 case kCsDevice:
1010 return "device";
1011 case kCsHost:
1012 return "host";
1013 case kCsRecovery:
1014 return "recovery";
1015 case kCsNoPerm:
1016 return UsbNoPermissionsShortHelpText();
1017 case kCsSideload:
1018 return "sideload";
1019 case kCsUnauthorized:
1020 return "unauthorized";
Josh Gao704494b2018-05-04 16:04:49 -07001021 case kCsAuthorizing:
1022 return "authorizing";
1023 case kCsConnecting:
1024 return "connecting";
Josh Gao1290fbf2016-11-22 14:32:34 -08001025 default:
1026 return "unknown";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001027 }
1028}
1029
Tamas Berghammer3d2904c2015-07-13 19:12:28 +01001030void atransport::update_version(int version, size_t payload) {
1031 protocol_version = std::min(version, A_VERSION);
1032 max_payload = std::min(payload, MAX_PAYLOAD);
1033}
1034
1035int atransport::get_protocol_version() const {
1036 return protocol_version;
1037}
1038
1039size_t atransport::get_max_payload() const {
1040 return max_payload;
1041}
1042
Dan Albert1792c232015-05-18 13:06:53 -07001043const FeatureSet& supported_features() {
David Pursell4e2fd362015-09-22 10:43:08 -07001044 // Local static allocation to avoid global non-POD variables.
1045 static const FeatureSet* features = new FeatureSet{
Josh Gao1290fbf2016-11-22 14:32:34 -08001046 kFeatureShell2, kFeatureCmd, kFeatureStat2,
David Pursellbbe3d212015-09-25 08:37:13 -07001047 // Increment ADB_SERVER_VERSION whenever the feature list changes to
1048 // make sure that the adb client and server features stay in sync
1049 // (http://b/24370690).
David Pursell4e2fd362015-09-22 10:43:08 -07001050 };
1051
1052 return *features;
1053}
1054
1055std::string FeatureSetToString(const FeatureSet& features) {
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001056 return android::base::Join(features, ',');
David Pursell4e2fd362015-09-22 10:43:08 -07001057}
1058
1059FeatureSet StringToFeatureSet(const std::string& features_string) {
David Purselld2b588e2015-09-25 13:04:21 -07001060 if (features_string.empty()) {
1061 return FeatureSet();
1062 }
1063
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001064 auto names = android::base::Split(features_string, ",");
David Pursell4e2fd362015-09-22 10:43:08 -07001065 return FeatureSet(names.begin(), names.end());
Dan Albert1792c232015-05-18 13:06:53 -07001066}
1067
David Pursell70ef7b42015-09-30 13:35:42 -07001068bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001069 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell70ef7b42015-09-30 13:35:42 -07001070}
1071
Dan Albert1792c232015-05-18 13:06:53 -07001072bool atransport::has_feature(const std::string& feature) const {
1073 return features_.count(feature) > 0;
1074}
1075
David Pursell4e2fd362015-09-22 10:43:08 -07001076void atransport::SetFeatures(const std::string& features_string) {
1077 features_ = StringToFeatureSet(features_string);
Dan Albert1792c232015-05-18 13:06:53 -07001078}
1079
Yabin Cuib3298242015-08-28 15:09:44 -07001080void atransport::AddDisconnect(adisconnect* disconnect) {
1081 disconnects_.push_back(disconnect);
1082}
1083
1084void atransport::RemoveDisconnect(adisconnect* disconnect) {
1085 disconnects_.remove(disconnect);
1086}
1087
1088void atransport::RunDisconnects() {
Elliott Hughes65fe2512015-10-07 15:59:35 -07001089 for (const auto& disconnect : disconnects_) {
Yabin Cuib3298242015-08-28 15:09:44 -07001090 disconnect->func(disconnect->opaque, this);
1091 }
1092 disconnects_.clear();
1093}
1094
David Pursell3f902aa2016-03-01 08:58:26 -08001095bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001096 if (!serial.empty()) {
David Pursell3f902aa2016-03-01 08:58:26 -08001097 if (target == serial) {
1098 return true;
1099 } else if (type == kTransportLocal) {
1100 // Local transports can match [tcp:|udp:]<hostname>[:port].
1101 const char* local_target_ptr = target.c_str();
1102
1103 // For fastboot compatibility, ignore protocol prefixes.
1104 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao1290fbf2016-11-22 14:32:34 -08001105 android::base::StartsWith(target, "udp:")) {
David Pursell3f902aa2016-03-01 08:58:26 -08001106 local_target_ptr += 4;
1107 }
1108
1109 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1110 std::string serial_host, error;
1111 int serial_port = -1;
Josh Gao1290fbf2016-11-22 14:32:34 -08001112 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursell3f902aa2016-03-01 08:58:26 -08001113 // |target| may omit the port to default to ours.
1114 std::string target_host;
1115 int target_port = serial_port;
1116 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1117 nullptr, &error) &&
Josh Gao1290fbf2016-11-22 14:32:34 -08001118 serial_host == target_host && serial_port == target_port) {
David Pursell3f902aa2016-03-01 08:58:26 -08001119 return true;
1120 }
1121 }
1122 }
1123 }
1124
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001125 return (target == devpath) || qual_match(target, "product:", product, false) ||
1126 qual_match(target, "model:", model, true) ||
1127 qual_match(target, "device:", device, false);
David Pursell3f902aa2016-03-01 08:58:26 -08001128}
1129
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001130void atransport::SetConnectionEstablished(bool success) {
1131 connection_waitable_->SetConnectionEstablished(success);
1132}
1133
Josh Gaofc2e56f2018-08-30 11:37:00 -07001134ReconnectResult atransport::Reconnect() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001135 return reconnect_(this);
1136}
1137
Elliott Hughese67f1f82015-04-30 17:32:03 -07001138#if ADB_HOST
1139
Josh Gaob122b172017-08-16 16:57:01 -07001140// We use newline as our delimiter, make sure to never output it.
1141static std::string sanitize(std::string str, bool alphanumeric) {
1142 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1143 : [](const char c) { return c == '\n'; };
1144 std::replace_if(str.begin(), str.end(), pred, '_');
1145 return str;
1146}
1147
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001148static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob122b172017-08-16 16:57:01 -07001149 bool alphanumeric) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001150 if (value.empty()) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001151 return;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001152 }
1153
Elliott Hughese67f1f82015-04-30 17:32:03 -07001154 *result += ' ';
1155 *result += key;
Josh Gaob122b172017-08-16 16:57:01 -07001156 *result += sanitize(value, alphanumeric);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001157}
1158
Josh Gao1290fbf2016-11-22 14:32:34 -08001159static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001160 std::string serial = t->serial;
1161 if (serial.empty()) {
Dan Albertd99d9022015-05-06 16:48:52 -07001162 serial = "(no serial number)";
Elliott Hughese67f1f82015-04-30 17:32:03 -07001163 }
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001164
1165 if (!long_listing) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001166 *result += serial;
1167 *result += '\t';
1168 *result += t->connection_state_name();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001169 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001170 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1171 t->connection_state_name().c_str());
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001172
Elliott Hughese67f1f82015-04-30 17:32:03 -07001173 append_transport_info(result, "", t->devpath, false);
1174 append_transport_info(result, "product:", t->product, false);
1175 append_transport_info(result, "model:", t->model, true);
1176 append_transport_info(result, "device:", t->device, false);
Josh Gaob122b172017-08-16 16:57:01 -07001177
1178 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1179 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1180 *result += " transport_id:";
1181 *result += std::to_string(t->id);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001182 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001183 *result += '\n';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001184}
1185
Elliott Hughese67f1f82015-04-30 17:32:03 -07001186std::string list_transports(bool long_listing) {
Josh Gao1db71af2017-08-17 13:50:51 -07001187 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov04398a92017-12-17 10:56:07 +00001188
1189 auto sorted_transport_list = transport_list;
1190 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1191 if (x->type != y->type) {
1192 return x->type < y->type;
1193 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001194 return x->serial < y->serial;
Artem Iglikov04398a92017-12-17 10:56:07 +00001195 });
1196
1197 std::string result;
1198 for (const auto& t : sorted_transport_list) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001199 append_transport(t, &result, long_listing);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001200 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001201 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001202}
1203
Josh Gao22d2b3e2016-10-27 14:01:08 -07001204void close_usb_devices(std::function<bool(const atransport*)> predicate) {
Josh Gao1db71af2017-08-17 13:50:51 -07001205 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao22d2b3e2016-10-27 14:01:08 -07001206 for (auto& t : transport_list) {
1207 if (predicate(t)) {
1208 t->Kick();
1209 }
1210 }
1211}
1212
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001213/* hack for osx */
Dan Albertc7915a32015-05-18 16:46:31 -07001214void close_usb_devices() {
Josh Gao22d2b3e2016-10-27 14:01:08 -07001215 close_usb_devices([](const atransport*) { return true; });
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001216}
Josh Gao1290fbf2016-11-22 14:32:34 -08001217#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001218
Josh Gao362e6962018-08-08 16:20:14 -07001219bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
1220 atransport::ReconnectCallback reconnect, int* error) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001221 atransport* t = new atransport(std::move(reconnect), kCsOffline);
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +01001222
Josh Gao3b4de3c2018-08-02 13:58:24 -07001223 D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
Josh Gao56300c92018-07-25 17:21:49 -07001224 if (init_socket_transport(t, std::move(s), port, local) < 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001225 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001226 if (error) *error = errno;
1227 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001228 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001229
Josh Gao1db71af2017-08-17 13:50:51 -07001230 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes65fe2512015-10-07 15:59:35 -07001231 for (const auto& transport : pending_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001232 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001233 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001234 << " is already in pending_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001235 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001236 if (error) *error = EALREADY;
1237 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001238 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001239 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001240
Elliott Hughes65fe2512015-10-07 15:59:35 -07001241 for (const auto& transport : transport_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001242 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001243 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001244 << " is already in transport_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001245 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001246 if (error) *error = EALREADY;
1247 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001248 }
1249 }
1250
Josh Gao3b4de3c2018-08-02 13:58:24 -07001251 t->serial = std::move(serial);
Dan Albertc7915a32015-05-18 16:46:31 -07001252 pending_list.push_front(t);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001253
1254 lock.unlock();
Benoit Goby1c45ee92013-03-29 18:22:36 -07001255
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001256 auto waitable = t->connection_waitable();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001257 register_transport(t);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001258
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001259 if (local == 1) {
1260 // Do not wait for emulator transports.
Josh Gao362e6962018-08-08 16:20:14 -07001261 return true;
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001262 }
1263
Josh Gao362e6962018-08-08 16:20:14 -07001264 if (!waitable->WaitForConnection(std::chrono::seconds(10))) {
1265 if (error) *error = ETIMEDOUT;
1266 return false;
1267 }
1268
1269 if (t->GetConnectionState() == kCsUnauthorized) {
1270 if (error) *error = EPERM;
1271 return false;
1272 }
1273
1274 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001275}
1276
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001277#if ADB_HOST
Josh Gao1290fbf2016-11-22 14:32:34 -08001278atransport* find_transport(const char* serial) {
Dan Albertc7915a32015-05-18 16:46:31 -07001279 atransport* result = nullptr;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001280
Josh Gao1db71af2017-08-17 13:50:51 -07001281 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001282 for (auto& t : transport_list) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001283 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001284 result = t;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001285 break;
1286 }
Dan Albertc7915a32015-05-18 16:46:31 -07001287 }
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001288
Dan Albertc7915a32015-05-18 16:46:31 -07001289 return result;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001290}
1291
Yabin Cuif4b99282015-08-27 12:03:11 -07001292void kick_all_tcp_devices() {
Josh Gao1db71af2017-08-17 13:50:51 -07001293 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001294 for (auto& t : transport_list) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001295 if (t->IsTcpDevice()) {
Yabin Cuid6ab3c22015-08-31 11:50:24 -07001296 // Kicking breaks the read_transport thread of this transport out of any read, then
1297 // the read_transport thread will notify the main thread to make this transport
1298 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cuif4b99282015-08-27 12:03:11 -07001299 // Finally, this transport will be closed and freed in the main thread.
Yabin Cui7f274902016-04-18 11:22:34 -07001300 t->Kick();
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001301 }
Dan Albertc7915a32015-05-18 16:46:31 -07001302 }
Josh Gao902dace2018-08-10 14:44:54 -07001303#if ADB_HOST
1304 reconnect_handler.CheckForKicked();
1305#endif
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001306}
1307
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001308#endif
1309
Josh Gao1290fbf2016-11-22 14:32:34 -08001310void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1311 unsigned writeable) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001312 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertc7915a32015-05-18 16:46:31 -07001313
Josh Gao1290fbf2016-11-22 14:32:34 -08001314 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cuib5e11412017-03-10 16:01:01 -08001315 init_usb_transport(t, usb);
Josh Gao1290fbf2016-11-22 14:32:34 -08001316 if (serial) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001317 t->serial = serial;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001318 }
Dan Albertc7915a32015-05-18 16:46:31 -07001319
1320 if (devpath) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001321 t->devpath = devpath;
Scott Andersone109d262012-04-20 11:21:14 -07001322 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001323
Josh Gao0cd3ae12016-09-21 12:37:10 -07001324 {
Josh Gao1db71af2017-08-17 13:50:51 -07001325 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001326 pending_list.push_front(t);
1327 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001328
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001329 register_transport(t);
1330}
1331
Dan Albertdcd78a12015-05-18 16:43:57 -07001332// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao1290fbf2016-11-22 14:32:34 -08001333void unregister_usb_transport(usb_handle* usb) {
Josh Gao1db71af2017-08-17 13:50:51 -07001334 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaob800d882018-01-28 20:32:46 -08001335 transport_list.remove_if([usb](atransport* t) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -07001336 auto connection = t->connection();
1337 if (auto usb_connection = dynamic_cast<UsbConnection*>(connection.get())) {
1338 return usb_connection->handle_ == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gaob800d882018-01-28 20:32:46 -08001339 }
1340 return false;
1341 });
Mike Lockwood0927bf92009-08-08 12:37:44 -04001342}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001343
Josh Gao36dadca2017-05-16 15:02:45 -07001344bool check_header(apacket* p, atransport* t) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001345 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cuib5e11412017-03-10 16:01:01 -08001346 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1347 << ", magic = " << p->msg.magic;
Josh Gao36dadca2017-05-16 15:02:45 -07001348 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001349 }
1350
Josh Gao1290fbf2016-11-22 14:32:34 -08001351 if (p->msg.data_length > t->get_max_payload()) {
1352 VLOG(RWX) << "check_header(): " << p->msg.data_length
1353 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao36dadca2017-05-16 15:02:45 -07001354 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001355 }
1356
Josh Gao36dadca2017-05-16 15:02:45 -07001357 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001358}
1359
Josh Gao3bd28792016-10-05 19:02:29 -07001360#if ADB_HOST
Josh Gao2e671202016-08-18 22:00:12 -07001361std::shared_ptr<RSA> atransport::NextKey() {
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001362 if (keys_.empty()) keys_ = adb_auth_get_private_keys();
1363
Josh Gao2e671202016-08-18 22:00:12 -07001364 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001365 keys_.pop_front();
1366 return result;
1367}
Josh Gao3bd28792016-10-05 19:02:29 -07001368#endif