blob: 638940c14c0a06dc275b6efa5a9ee96f3606a42a [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;
105 std::chrono::system_clock::time_point deadline;
106 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{
152 transport, std::chrono::system_clock::now() + ReconnectHandler::kDefaultTimeout,
153 ReconnectHandler::kMaxAttempts});
154 }
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
165 auto deadline = std::chrono::time_point<std::chrono::system_clock>::max();
166 if (!reconnect_queue_.empty()) deadline = reconnect_queue_.front().deadline;
167 reconnect_cv_.wait_until(lock, deadline, [&]() REQUIRES(reconnect_mutex_) {
168 return !running_ ||
169 (!reconnect_queue_.empty() && reconnect_queue_.front().deadline < deadline);
170 });
171
172 if (!running_) return;
173 attempt = reconnect_queue_.front();
174 reconnect_queue_.pop();
175 if (attempt.transport->kicked()) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700176 D("transport %s was kicked. giving up on it.", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700177 remove_transport(attempt.transport);
178 continue;
179 }
180 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700181 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700182
183 if (!attempt.transport->Reconnect()) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700184 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700185 if (attempt.attempts_left == 0) {
186 D("transport %s exceeded the number of retry attempts. giving up on it.",
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700187 attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700188 remove_transport(attempt.transport);
189 continue;
190 }
191
192 std::lock_guard<std::mutex> lock(reconnect_mutex_);
193 reconnect_queue_.emplace(ReconnectAttempt{
194 attempt.transport,
195 std::chrono::system_clock::now() + ReconnectHandler::kDefaultTimeout,
196 attempt.attempts_left - 1});
197 continue;
198 }
199
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700200 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700201 register_transport(attempt.transport);
202 }
203}
204
205static auto& reconnect_handler = *new ReconnectHandler();
206
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700207} // namespace
208
Josh Gaob122b172017-08-16 16:57:01 -0700209TransportId NextTransportId() {
210 static std::atomic<TransportId> next(1);
211 return next++;
212}
213
Josh Gao0bbf69c2018-02-16 13:24:58 -0800214BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
215 : underlying_(std::move(connection)) {}
216
217BlockingConnectionAdapter::~BlockingConnectionAdapter() {
218 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
219 Stop();
220}
221
222void BlockingConnectionAdapter::Start() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700223 std::lock_guard<std::mutex> lock(mutex_);
224 if (started_) {
225 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
226 << "): started multiple times";
227 }
228
Josh Gao0bbf69c2018-02-16 13:24:58 -0800229 read_thread_ = std::thread([this]() {
230 LOG(INFO) << this->transport_name_ << ": read thread spawning";
231 while (true) {
Josh Gao31b5be62018-03-07 16:51:08 -0800232 auto packet = std::make_unique<apacket>();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800233 if (!underlying_->Read(packet.get())) {
234 PLOG(INFO) << this->transport_name_ << ": read failed";
235 break;
236 }
237 read_callback_(this, std::move(packet));
238 }
239 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
240 });
241
242 write_thread_ = std::thread([this]() {
243 LOG(INFO) << this->transport_name_ << ": write thread spawning";
244 while (true) {
245 std::unique_lock<std::mutex> lock(mutex_);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700246 ScopedAssumeLocked assume_locked(mutex_);
Josh Gaoc251ec52018-04-03 12:55:18 -0700247 cv_.wait(lock, [this]() REQUIRES(mutex_) {
248 return this->stopped_ || !this->write_queue_.empty();
249 });
250
Josh Gao0bbf69c2018-02-16 13:24:58 -0800251 if (this->stopped_) {
252 return;
253 }
254
255 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
256 this->write_queue_.pop_front();
257 lock.unlock();
258
259 if (!this->underlying_->Write(packet.get())) {
260 break;
261 }
262 }
263 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
264 });
Josh Gaoc251ec52018-04-03 12:55:18 -0700265
266 started_ = true;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800267}
268
269void BlockingConnectionAdapter::Stop() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700270 {
271 std::lock_guard<std::mutex> lock(mutex_);
272 if (!started_) {
273 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
274 return;
275 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800276
Josh Gaoc251ec52018-04-03 12:55:18 -0700277 if (stopped_) {
278 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
279 << "): already stopped";
280 return;
281 }
282
283 stopped_ = true;
284 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800285
286 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
287
288 this->underlying_->Close();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800289 this->cv_.notify_one();
Josh Gaoc251ec52018-04-03 12:55:18 -0700290
291 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
292 std::thread read_thread;
293 std::thread write_thread;
294
295 {
296 std::lock_guard<std::mutex> lock(mutex_);
297 read_thread = std::move(read_thread_);
298 write_thread = std::move(write_thread_);
299 }
300
301 read_thread.join();
302 write_thread.join();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800303
304 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
305 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
306}
307
308bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
309 {
Josh Gaoc251ec52018-04-03 12:55:18 -0700310 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800311 write_queue_.emplace_back(std::move(packet));
312 }
313
314 cv_.notify_one();
315 return true;
316}
317
Josh Gaob800d882018-01-28 20:32:46 -0800318bool FdConnection::Read(apacket* packet) {
319 if (!ReadFdExactly(fd_.get(), &packet->msg, sizeof(amessage))) {
320 D("remote local: read terminated (message)");
321 return false;
322 }
323
Josh Gaof571fcb2018-02-05 18:49:10 -0800324 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gao5caaebd2018-02-02 14:38:04 -0800325 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
326 return false;
327 }
328
Josh Gaof571fcb2018-02-05 18:49:10 -0800329 packet->payload.resize(packet->msg.data_length);
330
331 if (!ReadFdExactly(fd_.get(), &packet->payload[0], packet->payload.size())) {
Josh Gaob800d882018-01-28 20:32:46 -0800332 D("remote local: terminated (data)");
333 return false;
334 }
335
336 return true;
337}
338
339bool FdConnection::Write(apacket* packet) {
Josh Gaof571fcb2018-02-05 18:49:10 -0800340 if (!WriteFdExactly(fd_.get(), &packet->msg, sizeof(packet->msg))) {
Josh Gaob800d882018-01-28 20:32:46 -0800341 D("remote local: write terminated");
342 return false;
343 }
344
Josh Gaof571fcb2018-02-05 18:49:10 -0800345 if (packet->msg.data_length) {
346 if (!WriteFdExactly(fd_.get(), &packet->payload[0], packet->msg.data_length)) {
347 D("remote local: write terminated");
348 return false;
349 }
350 }
351
Josh Gaob800d882018-01-28 20:32:46 -0800352 return true;
353}
354
355void FdConnection::Close() {
356 adb_shutdown(fd_.get());
357 fd_.reset();
358}
359
Yabin Cuiaed3c612015-09-22 15:52:57 -0700360static std::string dump_packet(const char* name, const char* func, apacket* p) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800361 unsigned command = p->msg.command;
362 int len = p->msg.data_length;
363 char cmd[9];
364 char arg0[12], arg1[12];
365 int n;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100366
367 for (n = 0; n < 4; n++) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800368 int b = (command >> (n * 8)) & 255;
369 if (b < 32 || b >= 127) break;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100370 cmd[n] = (char)b;
371 }
372 if (n == 4) {
373 cmd[4] = 0;
374 } else {
375 /* There is some non-ASCII name in the command, so dump
376 * the hexadecimal value instead */
377 snprintf(cmd, sizeof cmd, "%08x", command);
378 }
379
380 if (p->msg.arg0 < 256U)
381 snprintf(arg0, sizeof arg0, "%d", p->msg.arg0);
382 else
383 snprintf(arg0, sizeof arg0, "0x%x", p->msg.arg0);
384
385 if (p->msg.arg1 < 256U)
386 snprintf(arg1, sizeof arg1, "%d", p->msg.arg1);
387 else
388 snprintf(arg1, sizeof arg1, "0x%x", p->msg.arg1);
389
Josh Gao1290fbf2016-11-22 14:32:34 -0800390 std::string result = android::base::StringPrintf("%s: %s: [%s] arg0=%s arg1=%s (len=%d) ", name,
391 func, cmd, arg0, arg1, len);
Josh Gaof571fcb2018-02-05 18:49:10 -0800392 result += dump_hex(p->payload.data(), p->payload.size());
Yabin Cuiaed3c612015-09-22 15:52:57 -0700393 return result;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100394}
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100395
Josh Gao06d61d42016-10-06 13:31:44 -0700396void send_packet(apacket* p, atransport* t) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800397 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayde471942017-12-07 11:40:00 -0800398 // compute a checksum for connection/auth packets for compatibility reasons
399 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
400 p->msg.data_check = 0;
401 } else {
402 p->msg.data_check = calculate_apacket_checksum(p);
403 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800404
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700405 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800406
Yi Kongaed415c2018-07-13 18:15:16 -0700407 if (t == nullptr) {
Josh Gao06d61d42016-10-06 13:31:44 -0700408 fatal("Transport is null");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800409 }
410
Josh Gao0bbf69c2018-02-16 13:24:58 -0800411 if (t->Write(p) != 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700412 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800413 t->Kick();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800414 }
415}
416
Yabin Cuif4b99282015-08-27 12:03:11 -0700417void kick_transport(atransport* t) {
Josh Gao1db71af2017-08-17 13:50:51 -0700418 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui1f4ec192016-04-05 13:50:44 -0700419 // As kick_transport() can be called from threads without guarantee that t is valid,
420 // check if the transport is in transport_list first.
Josh Gaob122b172017-08-16 16:57:01 -0700421 //
422 // TODO(jmgao): WTF? Is this actually true?
Yabin Cui1f4ec192016-04-05 13:50:44 -0700423 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Yabin Cui7f274902016-04-18 11:22:34 -0700424 t->Kick();
Yabin Cui1f4ec192016-04-05 13:50:44 -0700425 }
Yabin Cuif4b99282015-08-27 12:03:11 -0700426}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800427
428static int transport_registration_send = -1;
429static int transport_registration_recv = -1;
Josh Gao71f775a2018-05-14 11:14:33 -0700430static fdevent* transport_registration_fde;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800431
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800432#if ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800433
434/* this adds support required by the 'track-devices' service.
435 * this is used to send the content of "list_transport" to any
436 * number of client connections that want it through a single
437 * live TCP connection
438 */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800439struct device_tracker {
Josh Gao1290fbf2016-11-22 14:32:34 -0800440 asocket socket;
Josh Gaoe0361d12018-02-12 17:24:00 -0800441 bool update_needed = false;
442 bool long_output = false;
443 device_tracker* next = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800444};
445
446/* linked list of all device trackers */
Josh Gao1290fbf2016-11-22 14:32:34 -0800447static device_tracker* device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800448
Josh Gao1290fbf2016-11-22 14:32:34 -0800449static void device_tracker_remove(device_tracker* tracker) {
450 device_tracker** pnode = &device_tracker_list;
451 device_tracker* node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800452
Josh Gao1db71af2017-08-17 13:50:51 -0700453 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800454 while (node) {
455 if (node == tracker) {
456 *pnode = node->next;
457 break;
458 }
459 pnode = &node->next;
Josh Gao1290fbf2016-11-22 14:32:34 -0800460 node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800461 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800462}
463
Josh Gao1290fbf2016-11-22 14:32:34 -0800464static void device_tracker_close(asocket* socket) {
465 device_tracker* tracker = (device_tracker*)socket;
466 asocket* peer = socket->peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800467
Josh Gao1290fbf2016-11-22 14:32:34 -0800468 D("device tracker %p removed", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800469 if (peer) {
Yi Kongaed415c2018-07-13 18:15:16 -0700470 peer->peer = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800471 peer->close(peer);
472 }
473 device_tracker_remove(tracker);
Josh Gaoe0361d12018-02-12 17:24:00 -0800474 delete tracker;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800475}
476
Josh Gao1ce99572018-03-07 16:52:28 -0800477static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800478 /* you can't read from a device tracker, close immediately */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800479 device_tracker_close(socket);
480 return -1;
481}
482
Elliott Hughese67f1f82015-04-30 17:32:03 -0700483static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700484 asocket* peer = tracker->socket.peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800485
Josh Gao1ce99572018-03-07 16:52:28 -0800486 apacket::payload_type data;
Josh Gao27cb7dc2018-02-01 13:17:50 -0800487 data.resize(4 + string.size());
488 char buf[5];
489 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
490 memcpy(&data[0], buf, 4);
491 memcpy(&data[4], string.data(), string.size());
492 return peer->enqueue(peer, std::move(data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800493}
494
Elliott Hughese67f1f82015-04-30 17:32:03 -0700495static void device_tracker_ready(asocket* socket) {
496 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800497
Elliott Hughese67f1f82015-04-30 17:32:03 -0700498 // We want to send the device list when the tracker connects
499 // for the first time, even if no update occurred.
Josh Gaob0c18022017-08-14 18:57:54 -0700500 if (tracker->update_needed) {
501 tracker->update_needed = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800502
Josh Gaob0c18022017-08-14 18:57:54 -0700503 std::string transports = list_transports(tracker->long_output);
Elliott Hughese67f1f82015-04-30 17:32:03 -0700504 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800505 }
506}
507
Josh Gaob0c18022017-08-14 18:57:54 -0700508asocket* create_device_tracker(bool long_output) {
Josh Gaoe0361d12018-02-12 17:24:00 -0800509 device_tracker* tracker = new device_tracker();
Elliott Hughesdc3b4592015-04-21 19:39:52 -0700510 if (tracker == nullptr) fatal("cannot allocate device tracker");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800511
Josh Gao1290fbf2016-11-22 14:32:34 -0800512 D("device tracker %p created", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800513
514 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao1290fbf2016-11-22 14:32:34 -0800515 tracker->socket.ready = device_tracker_ready;
516 tracker->socket.close = device_tracker_close;
Josh Gaob0c18022017-08-14 18:57:54 -0700517 tracker->update_needed = true;
518 tracker->long_output = long_output;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800519
Josh Gao1290fbf2016-11-22 14:32:34 -0800520 tracker->next = device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800521 device_tracker_list = tracker;
522
523 return &tracker->socket;
524}
525
Josh Gaofd713e52017-05-03 22:37:10 -0700526// Check if all of the USB transports are connected.
527bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gao1db71af2017-08-17 13:50:51 -0700528 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaofd713e52017-05-03 22:37:10 -0700529 for (const auto& t : transport_list) {
530 if (!fn(t)) {
531 return false;
532 }
533 }
534 for (const auto& t : pending_list) {
535 if (!fn(t)) {
536 return false;
537 }
538 }
539 return true;
540}
541
Elliott Hughese67f1f82015-04-30 17:32:03 -0700542// Call this function each time the transport list has changed.
543void update_transports() {
Josh Gaofd713e52017-05-03 22:37:10 -0700544 update_transport_status();
545
546 // Notify `adb track-devices` clients.
Elliott Hughese67f1f82015-04-30 17:32:03 -0700547 std::string transports = list_transports(false);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800548
Elliott Hughese67f1f82015-04-30 17:32:03 -0700549 device_tracker* tracker = device_tracker_list;
550 while (tracker != nullptr) {
551 device_tracker* next = tracker->next;
552 // This may destroy the tracker if the connection is closed.
553 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800554 tracker = next;
555 }
556}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700557
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800558#else
Elliott Hughese67f1f82015-04-30 17:32:03 -0700559
560void update_transports() {
561 // Nothing to do on the device side.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800562}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700563
Josh Gao1290fbf2016-11-22 14:32:34 -0800564#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800565
Josh Gao1290fbf2016-11-22 14:32:34 -0800566struct tmsg {
567 atransport* transport;
568 int action;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800569};
570
Josh Gao1290fbf2016-11-22 14:32:34 -0800571static int transport_read_action(int fd, struct tmsg* m) {
572 char* p = (char*)m;
573 int len = sizeof(*m);
574 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800575
Josh Gao1290fbf2016-11-22 14:32:34 -0800576 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800577 r = adb_read(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800578 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800579 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800580 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800581 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700582 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800583 return -1;
584 }
585 }
586 return 0;
587}
588
Josh Gao1290fbf2016-11-22 14:32:34 -0800589static int transport_write_action(int fd, struct tmsg* m) {
590 char* p = (char*)m;
591 int len = sizeof(*m);
592 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800593
Josh Gao1290fbf2016-11-22 14:32:34 -0800594 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800595 r = adb_write(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800596 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800597 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800598 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800599 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700600 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800601 return -1;
602 }
603 }
604 return 0;
605}
606
Josh Gao0bbf69c2018-02-16 13:24:58 -0800607static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800608 tmsg m;
Josh Gao1290fbf2016-11-22 14:32:34 -0800609 atransport* t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800610
Josh Gao1290fbf2016-11-22 14:32:34 -0800611 if (!(ev & FDE_READ)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800612 return;
613 }
614
Josh Gao1290fbf2016-11-22 14:32:34 -0800615 if (transport_read_action(_fd, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800616 fatal_errno("cannot read transport registration socket");
617 }
618
619 t = m.transport;
620
Dan Albert1792c232015-05-18 13:06:53 -0700621 if (m.action == 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700622 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800623
Josh Gao0cd3ae12016-09-21 12:37:10 -0700624 {
Josh Gao1db71af2017-08-17 13:50:51 -0700625 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700626 transport_list.remove(t);
627 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800628
Dan Albertc7915a32015-05-18 16:46:31 -0700629 delete t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800630
631 update_transports();
632 return;
633 }
634
Mike Lockwood0927bf92009-08-08 12:37:44 -0400635 /* don't create transport threads for inaccessible devices */
Yabin Cuib5e11412017-03-10 16:01:01 -0800636 if (t->GetConnectionState() != kCsNoPerm) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700637 // The connection gets a reference to the atransport. It will release it
638 // upon a read/write error.
639 t->ref_count++;
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700640 t->connection()->SetTransportName(t->serial_name());
641 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao0bbf69c2018-02-16 13:24:58 -0800642 if (!check_header(p.get(), t)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700643 D("%s: remote read: bad header", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800644 return false;
645 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800646
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700647 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "from remote", p.get());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800648 apacket* packet = p.release();
Mike Lockwood0927bf92009-08-08 12:37:44 -0400649
Josh Gao0bbf69c2018-02-16 13:24:58 -0800650 // TODO: Does this need to run on the main thread?
651 fdevent_run_on_main_thread([packet, t]() { handle_packet(packet, t); });
652 return true;
653 });
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700654 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700655 D("%s: connection terminated: %s", t->serial.c_str(), error.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800656 fdevent_run_on_main_thread([t]() {
657 handle_offline(t);
658 transport_unref(t);
659 });
660 });
Mike Lockwood0927bf92009-08-08 12:37:44 -0400661
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700662 t->connection()->Start();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800663#if ADB_HOST
664 send_connect(t);
665#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800666 }
667
Josh Gao0cd3ae12016-09-21 12:37:10 -0700668 {
Josh Gao1db71af2017-08-17 13:50:51 -0700669 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700670 auto it = std::find(pending_list.begin(), pending_list.end(), t);
671 if (it != pending_list.end()) {
672 pending_list.remove(t);
673 transport_list.push_front(t);
674 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700675 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800676
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800677 update_transports();
678}
679
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700680void init_reconnect_handler(void) {
681 reconnect_handler.Start();
682}
683
Josh Gao1290fbf2016-11-22 14:32:34 -0800684void init_transport_registration(void) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800685 int s[2];
686
Josh Gao1290fbf2016-11-22 14:32:34 -0800687 if (adb_socketpair(s)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800688 fatal_errno("cannot open transport registration socketpair");
689 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700690 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800691
692 transport_registration_send = s[0];
693 transport_registration_recv = s[1];
694
Josh Gao71f775a2018-05-14 11:14:33 -0700695 transport_registration_fde =
Yi Kongaed415c2018-07-13 18:15:16 -0700696 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao71f775a2018-05-14 11:14:33 -0700697 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao01b7bc42017-05-09 13:43:35 -0700698}
699
700void kick_all_transports() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700701 reconnect_handler.Stop();
Josh Gao01b7bc42017-05-09 13:43:35 -0700702 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gao1db71af2017-08-17 13:50:51 -0700703 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao01b7bc42017-05-09 13:43:35 -0700704 for (auto t : transport_list) {
705 t->Kick();
706 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800707}
708
709/* the fdevent select pump is single threaded */
Josh Gao1290fbf2016-11-22 14:32:34 -0800710static void register_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800711 tmsg m;
712 m.transport = transport;
713 m.action = 1;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700714 D("transport: %s registered", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800715 if (transport_write_action(transport_registration_send, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800716 fatal_errno("cannot write transport registration socket\n");
717 }
718}
719
Josh Gao1290fbf2016-11-22 14:32:34 -0800720static void remove_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800721 tmsg m;
722 m.transport = transport;
723 m.action = 0;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700724 D("transport: %s removed", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800725 if (transport_write_action(transport_registration_send, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800726 fatal_errno("cannot write transport registration socket\n");
727 }
728}
729
Yabin Cuif4b99282015-08-27 12:03:11 -0700730static void transport_unref(atransport* t) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700731 check_main_thread();
Yabin Cuif4b99282015-08-27 12:03:11 -0700732 CHECK(t != nullptr);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700733
Josh Gaoe48ecce2017-09-13 13:40:57 -0700734 std::lock_guard<std::recursive_mutex> lock(transport_lock);
735 CHECK_GT(t->ref_count, 0u);
736 t->ref_count--;
737 if (t->ref_count == 0) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700738 t->connection()->Stop();
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700739 if (t->IsTcpDevice() && !t->kicked()) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700740 D("transport: %s unref (attempting reconnection) %d", t->serial.c_str(), t->kicked());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700741 reconnect_handler.TrackTransport(t);
742 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700743 D("transport: %s unref (kicking and closing)", t->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700744 remove_transport(t);
745 }
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100746 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700747 D("transport: %s unref (count=%zu)", t->serial.c_str(), t->ref_count);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -0400748 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800749}
750
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700751static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao1290fbf2016-11-22 14:32:34 -0800752 bool sanitize_qual) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700753 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
754 return qual.empty();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700755
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700756 if (qual.empty()) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700757
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700758 const char* ptr = to_test.c_str();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700759 if (prefix) {
760 while (*prefix) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700761 if (*prefix++ != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700762 }
763 }
764
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700765 for (char ch : qual) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800766 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700767 if (ch != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700768 }
769
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700770 /* Everything matched so far. Return true if *ptr is a NUL. */
771 return !*ptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700772}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800773
Josh Gaob122b172017-08-16 16:57:01 -0700774atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
775 bool* is_ambiguous, std::string* error_out,
776 bool accept_any_state) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700777 atransport* result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800778
Josh Gaob122b172017-08-16 16:57:01 -0700779 if (transport_id != 0) {
780 *error_out =
781 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
782 } else if (serial) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700783 *error_out = android::base::StringPrintf("device '%s' not found", serial);
784 } else if (type == kTransportLocal) {
785 *error_out = "no emulators found";
786 } else if (type == kTransportAny) {
787 *error_out = "no devices/emulators found";
788 } else {
789 *error_out = "no devices found";
790 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800791
Josh Gao1db71af2017-08-17 13:50:51 -0700792 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes8d28e192015-10-07 14:55:10 -0700793 for (const auto& t : transport_list) {
Yabin Cuib5e11412017-03-10 16:01:01 -0800794 if (t->GetConnectionState() == kCsNoPerm) {
David Purselld2acbd12015-12-02 15:14:31 -0800795 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwood37d31112009-08-08 13:53:16 -0400796 continue;
797 }
Mike Lockwood0927bf92009-08-08 12:37:44 -0400798
Josh Gaob122b172017-08-16 16:57:01 -0700799 if (transport_id) {
800 if (t->id == transport_id) {
801 result = t;
802 break;
803 }
804 } else if (serial) {
David Pursell3f902aa2016-03-01 08:58:26 -0800805 if (t->MatchesTarget(serial)) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700806 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700807 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700808 if (is_ambiguous) *is_ambiguous = true;
809 result = nullptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700810 break;
811 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800812 result = t;
Scott Andersone109d262012-04-20 11:21:14 -0700813 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800814 } else {
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700815 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800816 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700817 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700818 if (is_ambiguous) *is_ambiguous = true;
819 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800820 break;
821 }
822 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700823 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800824 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700825 *error_out = "more than one emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700826 if (is_ambiguous) *is_ambiguous = true;
827 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800828 break;
829 }
830 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700831 } else if (type == kTransportAny) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800832 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700833 *error_out = "more than one device/emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700834 if (is_ambiguous) *is_ambiguous = true;
835 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800836 break;
837 }
838 result = t;
839 }
840 }
841 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700842 lock.unlock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800843
Josh Gao704494b2018-05-04 16:04:49 -0700844 if (result && !accept_any_state) {
845 // The caller requires an active transport.
846 // Make sure that we're actually connected.
847 ConnectionState state = result->GetConnectionState();
848 switch (state) {
849 case kCsConnecting:
850 *error_out = "device still connecting";
851 result = nullptr;
852 break;
Benoit Goby77e8e582013-01-15 12:36:47 -0800853
Josh Gao704494b2018-05-04 16:04:49 -0700854 case kCsAuthorizing:
855 *error_out = "device still authorizing";
856 result = nullptr;
857 break;
858
859 case kCsUnauthorized: {
860 *error_out = "device unauthorized.\n";
861 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
862 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
863 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
864 *error_out += "\n";
865 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
866 *error_out += "Otherwise check for a confirmation dialog on your device.";
867 result = nullptr;
868 break;
869 }
870
871 case kCsOffline:
872 *error_out = "device offline";
873 result = nullptr;
874 break;
875
876 default:
877 break;
878 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800879 }
880
881 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700882 *error_out = "success";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800883 }
884
885 return result;
886}
887
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700888bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
889 std::unique_lock<std::mutex> lock(mutex_);
890 ScopedAssumeLocked assume_locked(mutex_);
891 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
892 return connection_established_ready_;
893 }) && connection_established_;
894}
895
896void ConnectionWaitable::SetConnectionEstablished(bool success) {
897 {
898 std::lock_guard<std::mutex> lock(mutex_);
899 if (connection_established_ready_) return;
900 connection_established_ready_ = true;
901 connection_established_ = success;
902 D("connection established with %d", success);
903 }
904 cv_.notify_one();
905}
906
907atransport::~atransport() {
908 // If the connection callback had not been run before, run it now.
909 SetConnectionEstablished(false);
910}
911
Yabin Cuib5e11412017-03-10 16:01:01 -0800912int atransport::Write(apacket* p) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700913 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cuib5e11412017-03-10 16:01:01 -0800914}
915
Yabin Cui7f274902016-04-18 11:22:34 -0700916void atransport::Kick() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700917 if (!kicked_.exchange(true)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700918 D("kicking transport %p %s", this, this->serial.c_str());
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700919 this->connection()->Stop();
Yabin Cui7f274902016-04-18 11:22:34 -0700920 }
921}
922
Yabin Cuib5e11412017-03-10 16:01:01 -0800923ConnectionState atransport::GetConnectionState() const {
924 return connection_state_;
925}
926
927void atransport::SetConnectionState(ConnectionState state) {
928 check_main_thread();
929 connection_state_ = state;
930}
931
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700932void atransport::SetConnection(std::unique_ptr<Connection> connection) {
933 std::lock_guard<std::mutex> lock(mutex_);
934 connection_ = std::shared_ptr<Connection>(std::move(connection));
935}
936
Josh Gaoffbd3362018-02-28 14:44:23 -0800937std::string atransport::connection_state_name() const {
Yabin Cuib5e11412017-03-10 16:01:01 -0800938 ConnectionState state = GetConnectionState();
939 switch (state) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800940 case kCsOffline:
941 return "offline";
942 case kCsBootloader:
943 return "bootloader";
944 case kCsDevice:
945 return "device";
946 case kCsHost:
947 return "host";
948 case kCsRecovery:
949 return "recovery";
950 case kCsNoPerm:
951 return UsbNoPermissionsShortHelpText();
952 case kCsSideload:
953 return "sideload";
954 case kCsUnauthorized:
955 return "unauthorized";
Josh Gao704494b2018-05-04 16:04:49 -0700956 case kCsAuthorizing:
957 return "authorizing";
958 case kCsConnecting:
959 return "connecting";
Josh Gao1290fbf2016-11-22 14:32:34 -0800960 default:
961 return "unknown";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800962 }
963}
964
Tamas Berghammer3d2904c2015-07-13 19:12:28 +0100965void atransport::update_version(int version, size_t payload) {
966 protocol_version = std::min(version, A_VERSION);
967 max_payload = std::min(payload, MAX_PAYLOAD);
968}
969
970int atransport::get_protocol_version() const {
971 return protocol_version;
972}
973
974size_t atransport::get_max_payload() const {
975 return max_payload;
976}
977
David Pursell4e2fd362015-09-22 10:43:08 -0700978namespace {
David Pursell0955c662015-08-31 10:42:13 -0700979
David Pursell4e2fd362015-09-22 10:43:08 -0700980constexpr char kFeatureStringDelimiter = ',';
981
982} // namespace
Dan Albert1792c232015-05-18 13:06:53 -0700983
984const FeatureSet& supported_features() {
David Pursell4e2fd362015-09-22 10:43:08 -0700985 // Local static allocation to avoid global non-POD variables.
986 static const FeatureSet* features = new FeatureSet{
Josh Gao1290fbf2016-11-22 14:32:34 -0800987 kFeatureShell2, kFeatureCmd, kFeatureStat2,
David Pursellbbe3d212015-09-25 08:37:13 -0700988 // Increment ADB_SERVER_VERSION whenever the feature list changes to
989 // make sure that the adb client and server features stay in sync
990 // (http://b/24370690).
David Pursell4e2fd362015-09-22 10:43:08 -0700991 };
992
993 return *features;
994}
995
996std::string FeatureSetToString(const FeatureSet& features) {
997 return android::base::Join(features, kFeatureStringDelimiter);
998}
999
1000FeatureSet StringToFeatureSet(const std::string& features_string) {
David Purselld2b588e2015-09-25 13:04:21 -07001001 if (features_string.empty()) {
1002 return FeatureSet();
1003 }
1004
Josh Gao1290fbf2016-11-22 14:32:34 -08001005 auto names = android::base::Split(features_string, {kFeatureStringDelimiter});
David Pursell4e2fd362015-09-22 10:43:08 -07001006 return FeatureSet(names.begin(), names.end());
Dan Albert1792c232015-05-18 13:06:53 -07001007}
1008
David Pursell70ef7b42015-09-30 13:35:42 -07001009bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001010 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell70ef7b42015-09-30 13:35:42 -07001011}
1012
Dan Albert1792c232015-05-18 13:06:53 -07001013bool atransport::has_feature(const std::string& feature) const {
1014 return features_.count(feature) > 0;
1015}
1016
David Pursell4e2fd362015-09-22 10:43:08 -07001017void atransport::SetFeatures(const std::string& features_string) {
1018 features_ = StringToFeatureSet(features_string);
Dan Albert1792c232015-05-18 13:06:53 -07001019}
1020
Yabin Cuib3298242015-08-28 15:09:44 -07001021void atransport::AddDisconnect(adisconnect* disconnect) {
1022 disconnects_.push_back(disconnect);
1023}
1024
1025void atransport::RemoveDisconnect(adisconnect* disconnect) {
1026 disconnects_.remove(disconnect);
1027}
1028
1029void atransport::RunDisconnects() {
Elliott Hughes65fe2512015-10-07 15:59:35 -07001030 for (const auto& disconnect : disconnects_) {
Yabin Cuib3298242015-08-28 15:09:44 -07001031 disconnect->func(disconnect->opaque, this);
1032 }
1033 disconnects_.clear();
1034}
1035
David Pursell3f902aa2016-03-01 08:58:26 -08001036bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001037 if (!serial.empty()) {
David Pursell3f902aa2016-03-01 08:58:26 -08001038 if (target == serial) {
1039 return true;
1040 } else if (type == kTransportLocal) {
1041 // Local transports can match [tcp:|udp:]<hostname>[:port].
1042 const char* local_target_ptr = target.c_str();
1043
1044 // For fastboot compatibility, ignore protocol prefixes.
1045 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao1290fbf2016-11-22 14:32:34 -08001046 android::base::StartsWith(target, "udp:")) {
David Pursell3f902aa2016-03-01 08:58:26 -08001047 local_target_ptr += 4;
1048 }
1049
1050 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1051 std::string serial_host, error;
1052 int serial_port = -1;
Josh Gao1290fbf2016-11-22 14:32:34 -08001053 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursell3f902aa2016-03-01 08:58:26 -08001054 // |target| may omit the port to default to ours.
1055 std::string target_host;
1056 int target_port = serial_port;
1057 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1058 nullptr, &error) &&
Josh Gao1290fbf2016-11-22 14:32:34 -08001059 serial_host == target_host && serial_port == target_port) {
David Pursell3f902aa2016-03-01 08:58:26 -08001060 return true;
1061 }
1062 }
1063 }
1064 }
1065
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001066 return (target == devpath) || qual_match(target, "product:", product, false) ||
1067 qual_match(target, "model:", model, true) ||
1068 qual_match(target, "device:", device, false);
David Pursell3f902aa2016-03-01 08:58:26 -08001069}
1070
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001071void atransport::SetConnectionEstablished(bool success) {
1072 connection_waitable_->SetConnectionEstablished(success);
1073}
1074
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001075bool atransport::Reconnect() {
1076 return reconnect_(this);
1077}
1078
Elliott Hughese67f1f82015-04-30 17:32:03 -07001079#if ADB_HOST
1080
Josh Gaob122b172017-08-16 16:57:01 -07001081// We use newline as our delimiter, make sure to never output it.
1082static std::string sanitize(std::string str, bool alphanumeric) {
1083 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1084 : [](const char c) { return c == '\n'; };
1085 std::replace_if(str.begin(), str.end(), pred, '_');
1086 return str;
1087}
1088
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001089static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob122b172017-08-16 16:57:01 -07001090 bool alphanumeric) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001091 if (value.empty()) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001092 return;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001093 }
1094
Elliott Hughese67f1f82015-04-30 17:32:03 -07001095 *result += ' ';
1096 *result += key;
Josh Gaob122b172017-08-16 16:57:01 -07001097 *result += sanitize(value, alphanumeric);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001098}
1099
Josh Gao1290fbf2016-11-22 14:32:34 -08001100static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001101 std::string serial = t->serial;
1102 if (serial.empty()) {
Dan Albertd99d9022015-05-06 16:48:52 -07001103 serial = "(no serial number)";
Elliott Hughese67f1f82015-04-30 17:32:03 -07001104 }
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001105
1106 if (!long_listing) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001107 *result += serial;
1108 *result += '\t';
1109 *result += t->connection_state_name();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001110 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001111 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1112 t->connection_state_name().c_str());
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001113
Elliott Hughese67f1f82015-04-30 17:32:03 -07001114 append_transport_info(result, "", t->devpath, false);
1115 append_transport_info(result, "product:", t->product, false);
1116 append_transport_info(result, "model:", t->model, true);
1117 append_transport_info(result, "device:", t->device, false);
Josh Gaob122b172017-08-16 16:57:01 -07001118
1119 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1120 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1121 *result += " transport_id:";
1122 *result += std::to_string(t->id);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001123 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001124 *result += '\n';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001125}
1126
Elliott Hughese67f1f82015-04-30 17:32:03 -07001127std::string list_transports(bool long_listing) {
Josh Gao1db71af2017-08-17 13:50:51 -07001128 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov04398a92017-12-17 10:56:07 +00001129
1130 auto sorted_transport_list = transport_list;
1131 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1132 if (x->type != y->type) {
1133 return x->type < y->type;
1134 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001135 return x->serial < y->serial;
Artem Iglikov04398a92017-12-17 10:56:07 +00001136 });
1137
1138 std::string result;
1139 for (const auto& t : sorted_transport_list) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001140 append_transport(t, &result, long_listing);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001141 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001142 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001143}
1144
Josh Gao22d2b3e2016-10-27 14:01:08 -07001145void close_usb_devices(std::function<bool(const atransport*)> predicate) {
Josh Gao1db71af2017-08-17 13:50:51 -07001146 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao22d2b3e2016-10-27 14:01:08 -07001147 for (auto& t : transport_list) {
1148 if (predicate(t)) {
1149 t->Kick();
1150 }
1151 }
1152}
1153
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001154/* hack for osx */
Dan Albertc7915a32015-05-18 16:46:31 -07001155void close_usb_devices() {
Josh Gao22d2b3e2016-10-27 14:01:08 -07001156 close_usb_devices([](const atransport*) { return true; });
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001157}
Josh Gao1290fbf2016-11-22 14:32:34 -08001158#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001159
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001160int register_socket_transport(int s, const char* serial, int port, int local,
1161 atransport::ReconnectCallback reconnect) {
1162 atransport* t = new atransport(std::move(reconnect), kCsOffline);
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +01001163
1164 if (!serial) {
Dan Albertc7915a32015-05-18 16:46:31 -07001165 char buf[32];
1166 snprintf(buf, sizeof(buf), "T-%p", t);
1167 serial = buf;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +01001168 }
Dan Albertc7915a32015-05-18 16:46:31 -07001169
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001170 D("transport: %s init'ing for socket %d, on port %d", serial, s, port);
Benoit Goby1c45ee92013-03-29 18:22:36 -07001171 if (init_socket_transport(t, s, port, local) < 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001172 delete t;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001173 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001174 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001175
Josh Gao1db71af2017-08-17 13:50:51 -07001176 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes65fe2512015-10-07 15:59:35 -07001177 for (const auto& transport : pending_list) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001178 if (strcmp(serial, transport->serial.c_str()) == 0) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001179 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001180 << " is already in pending_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001181 delete t;
Luis Hector Chavez5d395852018-04-17 14:09:21 -07001182 return -EALREADY;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001183 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001184 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001185
Elliott Hughes65fe2512015-10-07 15:59:35 -07001186 for (const auto& transport : transport_list) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001187 if (strcmp(serial, transport->serial.c_str()) == 0) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001188 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001189 << " is already in transport_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001190 delete t;
Luis Hector Chavez5d395852018-04-17 14:09:21 -07001191 return -EALREADY;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001192 }
1193 }
1194
Dan Albertc7915a32015-05-18 16:46:31 -07001195 pending_list.push_front(t);
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001196 t->serial = serial;
Josh Gao0cd3ae12016-09-21 12:37:10 -07001197
1198 lock.unlock();
Benoit Goby1c45ee92013-03-29 18:22:36 -07001199
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001200 auto waitable = t->connection_waitable();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001201 register_transport(t);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001202
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001203 if (local == 1) {
1204 // Do not wait for emulator transports.
1205 return 0;
1206 }
1207
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001208 return waitable->WaitForConnection(std::chrono::seconds(10)) ? 0 : -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001209}
1210
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001211#if ADB_HOST
Josh Gao1290fbf2016-11-22 14:32:34 -08001212atransport* find_transport(const char* serial) {
Dan Albertc7915a32015-05-18 16:46:31 -07001213 atransport* result = nullptr;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001214
Josh Gao1db71af2017-08-17 13:50:51 -07001215 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001216 for (auto& t : transport_list) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001217 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001218 result = t;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001219 break;
1220 }
Dan Albertc7915a32015-05-18 16:46:31 -07001221 }
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001222
Dan Albertc7915a32015-05-18 16:46:31 -07001223 return result;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001224}
1225
Yabin Cuif4b99282015-08-27 12:03:11 -07001226void kick_all_tcp_devices() {
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) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001229 if (t->IsTcpDevice()) {
Yabin Cuid6ab3c22015-08-31 11:50:24 -07001230 // Kicking breaks the read_transport thread of this transport out of any read, then
1231 // the read_transport thread will notify the main thread to make this transport
1232 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cuif4b99282015-08-27 12:03:11 -07001233 // Finally, this transport will be closed and freed in the main thread.
Yabin Cui7f274902016-04-18 11:22:34 -07001234 t->Kick();
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001235 }
Dan Albertc7915a32015-05-18 16:46:31 -07001236 }
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001237}
1238
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001239#endif
1240
Josh Gao1290fbf2016-11-22 14:32:34 -08001241void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1242 unsigned writeable) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001243 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertc7915a32015-05-18 16:46:31 -07001244
Josh Gao1290fbf2016-11-22 14:32:34 -08001245 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cuib5e11412017-03-10 16:01:01 -08001246 init_usb_transport(t, usb);
Josh Gao1290fbf2016-11-22 14:32:34 -08001247 if (serial) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001248 t->serial = serial;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001249 }
Dan Albertc7915a32015-05-18 16:46:31 -07001250
1251 if (devpath) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001252 t->devpath = devpath;
Scott Andersone109d262012-04-20 11:21:14 -07001253 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001254
Josh Gao0cd3ae12016-09-21 12:37:10 -07001255 {
Josh Gao1db71af2017-08-17 13:50:51 -07001256 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001257 pending_list.push_front(t);
1258 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001259
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001260 register_transport(t);
1261}
1262
Dan Albertdcd78a12015-05-18 16:43:57 -07001263// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao1290fbf2016-11-22 14:32:34 -08001264void unregister_usb_transport(usb_handle* usb) {
Josh Gao1db71af2017-08-17 13:50:51 -07001265 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaob800d882018-01-28 20:32:46 -08001266 transport_list.remove_if([usb](atransport* t) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -07001267 auto connection = t->connection();
1268 if (auto usb_connection = dynamic_cast<UsbConnection*>(connection.get())) {
1269 return usb_connection->handle_ == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gaob800d882018-01-28 20:32:46 -08001270 }
1271 return false;
1272 });
Mike Lockwood0927bf92009-08-08 12:37:44 -04001273}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001274
Josh Gao36dadca2017-05-16 15:02:45 -07001275bool check_header(apacket* p, atransport* t) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001276 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cuib5e11412017-03-10 16:01:01 -08001277 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1278 << ", magic = " << p->msg.magic;
Josh Gao36dadca2017-05-16 15:02:45 -07001279 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001280 }
1281
Josh Gao1290fbf2016-11-22 14:32:34 -08001282 if (p->msg.data_length > t->get_max_payload()) {
1283 VLOG(RWX) << "check_header(): " << p->msg.data_length
1284 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao36dadca2017-05-16 15:02:45 -07001285 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001286 }
1287
Josh Gao36dadca2017-05-16 15:02:45 -07001288 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001289}
1290
Josh Gao3bd28792016-10-05 19:02:29 -07001291#if ADB_HOST
Josh Gao2e671202016-08-18 22:00:12 -07001292std::shared_ptr<RSA> atransport::NextKey() {
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001293 if (keys_.empty()) keys_ = adb_auth_get_private_keys();
1294
Josh Gao2e671202016-08-18 22:00:12 -07001295 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001296 keys_.pop_front();
1297 return result;
1298}
Josh Gao3bd28792016-10-05 19:02:29 -07001299#endif