blob: 0b4e08431e5f21e8168d400ab14d14423be2e805 [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
Dan Albert76649012015-02-24 15:51:19 -080021#include "transport.h"
22
Dan Albert055f1aa2015-02-20 17:24:58 -080023#include <ctype.h>
Dan Albert76649012015-02-24 15:51:19 -080024#include <errno.h>
Josh Gaob122b172017-08-16 16:57:01 -070025#include <inttypes.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080026#include <stdio.h>
27#include <stdlib.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080028#include <string.h>
Dan Albert76649012015-02-24 15:51:19 -080029#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080030
Spencer Low363af562015-11-07 18:51:54 -080031#include <algorithm>
Josh Gao0bbf69c2018-02-16 13:24:58 -080032#include <deque>
Dan Albertc7915a32015-05-18 16:46:31 -070033#include <list>
Pirama Arumuga Nainar29e3dd82018-08-08 10:33:24 -070034#include <memory>
Josh Gao0cd3ae12016-09-21 12:37:10 -070035#include <mutex>
Josh Gao8a40c8a2018-08-10 14:28:24 -070036#include <set>
Josh Gaoe1dacfc2017-04-12 17:00:49 -070037#include <thread>
Dan Albertc7915a32015-05-18 16:46:31 -070038
Elliott Hughes4f713192015-12-04 22:00:26 -080039#include <android-base/logging.h>
David Pursell3f902aa2016-03-01 08:58:26 -080040#include <android-base/parsenetaddress.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080041#include <android-base/stringprintf.h>
42#include <android-base/strings.h>
Josh Gaob122b172017-08-16 16:57:01 -070043#include <android-base/thread_annotations.h>
Elliott Hughese67f1f82015-04-30 17:32:03 -070044
Josh Gao27768452018-01-02 12:01:43 -080045#include <diagnose_usb.h>
46
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080047#include "adb.h"
Elliott Hughes0aeb5052016-06-29 17:42:01 -070048#include "adb_auth.h"
Josh Gaob800d882018-01-28 20:32:46 -080049#include "adb_io.h"
Josh Gaocfe72e22016-11-29 09:40:29 -080050#include "adb_trace.h"
Elliott Hughese67f1f82015-04-30 17:32:03 -070051#include "adb_utils.h"
Yabin Cuib5e11412017-03-10 16:01:01 -080052#include "fdevent.h"
Josh Gaoe445a6d2018-07-31 14:12:59 -070053#include "sysdeps/chrono.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080054
Josh Gao982f7bd2019-02-12 13:59:03 -080055using android::base::ScopedLockAssertion;
56
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070057static void remove_transport(atransport* transport);
58static void transport_unref(atransport* transport);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080059
Josh Gaob122b172017-08-16 16:57:01 -070060// TODO: unordered_map<TransportId, atransport*>
Josh Gaob7b1edf2015-11-11 17:56:12 -080061static auto& transport_list = *new std::list<atransport*>();
62static auto& pending_list = *new std::list<atransport*>();
Benoit Goby1c45ee92013-03-29 18:22:36 -070063
Josh Gao1db71af2017-08-17 13:50:51 -070064static auto& transport_lock = *new std::recursive_mutex();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080065
Todd Kennedy51c05ec2015-11-10 00:03:25 +000066const char* const kFeatureShell2 = "shell_v2";
67const char* const kFeatureCmd = "cmd";
Josh Gao5a1e3fd2016-12-05 17:11:34 -080068const char* const kFeatureStat2 = "stat_v2";
Josh Gao5d1756c2017-02-22 17:07:01 -080069const char* const kFeatureLibusb = "libusb";
Dan Albert5176df82017-05-23 14:30:00 -070070const char* const kFeaturePushSync = "push_sync";
Dario Freni29814de2018-10-04 16:26:40 +010071const char* const kFeatureApex = "apex";
Josh Gaofb085102018-10-22 13:00:05 -070072const char* const kFeatureFixedPushMkdir = "fixed_push_mkdir";
Alex Buynytskyy01a65ee2019-01-17 13:13:56 -080073const char* const kFeatureAbb = "abb";
Josh Gao7b1cb662019-02-20 13:01:40 -080074const char* const kFeatureFixedPushSymlinkTimestamp = "fixed_push_symlink_timestamp";
Alex Buynytskyy05626c12019-02-21 14:22:51 -080075const char* const kFeatureAbbExec = "abb_exec";
Todd Kennedy51c05ec2015-11-10 00:03:25 +000076
Luis Hector Chavez56fe7532018-04-17 14:25:04 -070077namespace {
78
Josh Gaodef91c02018-07-31 18:28:32 -070079#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070080// Tracks and handles atransport*s that are attempting reconnection.
81class ReconnectHandler {
82 public:
83 ReconnectHandler() = default;
84 ~ReconnectHandler() = default;
85
86 // Starts the ReconnectHandler thread.
87 void Start();
88
89 // Requests the ReconnectHandler thread to stop.
90 void Stop();
91
92 // Adds the atransport* to the queue of reconnect attempts.
93 void TrackTransport(atransport* transport);
94
Josh Gao902dace2018-08-10 14:44:54 -070095 // Wake up the ReconnectHandler thread to have it check for kicked transports.
96 void CheckForKicked();
97
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070098 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;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700107
108 bool operator<(const ReconnectAttempt& rhs) const {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700109 if (reconnect_time == rhs.reconnect_time) {
110 return reinterpret_cast<uintptr_t>(transport) <
111 reinterpret_cast<uintptr_t>(rhs.transport);
112 }
113 return reconnect_time < rhs.reconnect_time;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700114 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700115 };
116
117 // Only retry for up to one minute.
Josh Gaoe445a6d2018-07-31 14:12:59 -0700118 static constexpr const std::chrono::seconds kDefaultTimeout = 10s;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700119 static constexpr const size_t kMaxAttempts = 6;
120
121 // Protects all members.
122 std::mutex reconnect_mutex_;
123 bool running_ GUARDED_BY(reconnect_mutex_) = true;
124 std::thread handler_thread_;
125 std::condition_variable reconnect_cv_;
Josh Gao8a40c8a2018-08-10 14:28:24 -0700126 std::set<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700127
128 DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
129};
130
131void ReconnectHandler::Start() {
132 check_main_thread();
133 handler_thread_ = std::thread(&ReconnectHandler::Run, this);
134}
135
136void ReconnectHandler::Stop() {
137 check_main_thread();
138 {
139 std::lock_guard<std::mutex> lock(reconnect_mutex_);
140 running_ = false;
141 }
142 reconnect_cv_.notify_one();
143 handler_thread_.join();
144
145 // Drain the queue to free all resources.
146 std::lock_guard<std::mutex> lock(reconnect_mutex_);
147 while (!reconnect_queue_.empty()) {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700148 ReconnectAttempt attempt = *reconnect_queue_.begin();
149 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700150 remove_transport(attempt.transport);
151 }
152}
153
154void ReconnectHandler::TrackTransport(atransport* transport) {
155 check_main_thread();
156 {
157 std::lock_guard<std::mutex> lock(reconnect_mutex_);
158 if (!running_) return;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700159 // Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
160 auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
161 reconnect_queue_.emplace(
162 ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700163 }
164 reconnect_cv_.notify_one();
165}
166
Josh Gao902dace2018-08-10 14:44:54 -0700167void ReconnectHandler::CheckForKicked() {
168 reconnect_cv_.notify_one();
169}
170
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700171void ReconnectHandler::Run() {
172 while (true) {
173 ReconnectAttempt attempt;
174 {
175 std::unique_lock<std::mutex> lock(reconnect_mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800176 ScopedLockAssertion assume_lock(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700177
Josh Gao95af6412018-07-30 18:51:55 -0700178 if (!reconnect_queue_.empty()) {
179 // FIXME: libstdc++ (used on Windows) implements condition_variable with
180 // system_clock as its clock, so we're probably hosed if the clock changes,
181 // even if we use steady_clock throughout. This problem goes away once we
182 // switch to libc++.
Josh Gao8a40c8a2018-08-10 14:28:24 -0700183 reconnect_cv_.wait_until(lock, reconnect_queue_.begin()->reconnect_time);
Josh Gao95af6412018-07-30 18:51:55 -0700184 } else {
185 reconnect_cv_.wait(lock);
186 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700187
188 if (!running_) return;
Josh Gao902dace2018-08-10 14:44:54 -0700189
190 // Scan the whole list for kicked transports, so that we immediately handle an explicit
191 // disconnect request.
192 bool kicked = false;
193 for (auto it = reconnect_queue_.begin(); it != reconnect_queue_.end();) {
194 if (it->transport->kicked()) {
195 D("transport %s was kicked. giving up on it.", it->transport->serial.c_str());
196 remove_transport(it->transport);
197 it = reconnect_queue_.erase(it);
198 } else {
199 ++it;
200 }
201 kicked = true;
202 }
203
Josh Gao95af6412018-07-30 18:51:55 -0700204 if (reconnect_queue_.empty()) continue;
205
Josh Gao902dace2018-08-10 14:44:54 -0700206 // Go back to sleep if we either woke up spuriously, or we were woken up to remove
207 // a kicked transport, and the first transport isn't ready for reconnection yet.
Josh Gao95af6412018-07-30 18:51:55 -0700208 auto now = std::chrono::steady_clock::now();
Josh Gao8a40c8a2018-08-10 14:28:24 -0700209 if (reconnect_queue_.begin()->reconnect_time > now) {
Josh Gao95af6412018-07-30 18:51:55 -0700210 continue;
211 }
212
Josh Gao8a40c8a2018-08-10 14:28:24 -0700213 attempt = *reconnect_queue_.begin();
214 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700215 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700216 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700217
Josh Gaofc2e56f2018-08-30 11:37:00 -0700218 switch (attempt.transport->Reconnect()) {
219 case ReconnectResult::Retry: {
220 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
221 if (attempt.attempts_left == 0) {
222 D("transport %s exceeded the number of retry attempts. giving up on it.",
223 attempt.transport->serial.c_str());
224 remove_transport(attempt.transport);
225 continue;
226 }
227
228 std::lock_guard<std::mutex> lock(reconnect_mutex_);
229 reconnect_queue_.emplace(ReconnectAttempt{
230 attempt.transport,
231 std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
232 attempt.attempts_left - 1});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700233 continue;
234 }
235
Josh Gaofc2e56f2018-08-30 11:37:00 -0700236 case ReconnectResult::Success:
237 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
238 register_transport(attempt.transport);
239 continue;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700240
Josh Gaofc2e56f2018-08-30 11:37:00 -0700241 case ReconnectResult::Abort:
242 D("cancelling reconnection attempt to %s.", attempt.transport->serial.c_str());
243 remove_transport(attempt.transport);
244 continue;
245 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700246 }
247}
248
249static auto& reconnect_handler = *new ReconnectHandler();
250
Josh Gaodef91c02018-07-31 18:28:32 -0700251#endif
252
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700253} // namespace
254
Josh Gaob122b172017-08-16 16:57:01 -0700255TransportId NextTransportId() {
256 static std::atomic<TransportId> next(1);
257 return next++;
258}
259
Josh Gao0bbf69c2018-02-16 13:24:58 -0800260BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
261 : underlying_(std::move(connection)) {}
262
263BlockingConnectionAdapter::~BlockingConnectionAdapter() {
264 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
265 Stop();
266}
267
268void BlockingConnectionAdapter::Start() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700269 std::lock_guard<std::mutex> lock(mutex_);
270 if (started_) {
271 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
272 << "): started multiple times";
273 }
274
Josh Gao0bbf69c2018-02-16 13:24:58 -0800275 read_thread_ = std::thread([this]() {
276 LOG(INFO) << this->transport_name_ << ": read thread spawning";
277 while (true) {
Josh Gao31b5be62018-03-07 16:51:08 -0800278 auto packet = std::make_unique<apacket>();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800279 if (!underlying_->Read(packet.get())) {
280 PLOG(INFO) << this->transport_name_ << ": read failed";
281 break;
282 }
283 read_callback_(this, std::move(packet));
284 }
285 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
286 });
287
288 write_thread_ = std::thread([this]() {
289 LOG(INFO) << this->transport_name_ << ": write thread spawning";
290 while (true) {
291 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800292 ScopedLockAssertion assume_locked(mutex_);
Josh Gaoc251ec52018-04-03 12:55:18 -0700293 cv_.wait(lock, [this]() REQUIRES(mutex_) {
294 return this->stopped_ || !this->write_queue_.empty();
295 });
296
Josh Gao0bbf69c2018-02-16 13:24:58 -0800297 if (this->stopped_) {
298 return;
299 }
300
301 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
302 this->write_queue_.pop_front();
303 lock.unlock();
304
305 if (!this->underlying_->Write(packet.get())) {
306 break;
307 }
308 }
309 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
310 });
Josh Gaoc251ec52018-04-03 12:55:18 -0700311
312 started_ = true;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800313}
314
315void BlockingConnectionAdapter::Stop() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700316 {
317 std::lock_guard<std::mutex> lock(mutex_);
318 if (!started_) {
319 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
320 return;
321 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800322
Josh Gaoc251ec52018-04-03 12:55:18 -0700323 if (stopped_) {
324 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
325 << "): already stopped";
326 return;
327 }
328
329 stopped_ = true;
330 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800331
332 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
333
334 this->underlying_->Close();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800335 this->cv_.notify_one();
Josh Gaoc251ec52018-04-03 12:55:18 -0700336
337 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
338 std::thread read_thread;
339 std::thread write_thread;
340
341 {
342 std::lock_guard<std::mutex> lock(mutex_);
343 read_thread = std::move(read_thread_);
344 write_thread = std::move(write_thread_);
345 }
346
347 read_thread.join();
348 write_thread.join();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800349
350 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
351 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
352}
353
354bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
355 {
Josh Gaoc251ec52018-04-03 12:55:18 -0700356 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800357 write_queue_.emplace_back(std::move(packet));
358 }
359
360 cv_.notify_one();
361 return true;
362}
363
Josh Gaob800d882018-01-28 20:32:46 -0800364bool FdConnection::Read(apacket* packet) {
365 if (!ReadFdExactly(fd_.get(), &packet->msg, sizeof(amessage))) {
366 D("remote local: read terminated (message)");
367 return false;
368 }
369
Josh Gaof571fcb2018-02-05 18:49:10 -0800370 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gao5caaebd2018-02-02 14:38:04 -0800371 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
372 return false;
373 }
374
Josh Gaof571fcb2018-02-05 18:49:10 -0800375 packet->payload.resize(packet->msg.data_length);
376
377 if (!ReadFdExactly(fd_.get(), &packet->payload[0], packet->payload.size())) {
Josh Gaob800d882018-01-28 20:32:46 -0800378 D("remote local: terminated (data)");
379 return false;
380 }
381
382 return true;
383}
384
385bool FdConnection::Write(apacket* packet) {
Josh Gaof571fcb2018-02-05 18:49:10 -0800386 if (!WriteFdExactly(fd_.get(), &packet->msg, sizeof(packet->msg))) {
Josh Gaob800d882018-01-28 20:32:46 -0800387 D("remote local: write terminated");
388 return false;
389 }
390
Josh Gaof571fcb2018-02-05 18:49:10 -0800391 if (packet->msg.data_length) {
392 if (!WriteFdExactly(fd_.get(), &packet->payload[0], packet->msg.data_length)) {
393 D("remote local: write terminated");
394 return false;
395 }
396 }
397
Josh Gaob800d882018-01-28 20:32:46 -0800398 return true;
399}
400
401void FdConnection::Close() {
402 adb_shutdown(fd_.get());
403 fd_.reset();
404}
405
Josh Gao06d61d42016-10-06 13:31:44 -0700406void send_packet(apacket* p, atransport* t) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800407 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayde471942017-12-07 11:40:00 -0800408 // compute a checksum for connection/auth packets for compatibility reasons
409 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
410 p->msg.data_check = 0;
411 } else {
412 p->msg.data_check = calculate_apacket_checksum(p);
413 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800414
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700415 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800416
Yi Kongaed415c2018-07-13 18:15:16 -0700417 if (t == nullptr) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700418 LOG(FATAL) << "Transport is null";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800419 }
420
Josh Gao0bbf69c2018-02-16 13:24:58 -0800421 if (t->Write(p) != 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700422 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800423 t->Kick();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800424 }
425}
426
Yabin Cuif4b99282015-08-27 12:03:11 -0700427void kick_transport(atransport* t) {
Josh Gao1db71af2017-08-17 13:50:51 -0700428 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui1f4ec192016-04-05 13:50:44 -0700429 // As kick_transport() can be called from threads without guarantee that t is valid,
430 // check if the transport is in transport_list first.
Josh Gaob122b172017-08-16 16:57:01 -0700431 //
432 // TODO(jmgao): WTF? Is this actually true?
Yabin Cui1f4ec192016-04-05 13:50:44 -0700433 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Yabin Cui7f274902016-04-18 11:22:34 -0700434 t->Kick();
Yabin Cui1f4ec192016-04-05 13:50:44 -0700435 }
Josh Gao902dace2018-08-10 14:44:54 -0700436
437#if ADB_HOST
438 reconnect_handler.CheckForKicked();
439#endif
Yabin Cuif4b99282015-08-27 12:03:11 -0700440}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800441
442static int transport_registration_send = -1;
443static int transport_registration_recv = -1;
Josh Gao71f775a2018-05-14 11:14:33 -0700444static fdevent* transport_registration_fde;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800445
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800446#if ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800447
448/* this adds support required by the 'track-devices' service.
449 * this is used to send the content of "list_transport" to any
450 * number of client connections that want it through a single
451 * live TCP connection
452 */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800453struct device_tracker {
Josh Gao1290fbf2016-11-22 14:32:34 -0800454 asocket socket;
Josh Gaoe0361d12018-02-12 17:24:00 -0800455 bool update_needed = false;
456 bool long_output = false;
457 device_tracker* next = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800458};
459
460/* linked list of all device trackers */
Josh Gao1290fbf2016-11-22 14:32:34 -0800461static device_tracker* device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800462
Josh Gao1290fbf2016-11-22 14:32:34 -0800463static void device_tracker_remove(device_tracker* tracker) {
464 device_tracker** pnode = &device_tracker_list;
465 device_tracker* node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800466
Josh Gao1db71af2017-08-17 13:50:51 -0700467 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800468 while (node) {
469 if (node == tracker) {
470 *pnode = node->next;
471 break;
472 }
473 pnode = &node->next;
Josh Gao1290fbf2016-11-22 14:32:34 -0800474 node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800475 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800476}
477
Josh Gao1290fbf2016-11-22 14:32:34 -0800478static void device_tracker_close(asocket* socket) {
479 device_tracker* tracker = (device_tracker*)socket;
480 asocket* peer = socket->peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800481
Josh Gao1290fbf2016-11-22 14:32:34 -0800482 D("device tracker %p removed", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800483 if (peer) {
Yi Kongaed415c2018-07-13 18:15:16 -0700484 peer->peer = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800485 peer->close(peer);
486 }
487 device_tracker_remove(tracker);
Josh Gaoe0361d12018-02-12 17:24:00 -0800488 delete tracker;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800489}
490
Josh Gao1ce99572018-03-07 16:52:28 -0800491static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800492 /* you can't read from a device tracker, close immediately */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800493 device_tracker_close(socket);
494 return -1;
495}
496
Elliott Hughese67f1f82015-04-30 17:32:03 -0700497static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700498 asocket* peer = tracker->socket.peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800499
Josh Gao1ce99572018-03-07 16:52:28 -0800500 apacket::payload_type data;
Josh Gao27cb7dc2018-02-01 13:17:50 -0800501 data.resize(4 + string.size());
502 char buf[5];
503 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
504 memcpy(&data[0], buf, 4);
505 memcpy(&data[4], string.data(), string.size());
506 return peer->enqueue(peer, std::move(data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800507}
508
Elliott Hughese67f1f82015-04-30 17:32:03 -0700509static void device_tracker_ready(asocket* socket) {
510 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800511
Elliott Hughese67f1f82015-04-30 17:32:03 -0700512 // We want to send the device list when the tracker connects
513 // for the first time, even if no update occurred.
Josh Gaob0c18022017-08-14 18:57:54 -0700514 if (tracker->update_needed) {
515 tracker->update_needed = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800516
Josh Gaob0c18022017-08-14 18:57:54 -0700517 std::string transports = list_transports(tracker->long_output);
Elliott Hughese67f1f82015-04-30 17:32:03 -0700518 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800519 }
520}
521
Josh Gaob0c18022017-08-14 18:57:54 -0700522asocket* create_device_tracker(bool long_output) {
Josh Gaoe0361d12018-02-12 17:24:00 -0800523 device_tracker* tracker = new device_tracker();
Elliott Hughes4679a392018-10-19 13:59:44 -0700524 if (tracker == nullptr) LOG(FATAL) << "cannot allocate device tracker";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800525
Josh Gao1290fbf2016-11-22 14:32:34 -0800526 D("device tracker %p created", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800527
528 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao1290fbf2016-11-22 14:32:34 -0800529 tracker->socket.ready = device_tracker_ready;
530 tracker->socket.close = device_tracker_close;
Josh Gaob0c18022017-08-14 18:57:54 -0700531 tracker->update_needed = true;
532 tracker->long_output = long_output;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800533
Josh Gao1290fbf2016-11-22 14:32:34 -0800534 tracker->next = device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800535 device_tracker_list = tracker;
536
537 return &tracker->socket;
538}
539
Josh Gaofd713e52017-05-03 22:37:10 -0700540// Check if all of the USB transports are connected.
541bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gao1db71af2017-08-17 13:50:51 -0700542 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaofd713e52017-05-03 22:37:10 -0700543 for (const auto& t : transport_list) {
544 if (!fn(t)) {
545 return false;
546 }
547 }
548 for (const auto& t : pending_list) {
549 if (!fn(t)) {
550 return false;
551 }
552 }
553 return true;
554}
555
Elliott Hughese67f1f82015-04-30 17:32:03 -0700556// Call this function each time the transport list has changed.
557void update_transports() {
Josh Gaofd713e52017-05-03 22:37:10 -0700558 update_transport_status();
559
560 // Notify `adb track-devices` clients.
Elliott Hughese67f1f82015-04-30 17:32:03 -0700561 std::string transports = list_transports(false);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800562
Elliott Hughese67f1f82015-04-30 17:32:03 -0700563 device_tracker* tracker = device_tracker_list;
564 while (tracker != nullptr) {
565 device_tracker* next = tracker->next;
566 // This may destroy the tracker if the connection is closed.
567 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800568 tracker = next;
569 }
570}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700571
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800572#else
Elliott Hughese67f1f82015-04-30 17:32:03 -0700573
574void update_transports() {
575 // Nothing to do on the device side.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800576}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700577
Josh Gao1290fbf2016-11-22 14:32:34 -0800578#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800579
Josh Gao1290fbf2016-11-22 14:32:34 -0800580struct tmsg {
581 atransport* transport;
582 int action;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800583};
584
Josh Gao1290fbf2016-11-22 14:32:34 -0800585static int transport_read_action(int fd, struct tmsg* m) {
586 char* p = (char*)m;
587 int len = sizeof(*m);
588 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800589
Josh Gao1290fbf2016-11-22 14:32:34 -0800590 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800591 r = adb_read(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800592 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800593 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800594 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800595 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700596 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800597 return -1;
598 }
599 }
600 return 0;
601}
602
Josh Gao1290fbf2016-11-22 14:32:34 -0800603static int transport_write_action(int fd, struct tmsg* m) {
604 char* p = (char*)m;
605 int len = sizeof(*m);
606 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800607
Josh Gao1290fbf2016-11-22 14:32:34 -0800608 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800609 r = adb_write(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800610 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800611 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800612 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800613 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700614 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800615 return -1;
616 }
617 }
618 return 0;
619}
620
Josh Gao0bbf69c2018-02-16 13:24:58 -0800621static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800622 tmsg m;
Josh Gao1290fbf2016-11-22 14:32:34 -0800623 atransport* t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800624
Josh Gao1290fbf2016-11-22 14:32:34 -0800625 if (!(ev & FDE_READ)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800626 return;
627 }
628
Josh Gao1290fbf2016-11-22 14:32:34 -0800629 if (transport_read_action(_fd, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700630 PLOG(FATAL) << "cannot read transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800631 }
632
633 t = m.transport;
634
Dan Albert1792c232015-05-18 13:06:53 -0700635 if (m.action == 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700636 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800637
Josh Gao0cd3ae12016-09-21 12:37:10 -0700638 {
Josh Gao1db71af2017-08-17 13:50:51 -0700639 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700640 transport_list.remove(t);
641 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800642
Dan Albertc7915a32015-05-18 16:46:31 -0700643 delete t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800644
645 update_transports();
646 return;
647 }
648
Mike Lockwood0927bf92009-08-08 12:37:44 -0400649 /* don't create transport threads for inaccessible devices */
Yabin Cuib5e11412017-03-10 16:01:01 -0800650 if (t->GetConnectionState() != kCsNoPerm) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700651 // The connection gets a reference to the atransport. It will release it
652 // upon a read/write error.
653 t->ref_count++;
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700654 t->connection()->SetTransportName(t->serial_name());
655 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao0bbf69c2018-02-16 13:24:58 -0800656 if (!check_header(p.get(), t)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700657 D("%s: remote read: bad header", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800658 return false;
659 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800660
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700661 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "from remote", p.get());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800662 apacket* packet = p.release();
Mike Lockwood0927bf92009-08-08 12:37:44 -0400663
Josh Gao0bbf69c2018-02-16 13:24:58 -0800664 // TODO: Does this need to run on the main thread?
665 fdevent_run_on_main_thread([packet, t]() { handle_packet(packet, t); });
666 return true;
667 });
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700668 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700669 LOG(INFO) << t->serial_name() << ": connection terminated: " << error;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800670 fdevent_run_on_main_thread([t]() {
671 handle_offline(t);
672 transport_unref(t);
673 });
674 });
Mike Lockwood0927bf92009-08-08 12:37:44 -0400675
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700676 t->connection()->Start();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800677#if ADB_HOST
678 send_connect(t);
679#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800680 }
681
Josh Gao0cd3ae12016-09-21 12:37:10 -0700682 {
Josh Gao1db71af2017-08-17 13:50:51 -0700683 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700684 auto it = std::find(pending_list.begin(), pending_list.end(), t);
685 if (it != pending_list.end()) {
686 pending_list.remove(t);
687 transport_list.push_front(t);
688 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700689 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800690
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800691 update_transports();
692}
693
Josh Gaodef91c02018-07-31 18:28:32 -0700694#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700695void init_reconnect_handler(void) {
696 reconnect_handler.Start();
697}
Josh Gaodef91c02018-07-31 18:28:32 -0700698#endif
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700699
Josh Gao1290fbf2016-11-22 14:32:34 -0800700void init_transport_registration(void) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800701 int s[2];
702
Josh Gao1290fbf2016-11-22 14:32:34 -0800703 if (adb_socketpair(s)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700704 PLOG(FATAL) << "cannot open transport registration socketpair";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800705 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700706 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800707
708 transport_registration_send = s[0];
709 transport_registration_recv = s[1];
710
Josh Gao71f775a2018-05-14 11:14:33 -0700711 transport_registration_fde =
Yi Kongaed415c2018-07-13 18:15:16 -0700712 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao71f775a2018-05-14 11:14:33 -0700713 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao01b7bc42017-05-09 13:43:35 -0700714}
715
716void kick_all_transports() {
Josh Gaodef91c02018-07-31 18:28:32 -0700717#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700718 reconnect_handler.Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700719#endif
Josh Gao01b7bc42017-05-09 13:43:35 -0700720 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gao1db71af2017-08-17 13:50:51 -0700721 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao01b7bc42017-05-09 13:43:35 -0700722 for (auto t : transport_list) {
723 t->Kick();
724 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800725}
726
727/* the fdevent select pump is single threaded */
Josh Gaoc51726c2018-10-11 16:33:05 -0700728void register_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800729 tmsg m;
730 m.transport = transport;
731 m.action = 1;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700732 D("transport: %s registered", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800733 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700734 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800735 }
736}
737
Josh Gao1290fbf2016-11-22 14:32:34 -0800738static void remove_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800739 tmsg m;
740 m.transport = transport;
741 m.action = 0;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700742 D("transport: %s removed", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800743 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700744 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800745 }
746}
747
Yabin Cuif4b99282015-08-27 12:03:11 -0700748static void transport_unref(atransport* t) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700749 check_main_thread();
Yabin Cuif4b99282015-08-27 12:03:11 -0700750 CHECK(t != nullptr);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700751
Josh Gaoe48ecce2017-09-13 13:40:57 -0700752 std::lock_guard<std::recursive_mutex> lock(transport_lock);
753 CHECK_GT(t->ref_count, 0u);
754 t->ref_count--;
755 if (t->ref_count == 0) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700756 LOG(INFO) << "destroying transport " << t->serial_name();
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700757 t->connection()->Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700758#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700759 if (t->IsTcpDevice() && !t->kicked()) {
Josh Gaodef91c02018-07-31 18:28:32 -0700760 D("transport: %s unref (attempting reconnection)", t->serial.c_str());
Josh Gao4414e4c2018-12-04 01:07:50 -0800761
762 // We need to clear the transport's keys, so that on the next connection, it tries
763 // again from the beginning.
764 t->ResetKeys();
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700765 reconnect_handler.TrackTransport(t);
766 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700767 D("transport: %s unref (kicking and closing)", t->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700768 remove_transport(t);
769 }
Josh Gaodef91c02018-07-31 18:28:32 -0700770#else
771 D("transport: %s unref (kicking and closing)", t->serial.c_str());
772 remove_transport(t);
773#endif
774
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100775 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700776 D("transport: %s unref (count=%zu)", t->serial.c_str(), t->ref_count);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -0400777 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800778}
779
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700780static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao1290fbf2016-11-22 14:32:34 -0800781 bool sanitize_qual) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700782 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
783 return qual.empty();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700784
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700785 if (qual.empty()) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700786
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700787 const char* ptr = to_test.c_str();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700788 if (prefix) {
789 while (*prefix) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700790 if (*prefix++ != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700791 }
792 }
793
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700794 for (char ch : qual) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800795 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700796 if (ch != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700797 }
798
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700799 /* Everything matched so far. Return true if *ptr is a NUL. */
800 return !*ptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700801}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800802
Josh Gaob122b172017-08-16 16:57:01 -0700803atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
804 bool* is_ambiguous, std::string* error_out,
805 bool accept_any_state) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700806 atransport* result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800807
Josh Gaob122b172017-08-16 16:57:01 -0700808 if (transport_id != 0) {
809 *error_out =
810 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
811 } else if (serial) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700812 *error_out = android::base::StringPrintf("device '%s' not found", serial);
813 } else if (type == kTransportLocal) {
814 *error_out = "no emulators found";
815 } else if (type == kTransportAny) {
816 *error_out = "no devices/emulators found";
817 } else {
818 *error_out = "no devices found";
819 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800820
Josh Gao1db71af2017-08-17 13:50:51 -0700821 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes8d28e192015-10-07 14:55:10 -0700822 for (const auto& t : transport_list) {
Yabin Cuib5e11412017-03-10 16:01:01 -0800823 if (t->GetConnectionState() == kCsNoPerm) {
David Purselld2acbd12015-12-02 15:14:31 -0800824 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwood37d31112009-08-08 13:53:16 -0400825 continue;
826 }
Mike Lockwood0927bf92009-08-08 12:37:44 -0400827
Josh Gaob122b172017-08-16 16:57:01 -0700828 if (transport_id) {
829 if (t->id == transport_id) {
830 result = t;
831 break;
832 }
833 } else if (serial) {
David Pursell3f902aa2016-03-01 08:58:26 -0800834 if (t->MatchesTarget(serial)) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700835 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700836 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700837 if (is_ambiguous) *is_ambiguous = true;
838 result = nullptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700839 break;
840 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800841 result = t;
Scott Andersone109d262012-04-20 11:21:14 -0700842 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800843 } else {
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700844 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800845 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700846 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700847 if (is_ambiguous) *is_ambiguous = true;
848 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800849 break;
850 }
851 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700852 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800853 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700854 *error_out = "more than one emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700855 if (is_ambiguous) *is_ambiguous = true;
856 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800857 break;
858 }
859 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700860 } else if (type == kTransportAny) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800861 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700862 *error_out = "more than one device/emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700863 if (is_ambiguous) *is_ambiguous = true;
864 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800865 break;
866 }
867 result = t;
868 }
869 }
870 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700871 lock.unlock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800872
Josh Gao704494b2018-05-04 16:04:49 -0700873 if (result && !accept_any_state) {
874 // The caller requires an active transport.
875 // Make sure that we're actually connected.
876 ConnectionState state = result->GetConnectionState();
877 switch (state) {
878 case kCsConnecting:
879 *error_out = "device still connecting";
880 result = nullptr;
881 break;
Benoit Goby77e8e582013-01-15 12:36:47 -0800882
Josh Gao704494b2018-05-04 16:04:49 -0700883 case kCsAuthorizing:
884 *error_out = "device still authorizing";
885 result = nullptr;
886 break;
887
888 case kCsUnauthorized: {
889 *error_out = "device unauthorized.\n";
890 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
891 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
892 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
893 *error_out += "\n";
894 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
895 *error_out += "Otherwise check for a confirmation dialog on your device.";
896 result = nullptr;
897 break;
898 }
899
900 case kCsOffline:
901 *error_out = "device offline";
902 result = nullptr;
903 break;
904
905 default:
906 break;
907 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800908 }
909
910 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700911 *error_out = "success";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800912 }
913
914 return result;
915}
916
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700917bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
918 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800919 ScopedLockAssertion assume_locked(mutex_);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700920 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
921 return connection_established_ready_;
922 }) && connection_established_;
923}
924
925void ConnectionWaitable::SetConnectionEstablished(bool success) {
926 {
927 std::lock_guard<std::mutex> lock(mutex_);
928 if (connection_established_ready_) return;
929 connection_established_ready_ = true;
930 connection_established_ = success;
931 D("connection established with %d", success);
932 }
933 cv_.notify_one();
934}
935
936atransport::~atransport() {
937 // If the connection callback had not been run before, run it now.
938 SetConnectionEstablished(false);
939}
940
Yabin Cuib5e11412017-03-10 16:01:01 -0800941int atransport::Write(apacket* p) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700942 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cuib5e11412017-03-10 16:01:01 -0800943}
944
Yabin Cui7f274902016-04-18 11:22:34 -0700945void atransport::Kick() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700946 if (!kicked_.exchange(true)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700947 D("kicking transport %p %s", this, this->serial.c_str());
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700948 this->connection()->Stop();
Yabin Cui7f274902016-04-18 11:22:34 -0700949 }
950}
951
Yabin Cuib5e11412017-03-10 16:01:01 -0800952ConnectionState atransport::GetConnectionState() const {
953 return connection_state_;
954}
955
956void atransport::SetConnectionState(ConnectionState state) {
957 check_main_thread();
958 connection_state_ = state;
959}
960
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700961void atransport::SetConnection(std::unique_ptr<Connection> connection) {
962 std::lock_guard<std::mutex> lock(mutex_);
963 connection_ = std::shared_ptr<Connection>(std::move(connection));
964}
965
Josh Gaoffbd3362018-02-28 14:44:23 -0800966std::string atransport::connection_state_name() const {
Yabin Cuib5e11412017-03-10 16:01:01 -0800967 ConnectionState state = GetConnectionState();
968 switch (state) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800969 case kCsOffline:
970 return "offline";
971 case kCsBootloader:
972 return "bootloader";
973 case kCsDevice:
974 return "device";
975 case kCsHost:
976 return "host";
977 case kCsRecovery:
978 return "recovery";
979 case kCsNoPerm:
980 return UsbNoPermissionsShortHelpText();
981 case kCsSideload:
982 return "sideload";
983 case kCsUnauthorized:
984 return "unauthorized";
Josh Gao704494b2018-05-04 16:04:49 -0700985 case kCsAuthorizing:
986 return "authorizing";
987 case kCsConnecting:
988 return "connecting";
Josh Gao1290fbf2016-11-22 14:32:34 -0800989 default:
990 return "unknown";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800991 }
992}
993
Tamas Berghammer3d2904c2015-07-13 19:12:28 +0100994void atransport::update_version(int version, size_t payload) {
995 protocol_version = std::min(version, A_VERSION);
996 max_payload = std::min(payload, MAX_PAYLOAD);
997}
998
999int atransport::get_protocol_version() const {
1000 return protocol_version;
1001}
1002
1003size_t atransport::get_max_payload() const {
1004 return max_payload;
1005}
1006
Dan Albert1792c232015-05-18 13:06:53 -07001007const FeatureSet& supported_features() {
David Pursell4e2fd362015-09-22 10:43:08 -07001008 // Local static allocation to avoid global non-POD variables.
1009 static const FeatureSet* features = new FeatureSet{
Josh Gao7b1cb662019-02-20 13:01:40 -08001010 kFeatureShell2,
1011 kFeatureCmd,
1012 kFeatureStat2,
1013 kFeatureFixedPushMkdir,
1014 kFeatureApex,
1015 kFeatureAbb,
1016 kFeatureFixedPushSymlinkTimestamp,
Alex Buynytskyy05626c12019-02-21 14:22:51 -08001017 kFeatureAbbExec,
Josh Gao919b70c2018-11-08 22:39:43 -08001018 // Increment ADB_SERVER_VERSION when adding a feature that adbd needs
1019 // to know about. Otherwise, the client can be stuck running an old
1020 // version of the server even after upgrading their copy of adb.
1021 // (http://b/24370690)
David Pursell4e2fd362015-09-22 10:43:08 -07001022 };
1023
1024 return *features;
1025}
1026
1027std::string FeatureSetToString(const FeatureSet& features) {
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001028 return android::base::Join(features, ',');
David Pursell4e2fd362015-09-22 10:43:08 -07001029}
1030
1031FeatureSet StringToFeatureSet(const std::string& features_string) {
David Purselld2b588e2015-09-25 13:04:21 -07001032 if (features_string.empty()) {
1033 return FeatureSet();
1034 }
1035
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001036 auto names = android::base::Split(features_string, ",");
David Pursell4e2fd362015-09-22 10:43:08 -07001037 return FeatureSet(names.begin(), names.end());
Dan Albert1792c232015-05-18 13:06:53 -07001038}
1039
David Pursell70ef7b42015-09-30 13:35:42 -07001040bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001041 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell70ef7b42015-09-30 13:35:42 -07001042}
1043
Dan Albert1792c232015-05-18 13:06:53 -07001044bool atransport::has_feature(const std::string& feature) const {
1045 return features_.count(feature) > 0;
1046}
1047
David Pursell4e2fd362015-09-22 10:43:08 -07001048void atransport::SetFeatures(const std::string& features_string) {
1049 features_ = StringToFeatureSet(features_string);
Dan Albert1792c232015-05-18 13:06:53 -07001050}
1051
Yabin Cuib3298242015-08-28 15:09:44 -07001052void atransport::AddDisconnect(adisconnect* disconnect) {
1053 disconnects_.push_back(disconnect);
1054}
1055
1056void atransport::RemoveDisconnect(adisconnect* disconnect) {
1057 disconnects_.remove(disconnect);
1058}
1059
1060void atransport::RunDisconnects() {
Elliott Hughes65fe2512015-10-07 15:59:35 -07001061 for (const auto& disconnect : disconnects_) {
Yabin Cuib3298242015-08-28 15:09:44 -07001062 disconnect->func(disconnect->opaque, this);
1063 }
1064 disconnects_.clear();
1065}
1066
David Pursell3f902aa2016-03-01 08:58:26 -08001067bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001068 if (!serial.empty()) {
David Pursell3f902aa2016-03-01 08:58:26 -08001069 if (target == serial) {
1070 return true;
1071 } else if (type == kTransportLocal) {
1072 // Local transports can match [tcp:|udp:]<hostname>[:port].
1073 const char* local_target_ptr = target.c_str();
1074
1075 // For fastboot compatibility, ignore protocol prefixes.
1076 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao1290fbf2016-11-22 14:32:34 -08001077 android::base::StartsWith(target, "udp:")) {
David Pursell3f902aa2016-03-01 08:58:26 -08001078 local_target_ptr += 4;
1079 }
1080
1081 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1082 std::string serial_host, error;
1083 int serial_port = -1;
Josh Gao1290fbf2016-11-22 14:32:34 -08001084 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursell3f902aa2016-03-01 08:58:26 -08001085 // |target| may omit the port to default to ours.
1086 std::string target_host;
1087 int target_port = serial_port;
1088 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1089 nullptr, &error) &&
Josh Gao1290fbf2016-11-22 14:32:34 -08001090 serial_host == target_host && serial_port == target_port) {
David Pursell3f902aa2016-03-01 08:58:26 -08001091 return true;
1092 }
1093 }
1094 }
1095 }
1096
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001097 return (target == devpath) || qual_match(target, "product:", product, false) ||
1098 qual_match(target, "model:", model, true) ||
1099 qual_match(target, "device:", device, false);
David Pursell3f902aa2016-03-01 08:58:26 -08001100}
1101
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001102void atransport::SetConnectionEstablished(bool success) {
1103 connection_waitable_->SetConnectionEstablished(success);
1104}
1105
Josh Gaofc2e56f2018-08-30 11:37:00 -07001106ReconnectResult atransport::Reconnect() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001107 return reconnect_(this);
1108}
1109
Elliott Hughese67f1f82015-04-30 17:32:03 -07001110#if ADB_HOST
1111
Josh Gaob122b172017-08-16 16:57:01 -07001112// We use newline as our delimiter, make sure to never output it.
1113static std::string sanitize(std::string str, bool alphanumeric) {
1114 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1115 : [](const char c) { return c == '\n'; };
1116 std::replace_if(str.begin(), str.end(), pred, '_');
1117 return str;
1118}
1119
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001120static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob122b172017-08-16 16:57:01 -07001121 bool alphanumeric) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001122 if (value.empty()) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001123 return;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001124 }
1125
Elliott Hughese67f1f82015-04-30 17:32:03 -07001126 *result += ' ';
1127 *result += key;
Josh Gaob122b172017-08-16 16:57:01 -07001128 *result += sanitize(value, alphanumeric);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001129}
1130
Josh Gao1290fbf2016-11-22 14:32:34 -08001131static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001132 std::string serial = t->serial;
1133 if (serial.empty()) {
Dan Albertd99d9022015-05-06 16:48:52 -07001134 serial = "(no serial number)";
Elliott Hughese67f1f82015-04-30 17:32:03 -07001135 }
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001136
1137 if (!long_listing) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001138 *result += serial;
1139 *result += '\t';
1140 *result += t->connection_state_name();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001141 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001142 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1143 t->connection_state_name().c_str());
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001144
Elliott Hughese67f1f82015-04-30 17:32:03 -07001145 append_transport_info(result, "", t->devpath, false);
1146 append_transport_info(result, "product:", t->product, false);
1147 append_transport_info(result, "model:", t->model, true);
1148 append_transport_info(result, "device:", t->device, false);
Josh Gaob122b172017-08-16 16:57:01 -07001149
1150 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1151 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1152 *result += " transport_id:";
1153 *result += std::to_string(t->id);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001154 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001155 *result += '\n';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001156}
1157
Elliott Hughese67f1f82015-04-30 17:32:03 -07001158std::string list_transports(bool long_listing) {
Josh Gao1db71af2017-08-17 13:50:51 -07001159 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov04398a92017-12-17 10:56:07 +00001160
1161 auto sorted_transport_list = transport_list;
1162 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1163 if (x->type != y->type) {
1164 return x->type < y->type;
1165 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001166 return x->serial < y->serial;
Artem Iglikov04398a92017-12-17 10:56:07 +00001167 });
1168
1169 std::string result;
1170 for (const auto& t : sorted_transport_list) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001171 append_transport(t, &result, long_listing);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001172 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001173 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001174}
1175
Josh Gao22d2b3e2016-10-27 14:01:08 -07001176void close_usb_devices(std::function<bool(const atransport*)> predicate) {
Josh Gao1db71af2017-08-17 13:50:51 -07001177 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao22d2b3e2016-10-27 14:01:08 -07001178 for (auto& t : transport_list) {
1179 if (predicate(t)) {
1180 t->Kick();
1181 }
1182 }
1183}
1184
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001185/* hack for osx */
Dan Albertc7915a32015-05-18 16:46:31 -07001186void close_usb_devices() {
Josh Gao22d2b3e2016-10-27 14:01:08 -07001187 close_usb_devices([](const atransport*) { return true; });
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001188}
Josh Gao1290fbf2016-11-22 14:32:34 -08001189#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001190
Josh Gao362e6962018-08-08 16:20:14 -07001191bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
1192 atransport::ReconnectCallback reconnect, int* error) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001193 atransport* t = new atransport(std::move(reconnect), kCsOffline);
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +01001194
Josh Gao3b4de3c2018-08-02 13:58:24 -07001195 D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
Josh Gao56300c92018-07-25 17:21:49 -07001196 if (init_socket_transport(t, std::move(s), port, local) < 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001197 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001198 if (error) *error = errno;
1199 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001200 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001201
Josh Gao1db71af2017-08-17 13:50:51 -07001202 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes65fe2512015-10-07 15:59:35 -07001203 for (const auto& transport : pending_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001204 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001205 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001206 << " is already in pending_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001207 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001208 if (error) *error = EALREADY;
1209 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001210 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001211 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001212
Elliott Hughes65fe2512015-10-07 15:59:35 -07001213 for (const auto& transport : transport_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001214 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001215 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001216 << " is already in transport_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001217 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001218 if (error) *error = EALREADY;
1219 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001220 }
1221 }
1222
Josh Gao3b4de3c2018-08-02 13:58:24 -07001223 t->serial = std::move(serial);
Dan Albertc7915a32015-05-18 16:46:31 -07001224 pending_list.push_front(t);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001225
1226 lock.unlock();
Benoit Goby1c45ee92013-03-29 18:22:36 -07001227
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001228 auto waitable = t->connection_waitable();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001229 register_transport(t);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001230
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001231 if (local == 1) {
1232 // Do not wait for emulator transports.
Josh Gao362e6962018-08-08 16:20:14 -07001233 return true;
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001234 }
1235
Josh Gao362e6962018-08-08 16:20:14 -07001236 if (!waitable->WaitForConnection(std::chrono::seconds(10))) {
1237 if (error) *error = ETIMEDOUT;
1238 return false;
1239 }
1240
1241 if (t->GetConnectionState() == kCsUnauthorized) {
1242 if (error) *error = EPERM;
1243 return false;
1244 }
1245
1246 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001247}
1248
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001249#if ADB_HOST
Josh Gao1290fbf2016-11-22 14:32:34 -08001250atransport* find_transport(const char* serial) {
Dan Albertc7915a32015-05-18 16:46:31 -07001251 atransport* result = nullptr;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001252
Josh Gao1db71af2017-08-17 13:50:51 -07001253 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001254 for (auto& t : transport_list) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001255 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001256 result = t;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001257 break;
1258 }
Dan Albertc7915a32015-05-18 16:46:31 -07001259 }
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001260
Dan Albertc7915a32015-05-18 16:46:31 -07001261 return result;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001262}
1263
Yabin Cuif4b99282015-08-27 12:03:11 -07001264void kick_all_tcp_devices() {
Josh Gao1db71af2017-08-17 13:50:51 -07001265 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001266 for (auto& t : transport_list) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001267 if (t->IsTcpDevice()) {
Yabin Cuid6ab3c22015-08-31 11:50:24 -07001268 // Kicking breaks the read_transport thread of this transport out of any read, then
1269 // the read_transport thread will notify the main thread to make this transport
1270 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cuif4b99282015-08-27 12:03:11 -07001271 // Finally, this transport will be closed and freed in the main thread.
Yabin Cui7f274902016-04-18 11:22:34 -07001272 t->Kick();
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001273 }
Dan Albertc7915a32015-05-18 16:46:31 -07001274 }
Josh Gao902dace2018-08-10 14:44:54 -07001275#if ADB_HOST
1276 reconnect_handler.CheckForKicked();
1277#endif
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001278}
1279
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001280#endif
1281
Josh Gao1290fbf2016-11-22 14:32:34 -08001282void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1283 unsigned writeable) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001284 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertc7915a32015-05-18 16:46:31 -07001285
Josh Gao1290fbf2016-11-22 14:32:34 -08001286 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cuib5e11412017-03-10 16:01:01 -08001287 init_usb_transport(t, usb);
Josh Gao1290fbf2016-11-22 14:32:34 -08001288 if (serial) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001289 t->serial = serial;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001290 }
Dan Albertc7915a32015-05-18 16:46:31 -07001291
1292 if (devpath) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001293 t->devpath = devpath;
Scott Andersone109d262012-04-20 11:21:14 -07001294 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001295
Josh Gao0cd3ae12016-09-21 12:37:10 -07001296 {
Josh Gao1db71af2017-08-17 13:50:51 -07001297 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001298 pending_list.push_front(t);
1299 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001300
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001301 register_transport(t);
1302}
1303
Josh Gaoc51726c2018-10-11 16:33:05 -07001304#if ADB_HOST
Dan Albertdcd78a12015-05-18 16:43:57 -07001305// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao1290fbf2016-11-22 14:32:34 -08001306void unregister_usb_transport(usb_handle* usb) {
Josh Gao1db71af2017-08-17 13:50:51 -07001307 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaob800d882018-01-28 20:32:46 -08001308 transport_list.remove_if([usb](atransport* t) {
Josh Gaoce5ce872018-12-11 13:11:52 -08001309 return t->GetUsbHandle() == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gaob800d882018-01-28 20:32:46 -08001310 });
Mike Lockwood0927bf92009-08-08 12:37:44 -04001311}
Josh Gaoc51726c2018-10-11 16:33:05 -07001312#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001313
Josh Gao36dadca2017-05-16 15:02:45 -07001314bool check_header(apacket* p, atransport* t) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001315 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cuib5e11412017-03-10 16:01:01 -08001316 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1317 << ", magic = " << p->msg.magic;
Josh Gao36dadca2017-05-16 15:02:45 -07001318 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001319 }
1320
Josh Gao1290fbf2016-11-22 14:32:34 -08001321 if (p->msg.data_length > t->get_max_payload()) {
1322 VLOG(RWX) << "check_header(): " << p->msg.data_length
1323 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao36dadca2017-05-16 15:02:45 -07001324 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001325 }
1326
Josh Gao36dadca2017-05-16 15:02:45 -07001327 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001328}
1329
Josh Gao3bd28792016-10-05 19:02:29 -07001330#if ADB_HOST
Josh Gao2e671202016-08-18 22:00:12 -07001331std::shared_ptr<RSA> atransport::NextKey() {
Josh Gao4414e4c2018-12-04 01:07:50 -08001332 if (keys_.empty()) {
1333 LOG(INFO) << "fetching keys for transport " << this->serial_name();
1334 keys_ = adb_auth_get_private_keys();
1335
1336 // We should have gotten at least one key: the one that's automatically generated.
1337 CHECK(!keys_.empty());
1338 }
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001339
Josh Gao2e671202016-08-18 22:00:12 -07001340 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001341 keys_.pop_front();
1342 return result;
1343}
Josh Gao4414e4c2018-12-04 01:07:50 -08001344
1345void atransport::ResetKeys() {
1346 keys_.clear();
1347}
Josh Gao3bd28792016-10-05 19:02:29 -07001348#endif