blob: b08c7f9bb7ac11e6c8784d9a921c4e1303398a26 [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"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080053
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070054static void register_transport(atransport* transport);
55static void remove_transport(atransport* transport);
56static void transport_unref(atransport* transport);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080057
Josh Gaob122b172017-08-16 16:57:01 -070058// TODO: unordered_map<TransportId, atransport*>
Josh Gaob7b1edf2015-11-11 17:56:12 -080059static auto& transport_list = *new std::list<atransport*>();
60static auto& pending_list = *new std::list<atransport*>();
Benoit Goby1c45ee92013-03-29 18:22:36 -070061
Josh Gao1db71af2017-08-17 13:50:51 -070062static auto& transport_lock = *new std::recursive_mutex();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080063
Todd Kennedy51c05ec2015-11-10 00:03:25 +000064const char* const kFeatureShell2 = "shell_v2";
65const char* const kFeatureCmd = "cmd";
Josh Gao5a1e3fd2016-12-05 17:11:34 -080066const char* const kFeatureStat2 = "stat_v2";
Josh Gao5d1756c2017-02-22 17:07:01 -080067const char* const kFeatureLibusb = "libusb";
Dan Albert5176df82017-05-23 14:30:00 -070068const char* const kFeaturePushSync = "push_sync";
Todd Kennedy51c05ec2015-11-10 00:03:25 +000069
Luis Hector Chavez56fe7532018-04-17 14:25:04 -070070namespace {
71
72// A class that helps the Clang Thread Safety Analysis deal with
73// std::unique_lock. Given that std::unique_lock is movable, and the analysis
74// can not currently perform alias analysis, it is not annotated. In order to
75// assert that the mutex is held, a ScopedAssumeLocked can be created just after
76// the std::unique_lock.
77class SCOPED_CAPABILITY ScopedAssumeLocked {
78 public:
79 ScopedAssumeLocked(std::mutex& mutex) ACQUIRE(mutex) {}
80 ~ScopedAssumeLocked() RELEASE() {}
81};
82
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070083// Tracks and handles atransport*s that are attempting reconnection.
84class ReconnectHandler {
85 public:
86 ReconnectHandler() = default;
87 ~ReconnectHandler() = default;
88
89 // Starts the ReconnectHandler thread.
90 void Start();
91
92 // Requests the ReconnectHandler thread to stop.
93 void Stop();
94
95 // Adds the atransport* to the queue of reconnect attempts.
96 void TrackTransport(atransport* transport);
97
98 private:
99 // The main thread loop.
100 void Run();
101
102 // Tracks a reconnection attempt.
103 struct ReconnectAttempt {
104 atransport* transport;
Josh Gao95af6412018-07-30 18:51:55 -0700105 std::chrono::steady_clock::time_point reconnect_time;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700106 size_t attempts_left;
107 };
108
109 // Only retry for up to one minute.
110 static constexpr const std::chrono::seconds kDefaultTimeout = std::chrono::seconds(10);
111 static constexpr const size_t kMaxAttempts = 6;
112
113 // Protects all members.
114 std::mutex reconnect_mutex_;
115 bool running_ GUARDED_BY(reconnect_mutex_) = true;
116 std::thread handler_thread_;
117 std::condition_variable reconnect_cv_;
118 std::queue<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
119
120 DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
121};
122
123void ReconnectHandler::Start() {
124 check_main_thread();
125 handler_thread_ = std::thread(&ReconnectHandler::Run, this);
126}
127
128void ReconnectHandler::Stop() {
129 check_main_thread();
130 {
131 std::lock_guard<std::mutex> lock(reconnect_mutex_);
132 running_ = false;
133 }
134 reconnect_cv_.notify_one();
135 handler_thread_.join();
136
137 // Drain the queue to free all resources.
138 std::lock_guard<std::mutex> lock(reconnect_mutex_);
139 while (!reconnect_queue_.empty()) {
140 ReconnectAttempt attempt = reconnect_queue_.front();
141 reconnect_queue_.pop();
142 remove_transport(attempt.transport);
143 }
144}
145
146void ReconnectHandler::TrackTransport(atransport* transport) {
147 check_main_thread();
148 {
149 std::lock_guard<std::mutex> lock(reconnect_mutex_);
150 if (!running_) return;
151 reconnect_queue_.emplace(ReconnectAttempt{
Josh Gao95af6412018-07-30 18:51:55 -0700152 transport, std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
153 ReconnectHandler::kMaxAttempts});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700154 }
155 reconnect_cv_.notify_one();
156}
157
158void ReconnectHandler::Run() {
159 while (true) {
160 ReconnectAttempt attempt;
161 {
162 std::unique_lock<std::mutex> lock(reconnect_mutex_);
163 ScopedAssumeLocked assume_lock(reconnect_mutex_);
164
Josh Gao95af6412018-07-30 18:51:55 -0700165 if (!reconnect_queue_.empty()) {
166 // FIXME: libstdc++ (used on Windows) implements condition_variable with
167 // system_clock as its clock, so we're probably hosed if the clock changes,
168 // even if we use steady_clock throughout. This problem goes away once we
169 // switch to libc++.
170 reconnect_cv_.wait_until(lock, reconnect_queue_.front().reconnect_time);
171 } else {
172 reconnect_cv_.wait(lock);
173 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700174
175 if (!running_) return;
Josh Gao95af6412018-07-30 18:51:55 -0700176 if (reconnect_queue_.empty()) continue;
177
178 // Go back to sleep in case |reconnect_cv_| woke up spuriously and we still
179 // have more time to wait for the current attempt.
180 auto now = std::chrono::steady_clock::now();
181 if (reconnect_queue_.front().reconnect_time > now) {
182 continue;
183 }
184
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700185 attempt = reconnect_queue_.front();
186 reconnect_queue_.pop();
187 if (attempt.transport->kicked()) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700188 D("transport %s was kicked. giving up on it.", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700189 remove_transport(attempt.transport);
190 continue;
191 }
192 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700193 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700194
195 if (!attempt.transport->Reconnect()) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700196 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700197 if (attempt.attempts_left == 0) {
198 D("transport %s exceeded the number of retry attempts. giving up on it.",
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700199 attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700200 remove_transport(attempt.transport);
201 continue;
202 }
203
204 std::lock_guard<std::mutex> lock(reconnect_mutex_);
205 reconnect_queue_.emplace(ReconnectAttempt{
Josh Gao95af6412018-07-30 18:51:55 -0700206 attempt.transport,
207 std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
208 attempt.attempts_left - 1});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700209 continue;
210 }
211
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700212 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700213 register_transport(attempt.transport);
214 }
215}
216
217static auto& reconnect_handler = *new ReconnectHandler();
218
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700219} // namespace
220
Josh Gaob122b172017-08-16 16:57:01 -0700221TransportId NextTransportId() {
222 static std::atomic<TransportId> next(1);
223 return next++;
224}
225
Josh Gao0bbf69c2018-02-16 13:24:58 -0800226BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
227 : underlying_(std::move(connection)) {}
228
229BlockingConnectionAdapter::~BlockingConnectionAdapter() {
230 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
231 Stop();
232}
233
234void BlockingConnectionAdapter::Start() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700235 std::lock_guard<std::mutex> lock(mutex_);
236 if (started_) {
237 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
238 << "): started multiple times";
239 }
240
Josh Gao0bbf69c2018-02-16 13:24:58 -0800241 read_thread_ = std::thread([this]() {
242 LOG(INFO) << this->transport_name_ << ": read thread spawning";
243 while (true) {
Josh Gao31b5be62018-03-07 16:51:08 -0800244 auto packet = std::make_unique<apacket>();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800245 if (!underlying_->Read(packet.get())) {
246 PLOG(INFO) << this->transport_name_ << ": read failed";
247 break;
248 }
249 read_callback_(this, std::move(packet));
250 }
251 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
252 });
253
254 write_thread_ = std::thread([this]() {
255 LOG(INFO) << this->transport_name_ << ": write thread spawning";
256 while (true) {
257 std::unique_lock<std::mutex> lock(mutex_);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700258 ScopedAssumeLocked assume_locked(mutex_);
Josh Gaoc251ec52018-04-03 12:55:18 -0700259 cv_.wait(lock, [this]() REQUIRES(mutex_) {
260 return this->stopped_ || !this->write_queue_.empty();
261 });
262
Josh Gao0bbf69c2018-02-16 13:24:58 -0800263 if (this->stopped_) {
264 return;
265 }
266
267 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
268 this->write_queue_.pop_front();
269 lock.unlock();
270
271 if (!this->underlying_->Write(packet.get())) {
272 break;
273 }
274 }
275 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
276 });
Josh Gaoc251ec52018-04-03 12:55:18 -0700277
278 started_ = true;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800279}
280
281void BlockingConnectionAdapter::Stop() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700282 {
283 std::lock_guard<std::mutex> lock(mutex_);
284 if (!started_) {
285 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
286 return;
287 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800288
Josh Gaoc251ec52018-04-03 12:55:18 -0700289 if (stopped_) {
290 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
291 << "): already stopped";
292 return;
293 }
294
295 stopped_ = true;
296 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800297
298 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
299
300 this->underlying_->Close();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800301 this->cv_.notify_one();
Josh Gaoc251ec52018-04-03 12:55:18 -0700302
303 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
304 std::thread read_thread;
305 std::thread write_thread;
306
307 {
308 std::lock_guard<std::mutex> lock(mutex_);
309 read_thread = std::move(read_thread_);
310 write_thread = std::move(write_thread_);
311 }
312
313 read_thread.join();
314 write_thread.join();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800315
316 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
317 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
318}
319
320bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
321 {
Josh Gaoc251ec52018-04-03 12:55:18 -0700322 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800323 write_queue_.emplace_back(std::move(packet));
324 }
325
326 cv_.notify_one();
327 return true;
328}
329
Josh Gaob800d882018-01-28 20:32:46 -0800330bool FdConnection::Read(apacket* packet) {
331 if (!ReadFdExactly(fd_.get(), &packet->msg, sizeof(amessage))) {
332 D("remote local: read terminated (message)");
333 return false;
334 }
335
Josh Gaof571fcb2018-02-05 18:49:10 -0800336 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gao5caaebd2018-02-02 14:38:04 -0800337 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
338 return false;
339 }
340
Josh Gaof571fcb2018-02-05 18:49:10 -0800341 packet->payload.resize(packet->msg.data_length);
342
343 if (!ReadFdExactly(fd_.get(), &packet->payload[0], packet->payload.size())) {
Josh Gaob800d882018-01-28 20:32:46 -0800344 D("remote local: terminated (data)");
345 return false;
346 }
347
348 return true;
349}
350
351bool FdConnection::Write(apacket* packet) {
Josh Gaof571fcb2018-02-05 18:49:10 -0800352 if (!WriteFdExactly(fd_.get(), &packet->msg, sizeof(packet->msg))) {
Josh Gaob800d882018-01-28 20:32:46 -0800353 D("remote local: write terminated");
354 return false;
355 }
356
Josh Gaof571fcb2018-02-05 18:49:10 -0800357 if (packet->msg.data_length) {
358 if (!WriteFdExactly(fd_.get(), &packet->payload[0], packet->msg.data_length)) {
359 D("remote local: write terminated");
360 return false;
361 }
362 }
363
Josh Gaob800d882018-01-28 20:32:46 -0800364 return true;
365}
366
367void FdConnection::Close() {
368 adb_shutdown(fd_.get());
369 fd_.reset();
370}
371
Yabin Cuiaed3c612015-09-22 15:52:57 -0700372static std::string dump_packet(const char* name, const char* func, apacket* p) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800373 unsigned command = p->msg.command;
374 int len = p->msg.data_length;
375 char cmd[9];
376 char arg0[12], arg1[12];
377 int n;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100378
379 for (n = 0; n < 4; n++) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800380 int b = (command >> (n * 8)) & 255;
381 if (b < 32 || b >= 127) break;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100382 cmd[n] = (char)b;
383 }
384 if (n == 4) {
385 cmd[4] = 0;
386 } else {
387 /* There is some non-ASCII name in the command, so dump
388 * the hexadecimal value instead */
389 snprintf(cmd, sizeof cmd, "%08x", command);
390 }
391
392 if (p->msg.arg0 < 256U)
393 snprintf(arg0, sizeof arg0, "%d", p->msg.arg0);
394 else
395 snprintf(arg0, sizeof arg0, "0x%x", p->msg.arg0);
396
397 if (p->msg.arg1 < 256U)
398 snprintf(arg1, sizeof arg1, "%d", p->msg.arg1);
399 else
400 snprintf(arg1, sizeof arg1, "0x%x", p->msg.arg1);
401
Josh Gao1290fbf2016-11-22 14:32:34 -0800402 std::string result = android::base::StringPrintf("%s: %s: [%s] arg0=%s arg1=%s (len=%d) ", name,
403 func, cmd, arg0, arg1, len);
Josh Gaof571fcb2018-02-05 18:49:10 -0800404 result += dump_hex(p->payload.data(), p->payload.size());
Yabin Cuiaed3c612015-09-22 15:52:57 -0700405 return result;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100406}
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100407
Josh Gao06d61d42016-10-06 13:31:44 -0700408void send_packet(apacket* p, atransport* t) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800409 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayde471942017-12-07 11:40:00 -0800410 // compute a checksum for connection/auth packets for compatibility reasons
411 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
412 p->msg.data_check = 0;
413 } else {
414 p->msg.data_check = calculate_apacket_checksum(p);
415 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800416
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700417 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800418
Yi Kongaed415c2018-07-13 18:15:16 -0700419 if (t == nullptr) {
Josh Gao06d61d42016-10-06 13:31:44 -0700420 fatal("Transport is null");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800421 }
422
Josh Gao0bbf69c2018-02-16 13:24:58 -0800423 if (t->Write(p) != 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700424 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800425 t->Kick();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800426 }
427}
428
Yabin Cuif4b99282015-08-27 12:03:11 -0700429void kick_transport(atransport* t) {
Josh Gao1db71af2017-08-17 13:50:51 -0700430 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui1f4ec192016-04-05 13:50:44 -0700431 // As kick_transport() can be called from threads without guarantee that t is valid,
432 // check if the transport is in transport_list first.
Josh Gaob122b172017-08-16 16:57:01 -0700433 //
434 // TODO(jmgao): WTF? Is this actually true?
Yabin Cui1f4ec192016-04-05 13:50:44 -0700435 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Yabin Cui7f274902016-04-18 11:22:34 -0700436 t->Kick();
Yabin Cui1f4ec192016-04-05 13:50:44 -0700437 }
Yabin Cuif4b99282015-08-27 12:03:11 -0700438}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800439
440static int transport_registration_send = -1;
441static int transport_registration_recv = -1;
Josh Gao71f775a2018-05-14 11:14:33 -0700442static fdevent* transport_registration_fde;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800443
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800444#if ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800445
446/* this adds support required by the 'track-devices' service.
447 * this is used to send the content of "list_transport" to any
448 * number of client connections that want it through a single
449 * live TCP connection
450 */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800451struct device_tracker {
Josh Gao1290fbf2016-11-22 14:32:34 -0800452 asocket socket;
Josh Gaoe0361d12018-02-12 17:24:00 -0800453 bool update_needed = false;
454 bool long_output = false;
455 device_tracker* next = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800456};
457
458/* linked list of all device trackers */
Josh Gao1290fbf2016-11-22 14:32:34 -0800459static device_tracker* device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800460
Josh Gao1290fbf2016-11-22 14:32:34 -0800461static void device_tracker_remove(device_tracker* tracker) {
462 device_tracker** pnode = &device_tracker_list;
463 device_tracker* node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800464
Josh Gao1db71af2017-08-17 13:50:51 -0700465 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800466 while (node) {
467 if (node == tracker) {
468 *pnode = node->next;
469 break;
470 }
471 pnode = &node->next;
Josh Gao1290fbf2016-11-22 14:32:34 -0800472 node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800473 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800474}
475
Josh Gao1290fbf2016-11-22 14:32:34 -0800476static void device_tracker_close(asocket* socket) {
477 device_tracker* tracker = (device_tracker*)socket;
478 asocket* peer = socket->peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800479
Josh Gao1290fbf2016-11-22 14:32:34 -0800480 D("device tracker %p removed", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800481 if (peer) {
Yi Kongaed415c2018-07-13 18:15:16 -0700482 peer->peer = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800483 peer->close(peer);
484 }
485 device_tracker_remove(tracker);
Josh Gaoe0361d12018-02-12 17:24:00 -0800486 delete tracker;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800487}
488
Josh Gao1ce99572018-03-07 16:52:28 -0800489static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800490 /* you can't read from a device tracker, close immediately */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800491 device_tracker_close(socket);
492 return -1;
493}
494
Elliott Hughese67f1f82015-04-30 17:32:03 -0700495static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700496 asocket* peer = tracker->socket.peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800497
Josh Gao1ce99572018-03-07 16:52:28 -0800498 apacket::payload_type data;
Josh Gao27cb7dc2018-02-01 13:17:50 -0800499 data.resize(4 + string.size());
500 char buf[5];
501 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
502 memcpy(&data[0], buf, 4);
503 memcpy(&data[4], string.data(), string.size());
504 return peer->enqueue(peer, std::move(data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800505}
506
Elliott Hughese67f1f82015-04-30 17:32:03 -0700507static void device_tracker_ready(asocket* socket) {
508 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800509
Elliott Hughese67f1f82015-04-30 17:32:03 -0700510 // We want to send the device list when the tracker connects
511 // for the first time, even if no update occurred.
Josh Gaob0c18022017-08-14 18:57:54 -0700512 if (tracker->update_needed) {
513 tracker->update_needed = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800514
Josh Gaob0c18022017-08-14 18:57:54 -0700515 std::string transports = list_transports(tracker->long_output);
Elliott Hughese67f1f82015-04-30 17:32:03 -0700516 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800517 }
518}
519
Josh Gaob0c18022017-08-14 18:57:54 -0700520asocket* create_device_tracker(bool long_output) {
Josh Gaoe0361d12018-02-12 17:24:00 -0800521 device_tracker* tracker = new device_tracker();
Elliott Hughesdc3b4592015-04-21 19:39:52 -0700522 if (tracker == nullptr) fatal("cannot allocate device tracker");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800523
Josh Gao1290fbf2016-11-22 14:32:34 -0800524 D("device tracker %p created", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800525
526 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao1290fbf2016-11-22 14:32:34 -0800527 tracker->socket.ready = device_tracker_ready;
528 tracker->socket.close = device_tracker_close;
Josh Gaob0c18022017-08-14 18:57:54 -0700529 tracker->update_needed = true;
530 tracker->long_output = long_output;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800531
Josh Gao1290fbf2016-11-22 14:32:34 -0800532 tracker->next = device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800533 device_tracker_list = tracker;
534
535 return &tracker->socket;
536}
537
Josh Gaofd713e52017-05-03 22:37:10 -0700538// Check if all of the USB transports are connected.
539bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gao1db71af2017-08-17 13:50:51 -0700540 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaofd713e52017-05-03 22:37:10 -0700541 for (const auto& t : transport_list) {
542 if (!fn(t)) {
543 return false;
544 }
545 }
546 for (const auto& t : pending_list) {
547 if (!fn(t)) {
548 return false;
549 }
550 }
551 return true;
552}
553
Elliott Hughese67f1f82015-04-30 17:32:03 -0700554// Call this function each time the transport list has changed.
555void update_transports() {
Josh Gaofd713e52017-05-03 22:37:10 -0700556 update_transport_status();
557
558 // Notify `adb track-devices` clients.
Elliott Hughese67f1f82015-04-30 17:32:03 -0700559 std::string transports = list_transports(false);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800560
Elliott Hughese67f1f82015-04-30 17:32:03 -0700561 device_tracker* tracker = device_tracker_list;
562 while (tracker != nullptr) {
563 device_tracker* next = tracker->next;
564 // This may destroy the tracker if the connection is closed.
565 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800566 tracker = next;
567 }
568}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700569
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800570#else
Elliott Hughese67f1f82015-04-30 17:32:03 -0700571
572void update_transports() {
573 // Nothing to do on the device side.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800574}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700575
Josh Gao1290fbf2016-11-22 14:32:34 -0800576#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800577
Josh Gao1290fbf2016-11-22 14:32:34 -0800578struct tmsg {
579 atransport* transport;
580 int action;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800581};
582
Josh Gao1290fbf2016-11-22 14:32:34 -0800583static int transport_read_action(int fd, struct tmsg* m) {
584 char* p = (char*)m;
585 int len = sizeof(*m);
586 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800587
Josh Gao1290fbf2016-11-22 14:32:34 -0800588 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800589 r = adb_read(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800590 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800591 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800592 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800593 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700594 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800595 return -1;
596 }
597 }
598 return 0;
599}
600
Josh Gao1290fbf2016-11-22 14:32:34 -0800601static int transport_write_action(int fd, struct tmsg* m) {
602 char* p = (char*)m;
603 int len = sizeof(*m);
604 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800605
Josh Gao1290fbf2016-11-22 14:32:34 -0800606 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800607 r = adb_write(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800608 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800609 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800610 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800611 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700612 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800613 return -1;
614 }
615 }
616 return 0;
617}
618
Josh Gao0bbf69c2018-02-16 13:24:58 -0800619static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800620 tmsg m;
Josh Gao1290fbf2016-11-22 14:32:34 -0800621 atransport* t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800622
Josh Gao1290fbf2016-11-22 14:32:34 -0800623 if (!(ev & FDE_READ)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800624 return;
625 }
626
Josh Gao1290fbf2016-11-22 14:32:34 -0800627 if (transport_read_action(_fd, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800628 fatal_errno("cannot read transport registration socket");
629 }
630
631 t = m.transport;
632
Dan Albert1792c232015-05-18 13:06:53 -0700633 if (m.action == 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700634 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800635
Josh Gao0cd3ae12016-09-21 12:37:10 -0700636 {
Josh Gao1db71af2017-08-17 13:50:51 -0700637 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700638 transport_list.remove(t);
639 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800640
Dan Albertc7915a32015-05-18 16:46:31 -0700641 delete t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800642
643 update_transports();
644 return;
645 }
646
Mike Lockwood0927bf92009-08-08 12:37:44 -0400647 /* don't create transport threads for inaccessible devices */
Yabin Cuib5e11412017-03-10 16:01:01 -0800648 if (t->GetConnectionState() != kCsNoPerm) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700649 // The connection gets a reference to the atransport. It will release it
650 // upon a read/write error.
651 t->ref_count++;
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700652 t->connection()->SetTransportName(t->serial_name());
653 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao0bbf69c2018-02-16 13:24:58 -0800654 if (!check_header(p.get(), t)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700655 D("%s: remote read: bad header", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800656 return false;
657 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800658
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700659 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "from remote", p.get());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800660 apacket* packet = p.release();
Mike Lockwood0927bf92009-08-08 12:37:44 -0400661
Josh Gao0bbf69c2018-02-16 13:24:58 -0800662 // TODO: Does this need to run on the main thread?
663 fdevent_run_on_main_thread([packet, t]() { handle_packet(packet, t); });
664 return true;
665 });
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700666 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700667 D("%s: connection terminated: %s", t->serial.c_str(), error.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800668 fdevent_run_on_main_thread([t]() {
669 handle_offline(t);
670 transport_unref(t);
671 });
672 });
Mike Lockwood0927bf92009-08-08 12:37:44 -0400673
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700674 t->connection()->Start();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800675#if ADB_HOST
676 send_connect(t);
677#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800678 }
679
Josh Gao0cd3ae12016-09-21 12:37:10 -0700680 {
Josh Gao1db71af2017-08-17 13:50:51 -0700681 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700682 auto it = std::find(pending_list.begin(), pending_list.end(), t);
683 if (it != pending_list.end()) {
684 pending_list.remove(t);
685 transport_list.push_front(t);
686 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700687 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800688
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800689 update_transports();
690}
691
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700692void init_reconnect_handler(void) {
693 reconnect_handler.Start();
694}
695
Josh Gao1290fbf2016-11-22 14:32:34 -0800696void init_transport_registration(void) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800697 int s[2];
698
Josh Gao1290fbf2016-11-22 14:32:34 -0800699 if (adb_socketpair(s)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800700 fatal_errno("cannot open transport registration socketpair");
701 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700702 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800703
704 transport_registration_send = s[0];
705 transport_registration_recv = s[1];
706
Josh Gao71f775a2018-05-14 11:14:33 -0700707 transport_registration_fde =
Yi Kongaed415c2018-07-13 18:15:16 -0700708 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao71f775a2018-05-14 11:14:33 -0700709 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao01b7bc42017-05-09 13:43:35 -0700710}
711
712void kick_all_transports() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700713 reconnect_handler.Stop();
Josh Gao01b7bc42017-05-09 13:43:35 -0700714 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gao1db71af2017-08-17 13:50:51 -0700715 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao01b7bc42017-05-09 13:43:35 -0700716 for (auto t : transport_list) {
717 t->Kick();
718 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800719}
720
721/* the fdevent select pump is single threaded */
Josh Gao1290fbf2016-11-22 14:32:34 -0800722static void register_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800723 tmsg m;
724 m.transport = transport;
725 m.action = 1;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700726 D("transport: %s registered", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800727 if (transport_write_action(transport_registration_send, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800728 fatal_errno("cannot write transport registration socket\n");
729 }
730}
731
Josh Gao1290fbf2016-11-22 14:32:34 -0800732static void remove_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800733 tmsg m;
734 m.transport = transport;
735 m.action = 0;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700736 D("transport: %s removed", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800737 if (transport_write_action(transport_registration_send, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800738 fatal_errno("cannot write transport registration socket\n");
739 }
740}
741
Yabin Cuif4b99282015-08-27 12:03:11 -0700742static void transport_unref(atransport* t) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700743 check_main_thread();
Yabin Cuif4b99282015-08-27 12:03:11 -0700744 CHECK(t != nullptr);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700745
Josh Gaoe48ecce2017-09-13 13:40:57 -0700746 std::lock_guard<std::recursive_mutex> lock(transport_lock);
747 CHECK_GT(t->ref_count, 0u);
748 t->ref_count--;
749 if (t->ref_count == 0) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700750 t->connection()->Stop();
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700751 if (t->IsTcpDevice() && !t->kicked()) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700752 D("transport: %s unref (attempting reconnection) %d", t->serial.c_str(), t->kicked());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700753 reconnect_handler.TrackTransport(t);
754 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700755 D("transport: %s unref (kicking and closing)", t->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700756 remove_transport(t);
757 }
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100758 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700759 D("transport: %s unref (count=%zu)", t->serial.c_str(), t->ref_count);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -0400760 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800761}
762
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700763static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao1290fbf2016-11-22 14:32:34 -0800764 bool sanitize_qual) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700765 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
766 return qual.empty();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700767
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700768 if (qual.empty()) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700769
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700770 const char* ptr = to_test.c_str();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700771 if (prefix) {
772 while (*prefix) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700773 if (*prefix++ != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700774 }
775 }
776
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700777 for (char ch : qual) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800778 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700779 if (ch != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700780 }
781
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700782 /* Everything matched so far. Return true if *ptr is a NUL. */
783 return !*ptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700784}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800785
Josh Gaob122b172017-08-16 16:57:01 -0700786atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
787 bool* is_ambiguous, std::string* error_out,
788 bool accept_any_state) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700789 atransport* result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800790
Josh Gaob122b172017-08-16 16:57:01 -0700791 if (transport_id != 0) {
792 *error_out =
793 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
794 } else if (serial) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700795 *error_out = android::base::StringPrintf("device '%s' not found", serial);
796 } else if (type == kTransportLocal) {
797 *error_out = "no emulators found";
798 } else if (type == kTransportAny) {
799 *error_out = "no devices/emulators found";
800 } else {
801 *error_out = "no devices found";
802 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800803
Josh Gao1db71af2017-08-17 13:50:51 -0700804 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes8d28e192015-10-07 14:55:10 -0700805 for (const auto& t : transport_list) {
Yabin Cuib5e11412017-03-10 16:01:01 -0800806 if (t->GetConnectionState() == kCsNoPerm) {
David Purselld2acbd12015-12-02 15:14:31 -0800807 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwood37d31112009-08-08 13:53:16 -0400808 continue;
809 }
Mike Lockwood0927bf92009-08-08 12:37:44 -0400810
Josh Gaob122b172017-08-16 16:57:01 -0700811 if (transport_id) {
812 if (t->id == transport_id) {
813 result = t;
814 break;
815 }
816 } else if (serial) {
David Pursell3f902aa2016-03-01 08:58:26 -0800817 if (t->MatchesTarget(serial)) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700818 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700819 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700820 if (is_ambiguous) *is_ambiguous = true;
821 result = nullptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700822 break;
823 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800824 result = t;
Scott Andersone109d262012-04-20 11:21:14 -0700825 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800826 } else {
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700827 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800828 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700829 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700830 if (is_ambiguous) *is_ambiguous = true;
831 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800832 break;
833 }
834 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700835 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800836 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700837 *error_out = "more than one emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700838 if (is_ambiguous) *is_ambiguous = true;
839 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800840 break;
841 }
842 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700843 } else if (type == kTransportAny) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800844 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700845 *error_out = "more than one device/emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700846 if (is_ambiguous) *is_ambiguous = true;
847 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800848 break;
849 }
850 result = t;
851 }
852 }
853 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700854 lock.unlock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800855
Josh Gao704494b2018-05-04 16:04:49 -0700856 if (result && !accept_any_state) {
857 // The caller requires an active transport.
858 // Make sure that we're actually connected.
859 ConnectionState state = result->GetConnectionState();
860 switch (state) {
861 case kCsConnecting:
862 *error_out = "device still connecting";
863 result = nullptr;
864 break;
Benoit Goby77e8e582013-01-15 12:36:47 -0800865
Josh Gao704494b2018-05-04 16:04:49 -0700866 case kCsAuthorizing:
867 *error_out = "device still authorizing";
868 result = nullptr;
869 break;
870
871 case kCsUnauthorized: {
872 *error_out = "device unauthorized.\n";
873 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
874 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
875 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
876 *error_out += "\n";
877 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
878 *error_out += "Otherwise check for a confirmation dialog on your device.";
879 result = nullptr;
880 break;
881 }
882
883 case kCsOffline:
884 *error_out = "device offline";
885 result = nullptr;
886 break;
887
888 default:
889 break;
890 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800891 }
892
893 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700894 *error_out = "success";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800895 }
896
897 return result;
898}
899
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700900bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
901 std::unique_lock<std::mutex> lock(mutex_);
902 ScopedAssumeLocked assume_locked(mutex_);
903 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
904 return connection_established_ready_;
905 }) && connection_established_;
906}
907
908void ConnectionWaitable::SetConnectionEstablished(bool success) {
909 {
910 std::lock_guard<std::mutex> lock(mutex_);
911 if (connection_established_ready_) return;
912 connection_established_ready_ = true;
913 connection_established_ = success;
914 D("connection established with %d", success);
915 }
916 cv_.notify_one();
917}
918
919atransport::~atransport() {
920 // If the connection callback had not been run before, run it now.
921 SetConnectionEstablished(false);
922}
923
Yabin Cuib5e11412017-03-10 16:01:01 -0800924int atransport::Write(apacket* p) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700925 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cuib5e11412017-03-10 16:01:01 -0800926}
927
Yabin Cui7f274902016-04-18 11:22:34 -0700928void atransport::Kick() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700929 if (!kicked_.exchange(true)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700930 D("kicking transport %p %s", this, this->serial.c_str());
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700931 this->connection()->Stop();
Yabin Cui7f274902016-04-18 11:22:34 -0700932 }
933}
934
Yabin Cuib5e11412017-03-10 16:01:01 -0800935ConnectionState atransport::GetConnectionState() const {
936 return connection_state_;
937}
938
939void atransport::SetConnectionState(ConnectionState state) {
940 check_main_thread();
941 connection_state_ = state;
942}
943
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700944void atransport::SetConnection(std::unique_ptr<Connection> connection) {
945 std::lock_guard<std::mutex> lock(mutex_);
946 connection_ = std::shared_ptr<Connection>(std::move(connection));
947}
948
Josh Gaoffbd3362018-02-28 14:44:23 -0800949std::string atransport::connection_state_name() const {
Yabin Cuib5e11412017-03-10 16:01:01 -0800950 ConnectionState state = GetConnectionState();
951 switch (state) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800952 case kCsOffline:
953 return "offline";
954 case kCsBootloader:
955 return "bootloader";
956 case kCsDevice:
957 return "device";
958 case kCsHost:
959 return "host";
960 case kCsRecovery:
961 return "recovery";
962 case kCsNoPerm:
963 return UsbNoPermissionsShortHelpText();
964 case kCsSideload:
965 return "sideload";
966 case kCsUnauthorized:
967 return "unauthorized";
Josh Gao704494b2018-05-04 16:04:49 -0700968 case kCsAuthorizing:
969 return "authorizing";
970 case kCsConnecting:
971 return "connecting";
Josh Gao1290fbf2016-11-22 14:32:34 -0800972 default:
973 return "unknown";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800974 }
975}
976
Tamas Berghammer3d2904c2015-07-13 19:12:28 +0100977void atransport::update_version(int version, size_t payload) {
978 protocol_version = std::min(version, A_VERSION);
979 max_payload = std::min(payload, MAX_PAYLOAD);
980}
981
982int atransport::get_protocol_version() const {
983 return protocol_version;
984}
985
986size_t atransport::get_max_payload() const {
987 return max_payload;
988}
989
David Pursell4e2fd362015-09-22 10:43:08 -0700990namespace {
David Pursell0955c662015-08-31 10:42:13 -0700991
David Pursell4e2fd362015-09-22 10:43:08 -0700992constexpr char kFeatureStringDelimiter = ',';
993
994} // namespace
Dan Albert1792c232015-05-18 13:06:53 -0700995
996const FeatureSet& supported_features() {
David Pursell4e2fd362015-09-22 10:43:08 -0700997 // Local static allocation to avoid global non-POD variables.
998 static const FeatureSet* features = new FeatureSet{
Josh Gao1290fbf2016-11-22 14:32:34 -0800999 kFeatureShell2, kFeatureCmd, kFeatureStat2,
David Pursellbbe3d212015-09-25 08:37:13 -07001000 // Increment ADB_SERVER_VERSION whenever the feature list changes to
1001 // make sure that the adb client and server features stay in sync
1002 // (http://b/24370690).
David Pursell4e2fd362015-09-22 10:43:08 -07001003 };
1004
1005 return *features;
1006}
1007
1008std::string FeatureSetToString(const FeatureSet& features) {
1009 return android::base::Join(features, kFeatureStringDelimiter);
1010}
1011
1012FeatureSet StringToFeatureSet(const std::string& features_string) {
David Purselld2b588e2015-09-25 13:04:21 -07001013 if (features_string.empty()) {
1014 return FeatureSet();
1015 }
1016
Josh Gao1290fbf2016-11-22 14:32:34 -08001017 auto names = android::base::Split(features_string, {kFeatureStringDelimiter});
David Pursell4e2fd362015-09-22 10:43:08 -07001018 return FeatureSet(names.begin(), names.end());
Dan Albert1792c232015-05-18 13:06:53 -07001019}
1020
David Pursell70ef7b42015-09-30 13:35:42 -07001021bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001022 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell70ef7b42015-09-30 13:35:42 -07001023}
1024
Dan Albert1792c232015-05-18 13:06:53 -07001025bool atransport::has_feature(const std::string& feature) const {
1026 return features_.count(feature) > 0;
1027}
1028
David Pursell4e2fd362015-09-22 10:43:08 -07001029void atransport::SetFeatures(const std::string& features_string) {
1030 features_ = StringToFeatureSet(features_string);
Dan Albert1792c232015-05-18 13:06:53 -07001031}
1032
Yabin Cuib3298242015-08-28 15:09:44 -07001033void atransport::AddDisconnect(adisconnect* disconnect) {
1034 disconnects_.push_back(disconnect);
1035}
1036
1037void atransport::RemoveDisconnect(adisconnect* disconnect) {
1038 disconnects_.remove(disconnect);
1039}
1040
1041void atransport::RunDisconnects() {
Elliott Hughes65fe2512015-10-07 15:59:35 -07001042 for (const auto& disconnect : disconnects_) {
Yabin Cuib3298242015-08-28 15:09:44 -07001043 disconnect->func(disconnect->opaque, this);
1044 }
1045 disconnects_.clear();
1046}
1047
David Pursell3f902aa2016-03-01 08:58:26 -08001048bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001049 if (!serial.empty()) {
David Pursell3f902aa2016-03-01 08:58:26 -08001050 if (target == serial) {
1051 return true;
1052 } else if (type == kTransportLocal) {
1053 // Local transports can match [tcp:|udp:]<hostname>[:port].
1054 const char* local_target_ptr = target.c_str();
1055
1056 // For fastboot compatibility, ignore protocol prefixes.
1057 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao1290fbf2016-11-22 14:32:34 -08001058 android::base::StartsWith(target, "udp:")) {
David Pursell3f902aa2016-03-01 08:58:26 -08001059 local_target_ptr += 4;
1060 }
1061
1062 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1063 std::string serial_host, error;
1064 int serial_port = -1;
Josh Gao1290fbf2016-11-22 14:32:34 -08001065 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursell3f902aa2016-03-01 08:58:26 -08001066 // |target| may omit the port to default to ours.
1067 std::string target_host;
1068 int target_port = serial_port;
1069 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1070 nullptr, &error) &&
Josh Gao1290fbf2016-11-22 14:32:34 -08001071 serial_host == target_host && serial_port == target_port) {
David Pursell3f902aa2016-03-01 08:58:26 -08001072 return true;
1073 }
1074 }
1075 }
1076 }
1077
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001078 return (target == devpath) || qual_match(target, "product:", product, false) ||
1079 qual_match(target, "model:", model, true) ||
1080 qual_match(target, "device:", device, false);
David Pursell3f902aa2016-03-01 08:58:26 -08001081}
1082
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001083void atransport::SetConnectionEstablished(bool success) {
1084 connection_waitable_->SetConnectionEstablished(success);
1085}
1086
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001087bool atransport::Reconnect() {
1088 return reconnect_(this);
1089}
1090
Elliott Hughese67f1f82015-04-30 17:32:03 -07001091#if ADB_HOST
1092
Josh Gaob122b172017-08-16 16:57:01 -07001093// We use newline as our delimiter, make sure to never output it.
1094static std::string sanitize(std::string str, bool alphanumeric) {
1095 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1096 : [](const char c) { return c == '\n'; };
1097 std::replace_if(str.begin(), str.end(), pred, '_');
1098 return str;
1099}
1100
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001101static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob122b172017-08-16 16:57:01 -07001102 bool alphanumeric) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001103 if (value.empty()) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001104 return;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001105 }
1106
Elliott Hughese67f1f82015-04-30 17:32:03 -07001107 *result += ' ';
1108 *result += key;
Josh Gaob122b172017-08-16 16:57:01 -07001109 *result += sanitize(value, alphanumeric);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001110}
1111
Josh Gao1290fbf2016-11-22 14:32:34 -08001112static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001113 std::string serial = t->serial;
1114 if (serial.empty()) {
Dan Albertd99d9022015-05-06 16:48:52 -07001115 serial = "(no serial number)";
Elliott Hughese67f1f82015-04-30 17:32:03 -07001116 }
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001117
1118 if (!long_listing) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001119 *result += serial;
1120 *result += '\t';
1121 *result += t->connection_state_name();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001122 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001123 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1124 t->connection_state_name().c_str());
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001125
Elliott Hughese67f1f82015-04-30 17:32:03 -07001126 append_transport_info(result, "", t->devpath, false);
1127 append_transport_info(result, "product:", t->product, false);
1128 append_transport_info(result, "model:", t->model, true);
1129 append_transport_info(result, "device:", t->device, false);
Josh Gaob122b172017-08-16 16:57:01 -07001130
1131 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1132 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1133 *result += " transport_id:";
1134 *result += std::to_string(t->id);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001135 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001136 *result += '\n';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001137}
1138
Elliott Hughese67f1f82015-04-30 17:32:03 -07001139std::string list_transports(bool long_listing) {
Josh Gao1db71af2017-08-17 13:50:51 -07001140 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov04398a92017-12-17 10:56:07 +00001141
1142 auto sorted_transport_list = transport_list;
1143 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1144 if (x->type != y->type) {
1145 return x->type < y->type;
1146 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001147 return x->serial < y->serial;
Artem Iglikov04398a92017-12-17 10:56:07 +00001148 });
1149
1150 std::string result;
1151 for (const auto& t : sorted_transport_list) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001152 append_transport(t, &result, long_listing);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001153 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001154 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001155}
1156
Josh Gao22d2b3e2016-10-27 14:01:08 -07001157void close_usb_devices(std::function<bool(const atransport*)> predicate) {
Josh Gao1db71af2017-08-17 13:50:51 -07001158 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao22d2b3e2016-10-27 14:01:08 -07001159 for (auto& t : transport_list) {
1160 if (predicate(t)) {
1161 t->Kick();
1162 }
1163 }
1164}
1165
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001166/* hack for osx */
Dan Albertc7915a32015-05-18 16:46:31 -07001167void close_usb_devices() {
Josh Gao22d2b3e2016-10-27 14:01:08 -07001168 close_usb_devices([](const atransport*) { return true; });
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001169}
Josh Gao1290fbf2016-11-22 14:32:34 -08001170#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001171
Josh Gao56300c92018-07-25 17:21:49 -07001172int register_socket_transport(unique_fd s, const char* serial, int port, int local,
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001173 atransport::ReconnectCallback reconnect) {
1174 atransport* t = new atransport(std::move(reconnect), kCsOffline);
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +01001175
1176 if (!serial) {
Dan Albertc7915a32015-05-18 16:46:31 -07001177 char buf[32];
1178 snprintf(buf, sizeof(buf), "T-%p", t);
1179 serial = buf;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +01001180 }
Dan Albertc7915a32015-05-18 16:46:31 -07001181
Josh Gao56300c92018-07-25 17:21:49 -07001182 D("transport: %s init'ing for socket %d, on port %d", serial, s.get(), port);
1183 if (init_socket_transport(t, std::move(s), port, local) < 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001184 delete t;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001185 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001186 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001187
Josh Gao1db71af2017-08-17 13:50:51 -07001188 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes65fe2512015-10-07 15:59:35 -07001189 for (const auto& transport : pending_list) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001190 if (strcmp(serial, transport->serial.c_str()) == 0) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001191 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001192 << " is already in pending_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001193 delete t;
Luis Hector Chavez5d395852018-04-17 14:09:21 -07001194 return -EALREADY;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001195 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001196 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001197
Elliott Hughes65fe2512015-10-07 15:59:35 -07001198 for (const auto& transport : transport_list) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001199 if (strcmp(serial, transport->serial.c_str()) == 0) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001200 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001201 << " is already in transport_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001202 delete t;
Luis Hector Chavez5d395852018-04-17 14:09:21 -07001203 return -EALREADY;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001204 }
1205 }
1206
Dan Albertc7915a32015-05-18 16:46:31 -07001207 pending_list.push_front(t);
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001208 t->serial = serial;
Josh Gao0cd3ae12016-09-21 12:37:10 -07001209
1210 lock.unlock();
Benoit Goby1c45ee92013-03-29 18:22:36 -07001211
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001212 auto waitable = t->connection_waitable();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001213 register_transport(t);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001214
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001215 if (local == 1) {
1216 // Do not wait for emulator transports.
1217 return 0;
1218 }
1219
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001220 return waitable->WaitForConnection(std::chrono::seconds(10)) ? 0 : -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001221}
1222
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001223#if ADB_HOST
Josh Gao1290fbf2016-11-22 14:32:34 -08001224atransport* find_transport(const char* serial) {
Dan Albertc7915a32015-05-18 16:46:31 -07001225 atransport* result = nullptr;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001226
Josh Gao1db71af2017-08-17 13:50:51 -07001227 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001228 for (auto& t : transport_list) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001229 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001230 result = t;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001231 break;
1232 }
Dan Albertc7915a32015-05-18 16:46:31 -07001233 }
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001234
Dan Albertc7915a32015-05-18 16:46:31 -07001235 return result;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001236}
1237
Yabin Cuif4b99282015-08-27 12:03:11 -07001238void kick_all_tcp_devices() {
Josh Gao1db71af2017-08-17 13:50:51 -07001239 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001240 for (auto& t : transport_list) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001241 if (t->IsTcpDevice()) {
Yabin Cuid6ab3c22015-08-31 11:50:24 -07001242 // Kicking breaks the read_transport thread of this transport out of any read, then
1243 // the read_transport thread will notify the main thread to make this transport
1244 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cuif4b99282015-08-27 12:03:11 -07001245 // Finally, this transport will be closed and freed in the main thread.
Yabin Cui7f274902016-04-18 11:22:34 -07001246 t->Kick();
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001247 }
Dan Albertc7915a32015-05-18 16:46:31 -07001248 }
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001249}
1250
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001251#endif
1252
Josh Gao1290fbf2016-11-22 14:32:34 -08001253void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1254 unsigned writeable) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001255 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertc7915a32015-05-18 16:46:31 -07001256
Josh Gao1290fbf2016-11-22 14:32:34 -08001257 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cuib5e11412017-03-10 16:01:01 -08001258 init_usb_transport(t, usb);
Josh Gao1290fbf2016-11-22 14:32:34 -08001259 if (serial) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001260 t->serial = serial;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001261 }
Dan Albertc7915a32015-05-18 16:46:31 -07001262
1263 if (devpath) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001264 t->devpath = devpath;
Scott Andersone109d262012-04-20 11:21:14 -07001265 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001266
Josh Gao0cd3ae12016-09-21 12:37:10 -07001267 {
Josh Gao1db71af2017-08-17 13:50:51 -07001268 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001269 pending_list.push_front(t);
1270 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001271
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001272 register_transport(t);
1273}
1274
Dan Albertdcd78a12015-05-18 16:43:57 -07001275// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao1290fbf2016-11-22 14:32:34 -08001276void unregister_usb_transport(usb_handle* usb) {
Josh Gao1db71af2017-08-17 13:50:51 -07001277 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaob800d882018-01-28 20:32:46 -08001278 transport_list.remove_if([usb](atransport* t) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -07001279 auto connection = t->connection();
1280 if (auto usb_connection = dynamic_cast<UsbConnection*>(connection.get())) {
1281 return usb_connection->handle_ == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gaob800d882018-01-28 20:32:46 -08001282 }
1283 return false;
1284 });
Mike Lockwood0927bf92009-08-08 12:37:44 -04001285}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001286
Josh Gao36dadca2017-05-16 15:02:45 -07001287bool check_header(apacket* p, atransport* t) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001288 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cuib5e11412017-03-10 16:01:01 -08001289 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1290 << ", magic = " << p->msg.magic;
Josh Gao36dadca2017-05-16 15:02:45 -07001291 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001292 }
1293
Josh Gao1290fbf2016-11-22 14:32:34 -08001294 if (p->msg.data_length > t->get_max_payload()) {
1295 VLOG(RWX) << "check_header(): " << p->msg.data_length
1296 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao36dadca2017-05-16 15:02:45 -07001297 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001298 }
1299
Josh Gao36dadca2017-05-16 15:02:45 -07001300 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001301}
1302
Josh Gao3bd28792016-10-05 19:02:29 -07001303#if ADB_HOST
Josh Gao2e671202016-08-18 22:00:12 -07001304std::shared_ptr<RSA> atransport::NextKey() {
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001305 if (keys_.empty()) keys_ = adb_auth_get_private_keys();
1306
Josh Gao2e671202016-08-18 22:00:12 -07001307 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001308 keys_.pop_front();
1309 return result;
1310}
Josh Gao3bd28792016-10-05 19:02:29 -07001311#endif