blob: 90f94ee1ea405b13afd5d074377892a37a95fd4f [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";
Todd Kennedy51c05ec2015-11-10 00:03:25 +000074
Luis Hector Chavez56fe7532018-04-17 14:25:04 -070075namespace {
76
Josh Gaodef91c02018-07-31 18:28:32 -070077#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070078// Tracks and handles atransport*s that are attempting reconnection.
79class ReconnectHandler {
80 public:
81 ReconnectHandler() = default;
82 ~ReconnectHandler() = default;
83
84 // Starts the ReconnectHandler thread.
85 void Start();
86
87 // Requests the ReconnectHandler thread to stop.
88 void Stop();
89
90 // Adds the atransport* to the queue of reconnect attempts.
91 void TrackTransport(atransport* transport);
92
Josh Gao902dace2018-08-10 14:44:54 -070093 // Wake up the ReconnectHandler thread to have it check for kicked transports.
94 void CheckForKicked();
95
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070096 private:
97 // The main thread loop.
98 void Run();
99
100 // Tracks a reconnection attempt.
101 struct ReconnectAttempt {
102 atransport* transport;
Josh Gao95af6412018-07-30 18:51:55 -0700103 std::chrono::steady_clock::time_point reconnect_time;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700104 size_t attempts_left;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700105
106 bool operator<(const ReconnectAttempt& rhs) const {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700107 if (reconnect_time == rhs.reconnect_time) {
108 return reinterpret_cast<uintptr_t>(transport) <
109 reinterpret_cast<uintptr_t>(rhs.transport);
110 }
111 return reconnect_time < rhs.reconnect_time;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700112 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700113 };
114
115 // Only retry for up to one minute.
Josh Gaoe445a6d2018-07-31 14:12:59 -0700116 static constexpr const std::chrono::seconds kDefaultTimeout = 10s;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700117 static constexpr const size_t kMaxAttempts = 6;
118
119 // Protects all members.
120 std::mutex reconnect_mutex_;
121 bool running_ GUARDED_BY(reconnect_mutex_) = true;
122 std::thread handler_thread_;
123 std::condition_variable reconnect_cv_;
Josh Gao8a40c8a2018-08-10 14:28:24 -0700124 std::set<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700125
126 DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
127};
128
129void ReconnectHandler::Start() {
130 check_main_thread();
131 handler_thread_ = std::thread(&ReconnectHandler::Run, this);
132}
133
134void ReconnectHandler::Stop() {
135 check_main_thread();
136 {
137 std::lock_guard<std::mutex> lock(reconnect_mutex_);
138 running_ = false;
139 }
140 reconnect_cv_.notify_one();
141 handler_thread_.join();
142
143 // Drain the queue to free all resources.
144 std::lock_guard<std::mutex> lock(reconnect_mutex_);
145 while (!reconnect_queue_.empty()) {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700146 ReconnectAttempt attempt = *reconnect_queue_.begin();
147 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700148 remove_transport(attempt.transport);
149 }
150}
151
152void ReconnectHandler::TrackTransport(atransport* transport) {
153 check_main_thread();
154 {
155 std::lock_guard<std::mutex> lock(reconnect_mutex_);
156 if (!running_) return;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700157 // Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
158 auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
159 reconnect_queue_.emplace(
160 ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700161 }
162 reconnect_cv_.notify_one();
163}
164
Josh Gao902dace2018-08-10 14:44:54 -0700165void ReconnectHandler::CheckForKicked() {
166 reconnect_cv_.notify_one();
167}
168
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700169void ReconnectHandler::Run() {
170 while (true) {
171 ReconnectAttempt attempt;
172 {
173 std::unique_lock<std::mutex> lock(reconnect_mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800174 ScopedLockAssertion assume_lock(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700175
Josh Gao95af6412018-07-30 18:51:55 -0700176 if (!reconnect_queue_.empty()) {
177 // FIXME: libstdc++ (used on Windows) implements condition_variable with
178 // system_clock as its clock, so we're probably hosed if the clock changes,
179 // even if we use steady_clock throughout. This problem goes away once we
180 // switch to libc++.
Josh Gao8a40c8a2018-08-10 14:28:24 -0700181 reconnect_cv_.wait_until(lock, reconnect_queue_.begin()->reconnect_time);
Josh Gao95af6412018-07-30 18:51:55 -0700182 } else {
183 reconnect_cv_.wait(lock);
184 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700185
186 if (!running_) return;
Josh Gao902dace2018-08-10 14:44:54 -0700187
188 // Scan the whole list for kicked transports, so that we immediately handle an explicit
189 // disconnect request.
190 bool kicked = false;
191 for (auto it = reconnect_queue_.begin(); it != reconnect_queue_.end();) {
192 if (it->transport->kicked()) {
193 D("transport %s was kicked. giving up on it.", it->transport->serial.c_str());
194 remove_transport(it->transport);
195 it = reconnect_queue_.erase(it);
196 } else {
197 ++it;
198 }
199 kicked = true;
200 }
201
Josh Gao95af6412018-07-30 18:51:55 -0700202 if (reconnect_queue_.empty()) continue;
203
Josh Gao902dace2018-08-10 14:44:54 -0700204 // Go back to sleep if we either woke up spuriously, or we were woken up to remove
205 // a kicked transport, and the first transport isn't ready for reconnection yet.
Josh Gao95af6412018-07-30 18:51:55 -0700206 auto now = std::chrono::steady_clock::now();
Josh Gao8a40c8a2018-08-10 14:28:24 -0700207 if (reconnect_queue_.begin()->reconnect_time > now) {
Josh Gao95af6412018-07-30 18:51:55 -0700208 continue;
209 }
210
Josh Gao8a40c8a2018-08-10 14:28:24 -0700211 attempt = *reconnect_queue_.begin();
212 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700213 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700214 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700215
Josh Gaofc2e56f2018-08-30 11:37:00 -0700216 switch (attempt.transport->Reconnect()) {
217 case ReconnectResult::Retry: {
218 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
219 if (attempt.attempts_left == 0) {
220 D("transport %s exceeded the number of retry attempts. giving up on it.",
221 attempt.transport->serial.c_str());
222 remove_transport(attempt.transport);
223 continue;
224 }
225
226 std::lock_guard<std::mutex> lock(reconnect_mutex_);
227 reconnect_queue_.emplace(ReconnectAttempt{
228 attempt.transport,
229 std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
230 attempt.attempts_left - 1});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700231 continue;
232 }
233
Josh Gaofc2e56f2018-08-30 11:37:00 -0700234 case ReconnectResult::Success:
235 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
236 register_transport(attempt.transport);
237 continue;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700238
Josh Gaofc2e56f2018-08-30 11:37:00 -0700239 case ReconnectResult::Abort:
240 D("cancelling reconnection attempt to %s.", attempt.transport->serial.c_str());
241 remove_transport(attempt.transport);
242 continue;
243 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700244 }
245}
246
247static auto& reconnect_handler = *new ReconnectHandler();
248
Josh Gaodef91c02018-07-31 18:28:32 -0700249#endif
250
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700251} // namespace
252
Josh Gaob122b172017-08-16 16:57:01 -0700253TransportId NextTransportId() {
254 static std::atomic<TransportId> next(1);
255 return next++;
256}
257
Josh Gao0bbf69c2018-02-16 13:24:58 -0800258BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
259 : underlying_(std::move(connection)) {}
260
261BlockingConnectionAdapter::~BlockingConnectionAdapter() {
262 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
263 Stop();
264}
265
266void BlockingConnectionAdapter::Start() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700267 std::lock_guard<std::mutex> lock(mutex_);
268 if (started_) {
269 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
270 << "): started multiple times";
271 }
272
Josh Gao0bbf69c2018-02-16 13:24:58 -0800273 read_thread_ = std::thread([this]() {
274 LOG(INFO) << this->transport_name_ << ": read thread spawning";
275 while (true) {
Josh Gao31b5be62018-03-07 16:51:08 -0800276 auto packet = std::make_unique<apacket>();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800277 if (!underlying_->Read(packet.get())) {
278 PLOG(INFO) << this->transport_name_ << ": read failed";
279 break;
280 }
281 read_callback_(this, std::move(packet));
282 }
283 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
284 });
285
286 write_thread_ = std::thread([this]() {
287 LOG(INFO) << this->transport_name_ << ": write thread spawning";
288 while (true) {
289 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800290 ScopedLockAssertion assume_locked(mutex_);
Josh Gaoc251ec52018-04-03 12:55:18 -0700291 cv_.wait(lock, [this]() REQUIRES(mutex_) {
292 return this->stopped_ || !this->write_queue_.empty();
293 });
294
Josh Gao0bbf69c2018-02-16 13:24:58 -0800295 if (this->stopped_) {
296 return;
297 }
298
299 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
300 this->write_queue_.pop_front();
301 lock.unlock();
302
303 if (!this->underlying_->Write(packet.get())) {
304 break;
305 }
306 }
307 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
308 });
Josh Gaoc251ec52018-04-03 12:55:18 -0700309
310 started_ = true;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800311}
312
313void BlockingConnectionAdapter::Stop() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700314 {
315 std::lock_guard<std::mutex> lock(mutex_);
316 if (!started_) {
317 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
318 return;
319 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800320
Josh Gaoc251ec52018-04-03 12:55:18 -0700321 if (stopped_) {
322 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
323 << "): already stopped";
324 return;
325 }
326
327 stopped_ = true;
328 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800329
330 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
331
332 this->underlying_->Close();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800333 this->cv_.notify_one();
Josh Gaoc251ec52018-04-03 12:55:18 -0700334
335 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
336 std::thread read_thread;
337 std::thread write_thread;
338
339 {
340 std::lock_guard<std::mutex> lock(mutex_);
341 read_thread = std::move(read_thread_);
342 write_thread = std::move(write_thread_);
343 }
344
345 read_thread.join();
346 write_thread.join();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800347
348 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
349 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
350}
351
352bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
353 {
Josh Gaoc251ec52018-04-03 12:55:18 -0700354 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800355 write_queue_.emplace_back(std::move(packet));
356 }
357
358 cv_.notify_one();
359 return true;
360}
361
Josh Gaob800d882018-01-28 20:32:46 -0800362bool FdConnection::Read(apacket* packet) {
363 if (!ReadFdExactly(fd_.get(), &packet->msg, sizeof(amessage))) {
364 D("remote local: read terminated (message)");
365 return false;
366 }
367
Josh Gaof571fcb2018-02-05 18:49:10 -0800368 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gao5caaebd2018-02-02 14:38:04 -0800369 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
370 return false;
371 }
372
Josh Gaof571fcb2018-02-05 18:49:10 -0800373 packet->payload.resize(packet->msg.data_length);
374
375 if (!ReadFdExactly(fd_.get(), &packet->payload[0], packet->payload.size())) {
Josh Gaob800d882018-01-28 20:32:46 -0800376 D("remote local: terminated (data)");
377 return false;
378 }
379
380 return true;
381}
382
383bool FdConnection::Write(apacket* packet) {
Josh Gaof571fcb2018-02-05 18:49:10 -0800384 if (!WriteFdExactly(fd_.get(), &packet->msg, sizeof(packet->msg))) {
Josh Gaob800d882018-01-28 20:32:46 -0800385 D("remote local: write terminated");
386 return false;
387 }
388
Josh Gaof571fcb2018-02-05 18:49:10 -0800389 if (packet->msg.data_length) {
390 if (!WriteFdExactly(fd_.get(), &packet->payload[0], packet->msg.data_length)) {
391 D("remote local: write terminated");
392 return false;
393 }
394 }
395
Josh Gaob800d882018-01-28 20:32:46 -0800396 return true;
397}
398
399void FdConnection::Close() {
400 adb_shutdown(fd_.get());
401 fd_.reset();
402}
403
Josh Gao06d61d42016-10-06 13:31:44 -0700404void send_packet(apacket* p, atransport* t) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800405 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayde471942017-12-07 11:40:00 -0800406 // compute a checksum for connection/auth packets for compatibility reasons
407 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
408 p->msg.data_check = 0;
409 } else {
410 p->msg.data_check = calculate_apacket_checksum(p);
411 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800412
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700413 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800414
Yi Kongaed415c2018-07-13 18:15:16 -0700415 if (t == nullptr) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700416 LOG(FATAL) << "Transport is null";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800417 }
418
Josh Gao0bbf69c2018-02-16 13:24:58 -0800419 if (t->Write(p) != 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700420 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800421 t->Kick();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800422 }
423}
424
Yabin Cuif4b99282015-08-27 12:03:11 -0700425void kick_transport(atransport* t) {
Josh Gao1db71af2017-08-17 13:50:51 -0700426 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui1f4ec192016-04-05 13:50:44 -0700427 // As kick_transport() can be called from threads without guarantee that t is valid,
428 // check if the transport is in transport_list first.
Josh Gaob122b172017-08-16 16:57:01 -0700429 //
430 // TODO(jmgao): WTF? Is this actually true?
Yabin Cui1f4ec192016-04-05 13:50:44 -0700431 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Yabin Cui7f274902016-04-18 11:22:34 -0700432 t->Kick();
Yabin Cui1f4ec192016-04-05 13:50:44 -0700433 }
Josh Gao902dace2018-08-10 14:44:54 -0700434
435#if ADB_HOST
436 reconnect_handler.CheckForKicked();
437#endif
Yabin Cuif4b99282015-08-27 12:03:11 -0700438}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800439
440static int transport_registration_send = -1;
441static int transport_registration_recv = -1;
Josh Gao71f775a2018-05-14 11:14:33 -0700442static fdevent* transport_registration_fde;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800443
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800444#if ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800445
446/* this adds support required by the 'track-devices' service.
447 * this is used to send the content of "list_transport" to any
448 * number of client connections that want it through a single
449 * live TCP connection
450 */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800451struct device_tracker {
Josh Gao1290fbf2016-11-22 14:32:34 -0800452 asocket socket;
Josh Gaoe0361d12018-02-12 17:24:00 -0800453 bool update_needed = false;
454 bool long_output = false;
455 device_tracker* next = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800456};
457
458/* linked list of all device trackers */
Josh Gao1290fbf2016-11-22 14:32:34 -0800459static device_tracker* device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800460
Josh Gao1290fbf2016-11-22 14:32:34 -0800461static void device_tracker_remove(device_tracker* tracker) {
462 device_tracker** pnode = &device_tracker_list;
463 device_tracker* node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800464
Josh Gao1db71af2017-08-17 13:50:51 -0700465 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800466 while (node) {
467 if (node == tracker) {
468 *pnode = node->next;
469 break;
470 }
471 pnode = &node->next;
Josh Gao1290fbf2016-11-22 14:32:34 -0800472 node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800473 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800474}
475
Josh Gao1290fbf2016-11-22 14:32:34 -0800476static void device_tracker_close(asocket* socket) {
477 device_tracker* tracker = (device_tracker*)socket;
478 asocket* peer = socket->peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800479
Josh Gao1290fbf2016-11-22 14:32:34 -0800480 D("device tracker %p removed", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800481 if (peer) {
Yi Kongaed415c2018-07-13 18:15:16 -0700482 peer->peer = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800483 peer->close(peer);
484 }
485 device_tracker_remove(tracker);
Josh Gaoe0361d12018-02-12 17:24:00 -0800486 delete tracker;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800487}
488
Josh Gao1ce99572018-03-07 16:52:28 -0800489static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800490 /* you can't read from a device tracker, close immediately */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800491 device_tracker_close(socket);
492 return -1;
493}
494
Elliott Hughese67f1f82015-04-30 17:32:03 -0700495static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700496 asocket* peer = tracker->socket.peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800497
Josh Gao1ce99572018-03-07 16:52:28 -0800498 apacket::payload_type data;
Josh Gao27cb7dc2018-02-01 13:17:50 -0800499 data.resize(4 + string.size());
500 char buf[5];
501 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
502 memcpy(&data[0], buf, 4);
503 memcpy(&data[4], string.data(), string.size());
504 return peer->enqueue(peer, std::move(data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800505}
506
Elliott Hughese67f1f82015-04-30 17:32:03 -0700507static void device_tracker_ready(asocket* socket) {
508 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800509
Elliott Hughese67f1f82015-04-30 17:32:03 -0700510 // We want to send the device list when the tracker connects
511 // for the first time, even if no update occurred.
Josh Gaob0c18022017-08-14 18:57:54 -0700512 if (tracker->update_needed) {
513 tracker->update_needed = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800514
Josh Gaob0c18022017-08-14 18:57:54 -0700515 std::string transports = list_transports(tracker->long_output);
Elliott Hughese67f1f82015-04-30 17:32:03 -0700516 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800517 }
518}
519
Josh Gaob0c18022017-08-14 18:57:54 -0700520asocket* create_device_tracker(bool long_output) {
Josh Gaoe0361d12018-02-12 17:24:00 -0800521 device_tracker* tracker = new device_tracker();
Elliott Hughes4679a392018-10-19 13:59:44 -0700522 if (tracker == nullptr) LOG(FATAL) << "cannot allocate device tracker";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800523
Josh Gao1290fbf2016-11-22 14:32:34 -0800524 D("device tracker %p created", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800525
526 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao1290fbf2016-11-22 14:32:34 -0800527 tracker->socket.ready = device_tracker_ready;
528 tracker->socket.close = device_tracker_close;
Josh Gaob0c18022017-08-14 18:57:54 -0700529 tracker->update_needed = true;
530 tracker->long_output = long_output;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800531
Josh Gao1290fbf2016-11-22 14:32:34 -0800532 tracker->next = device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800533 device_tracker_list = tracker;
534
535 return &tracker->socket;
536}
537
Josh Gaofd713e52017-05-03 22:37:10 -0700538// Check if all of the USB transports are connected.
539bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gao1db71af2017-08-17 13:50:51 -0700540 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaofd713e52017-05-03 22:37:10 -0700541 for (const auto& t : transport_list) {
542 if (!fn(t)) {
543 return false;
544 }
545 }
546 for (const auto& t : pending_list) {
547 if (!fn(t)) {
548 return false;
549 }
550 }
551 return true;
552}
553
Elliott Hughese67f1f82015-04-30 17:32:03 -0700554// Call this function each time the transport list has changed.
555void update_transports() {
Josh Gaofd713e52017-05-03 22:37:10 -0700556 update_transport_status();
557
558 // Notify `adb track-devices` clients.
Elliott Hughese67f1f82015-04-30 17:32:03 -0700559 std::string transports = list_transports(false);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800560
Elliott Hughese67f1f82015-04-30 17:32:03 -0700561 device_tracker* tracker = device_tracker_list;
562 while (tracker != nullptr) {
563 device_tracker* next = tracker->next;
564 // This may destroy the tracker if the connection is closed.
565 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800566 tracker = next;
567 }
568}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700569
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800570#else
Elliott Hughese67f1f82015-04-30 17:32:03 -0700571
572void update_transports() {
573 // Nothing to do on the device side.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800574}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700575
Josh Gao1290fbf2016-11-22 14:32:34 -0800576#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800577
Josh Gao1290fbf2016-11-22 14:32:34 -0800578struct tmsg {
579 atransport* transport;
580 int action;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800581};
582
Josh Gao1290fbf2016-11-22 14:32:34 -0800583static int transport_read_action(int fd, struct tmsg* m) {
584 char* p = (char*)m;
585 int len = sizeof(*m);
586 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800587
Josh Gao1290fbf2016-11-22 14:32:34 -0800588 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800589 r = adb_read(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800590 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800591 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800592 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800593 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700594 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800595 return -1;
596 }
597 }
598 return 0;
599}
600
Josh Gao1290fbf2016-11-22 14:32:34 -0800601static int transport_write_action(int fd, struct tmsg* m) {
602 char* p = (char*)m;
603 int len = sizeof(*m);
604 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800605
Josh Gao1290fbf2016-11-22 14:32:34 -0800606 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800607 r = adb_write(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800608 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800609 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800610 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800611 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700612 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800613 return -1;
614 }
615 }
616 return 0;
617}
618
Josh Gao0bbf69c2018-02-16 13:24:58 -0800619static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800620 tmsg m;
Josh Gao1290fbf2016-11-22 14:32:34 -0800621 atransport* t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800622
Josh Gao1290fbf2016-11-22 14:32:34 -0800623 if (!(ev & FDE_READ)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800624 return;
625 }
626
Josh Gao1290fbf2016-11-22 14:32:34 -0800627 if (transport_read_action(_fd, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700628 PLOG(FATAL) << "cannot read transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800629 }
630
631 t = m.transport;
632
Dan Albert1792c232015-05-18 13:06:53 -0700633 if (m.action == 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700634 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800635
Josh Gao0cd3ae12016-09-21 12:37:10 -0700636 {
Josh Gao1db71af2017-08-17 13:50:51 -0700637 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700638 transport_list.remove(t);
639 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800640
Dan Albertc7915a32015-05-18 16:46:31 -0700641 delete t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800642
643 update_transports();
644 return;
645 }
646
Mike Lockwood0927bf92009-08-08 12:37:44 -0400647 /* don't create transport threads for inaccessible devices */
Yabin Cuib5e11412017-03-10 16:01:01 -0800648 if (t->GetConnectionState() != kCsNoPerm) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700649 // The connection gets a reference to the atransport. It will release it
650 // upon a read/write error.
651 t->ref_count++;
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700652 t->connection()->SetTransportName(t->serial_name());
653 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao0bbf69c2018-02-16 13:24:58 -0800654 if (!check_header(p.get(), t)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700655 D("%s: remote read: bad header", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800656 return false;
657 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800658
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700659 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "from remote", p.get());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800660 apacket* packet = p.release();
Mike Lockwood0927bf92009-08-08 12:37:44 -0400661
Josh Gao0bbf69c2018-02-16 13:24:58 -0800662 // TODO: Does this need to run on the main thread?
663 fdevent_run_on_main_thread([packet, t]() { handle_packet(packet, t); });
664 return true;
665 });
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700666 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700667 LOG(INFO) << t->serial_name() << ": connection terminated: " << error;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800668 fdevent_run_on_main_thread([t]() {
669 handle_offline(t);
670 transport_unref(t);
671 });
672 });
Mike Lockwood0927bf92009-08-08 12:37:44 -0400673
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700674 t->connection()->Start();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800675#if ADB_HOST
676 send_connect(t);
677#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800678 }
679
Josh Gao0cd3ae12016-09-21 12:37:10 -0700680 {
Josh Gao1db71af2017-08-17 13:50:51 -0700681 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700682 auto it = std::find(pending_list.begin(), pending_list.end(), t);
683 if (it != pending_list.end()) {
684 pending_list.remove(t);
685 transport_list.push_front(t);
686 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700687 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800688
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800689 update_transports();
690}
691
Josh Gaodef91c02018-07-31 18:28:32 -0700692#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700693void init_reconnect_handler(void) {
694 reconnect_handler.Start();
695}
Josh Gaodef91c02018-07-31 18:28:32 -0700696#endif
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700697
Josh Gao1290fbf2016-11-22 14:32:34 -0800698void init_transport_registration(void) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800699 int s[2];
700
Josh Gao1290fbf2016-11-22 14:32:34 -0800701 if (adb_socketpair(s)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700702 PLOG(FATAL) << "cannot open transport registration socketpair";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800703 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700704 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800705
706 transport_registration_send = s[0];
707 transport_registration_recv = s[1];
708
Josh Gao71f775a2018-05-14 11:14:33 -0700709 transport_registration_fde =
Yi Kongaed415c2018-07-13 18:15:16 -0700710 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao71f775a2018-05-14 11:14:33 -0700711 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao01b7bc42017-05-09 13:43:35 -0700712}
713
714void kick_all_transports() {
Josh Gaodef91c02018-07-31 18:28:32 -0700715#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700716 reconnect_handler.Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700717#endif
Josh Gao01b7bc42017-05-09 13:43:35 -0700718 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gao1db71af2017-08-17 13:50:51 -0700719 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao01b7bc42017-05-09 13:43:35 -0700720 for (auto t : transport_list) {
721 t->Kick();
722 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800723}
724
725/* the fdevent select pump is single threaded */
Josh Gaoc51726c2018-10-11 16:33:05 -0700726void register_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800727 tmsg m;
728 m.transport = transport;
729 m.action = 1;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700730 D("transport: %s registered", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800731 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700732 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800733 }
734}
735
Josh Gao1290fbf2016-11-22 14:32:34 -0800736static void remove_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800737 tmsg m;
738 m.transport = transport;
739 m.action = 0;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700740 D("transport: %s removed", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800741 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700742 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800743 }
744}
745
Yabin Cuif4b99282015-08-27 12:03:11 -0700746static void transport_unref(atransport* t) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700747 check_main_thread();
Yabin Cuif4b99282015-08-27 12:03:11 -0700748 CHECK(t != nullptr);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700749
Josh Gaoe48ecce2017-09-13 13:40:57 -0700750 std::lock_guard<std::recursive_mutex> lock(transport_lock);
751 CHECK_GT(t->ref_count, 0u);
752 t->ref_count--;
753 if (t->ref_count == 0) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700754 LOG(INFO) << "destroying transport " << t->serial_name();
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700755 t->connection()->Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700756#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700757 if (t->IsTcpDevice() && !t->kicked()) {
Josh Gaodef91c02018-07-31 18:28:32 -0700758 D("transport: %s unref (attempting reconnection)", t->serial.c_str());
Josh Gao4414e4c2018-12-04 01:07:50 -0800759
760 // We need to clear the transport's keys, so that on the next connection, it tries
761 // again from the beginning.
762 t->ResetKeys();
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700763 reconnect_handler.TrackTransport(t);
764 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700765 D("transport: %s unref (kicking and closing)", t->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700766 remove_transport(t);
767 }
Josh Gaodef91c02018-07-31 18:28:32 -0700768#else
769 D("transport: %s unref (kicking and closing)", t->serial.c_str());
770 remove_transport(t);
771#endif
772
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100773 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700774 D("transport: %s unref (count=%zu)", t->serial.c_str(), t->ref_count);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -0400775 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800776}
777
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700778static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao1290fbf2016-11-22 14:32:34 -0800779 bool sanitize_qual) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700780 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
781 return qual.empty();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700782
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700783 if (qual.empty()) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700784
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700785 const char* ptr = to_test.c_str();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700786 if (prefix) {
787 while (*prefix) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700788 if (*prefix++ != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700789 }
790 }
791
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700792 for (char ch : qual) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800793 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700794 if (ch != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700795 }
796
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700797 /* Everything matched so far. Return true if *ptr is a NUL. */
798 return !*ptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700799}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800800
Josh Gaob122b172017-08-16 16:57:01 -0700801atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
802 bool* is_ambiguous, std::string* error_out,
803 bool accept_any_state) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700804 atransport* result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800805
Josh Gaob122b172017-08-16 16:57:01 -0700806 if (transport_id != 0) {
807 *error_out =
808 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
809 } else if (serial) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700810 *error_out = android::base::StringPrintf("device '%s' not found", serial);
811 } else if (type == kTransportLocal) {
812 *error_out = "no emulators found";
813 } else if (type == kTransportAny) {
814 *error_out = "no devices/emulators found";
815 } else {
816 *error_out = "no devices found";
817 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800818
Josh Gao1db71af2017-08-17 13:50:51 -0700819 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes8d28e192015-10-07 14:55:10 -0700820 for (const auto& t : transport_list) {
Yabin Cuib5e11412017-03-10 16:01:01 -0800821 if (t->GetConnectionState() == kCsNoPerm) {
David Purselld2acbd12015-12-02 15:14:31 -0800822 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwood37d31112009-08-08 13:53:16 -0400823 continue;
824 }
Mike Lockwood0927bf92009-08-08 12:37:44 -0400825
Josh Gaob122b172017-08-16 16:57:01 -0700826 if (transport_id) {
827 if (t->id == transport_id) {
828 result = t;
829 break;
830 }
831 } else if (serial) {
David Pursell3f902aa2016-03-01 08:58:26 -0800832 if (t->MatchesTarget(serial)) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700833 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700834 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700835 if (is_ambiguous) *is_ambiguous = true;
836 result = nullptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700837 break;
838 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800839 result = t;
Scott Andersone109d262012-04-20 11:21:14 -0700840 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800841 } else {
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700842 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800843 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700844 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700845 if (is_ambiguous) *is_ambiguous = true;
846 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800847 break;
848 }
849 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700850 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800851 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700852 *error_out = "more than one emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700853 if (is_ambiguous) *is_ambiguous = true;
854 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800855 break;
856 }
857 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700858 } else if (type == kTransportAny) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800859 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700860 *error_out = "more than one device/emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700861 if (is_ambiguous) *is_ambiguous = true;
862 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800863 break;
864 }
865 result = t;
866 }
867 }
868 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700869 lock.unlock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800870
Josh Gao704494b2018-05-04 16:04:49 -0700871 if (result && !accept_any_state) {
872 // The caller requires an active transport.
873 // Make sure that we're actually connected.
874 ConnectionState state = result->GetConnectionState();
875 switch (state) {
876 case kCsConnecting:
877 *error_out = "device still connecting";
878 result = nullptr;
879 break;
Benoit Goby77e8e582013-01-15 12:36:47 -0800880
Josh Gao704494b2018-05-04 16:04:49 -0700881 case kCsAuthorizing:
882 *error_out = "device still authorizing";
883 result = nullptr;
884 break;
885
886 case kCsUnauthorized: {
887 *error_out = "device unauthorized.\n";
888 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
889 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
890 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
891 *error_out += "\n";
892 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
893 *error_out += "Otherwise check for a confirmation dialog on your device.";
894 result = nullptr;
895 break;
896 }
897
898 case kCsOffline:
899 *error_out = "device offline";
900 result = nullptr;
901 break;
902
903 default:
904 break;
905 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800906 }
907
908 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700909 *error_out = "success";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800910 }
911
912 return result;
913}
914
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700915bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
916 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800917 ScopedLockAssertion assume_locked(mutex_);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700918 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
919 return connection_established_ready_;
920 }) && connection_established_;
921}
922
923void ConnectionWaitable::SetConnectionEstablished(bool success) {
924 {
925 std::lock_guard<std::mutex> lock(mutex_);
926 if (connection_established_ready_) return;
927 connection_established_ready_ = true;
928 connection_established_ = success;
929 D("connection established with %d", success);
930 }
931 cv_.notify_one();
932}
933
934atransport::~atransport() {
935 // If the connection callback had not been run before, run it now.
936 SetConnectionEstablished(false);
937}
938
Yabin Cuib5e11412017-03-10 16:01:01 -0800939int atransport::Write(apacket* p) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700940 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cuib5e11412017-03-10 16:01:01 -0800941}
942
Yabin Cui7f274902016-04-18 11:22:34 -0700943void atransport::Kick() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700944 if (!kicked_.exchange(true)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700945 D("kicking transport %p %s", this, this->serial.c_str());
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700946 this->connection()->Stop();
Yabin Cui7f274902016-04-18 11:22:34 -0700947 }
948}
949
Yabin Cuib5e11412017-03-10 16:01:01 -0800950ConnectionState atransport::GetConnectionState() const {
951 return connection_state_;
952}
953
954void atransport::SetConnectionState(ConnectionState state) {
955 check_main_thread();
956 connection_state_ = state;
957}
958
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700959void atransport::SetConnection(std::unique_ptr<Connection> connection) {
960 std::lock_guard<std::mutex> lock(mutex_);
961 connection_ = std::shared_ptr<Connection>(std::move(connection));
962}
963
Josh Gaoffbd3362018-02-28 14:44:23 -0800964std::string atransport::connection_state_name() const {
Yabin Cuib5e11412017-03-10 16:01:01 -0800965 ConnectionState state = GetConnectionState();
966 switch (state) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800967 case kCsOffline:
968 return "offline";
969 case kCsBootloader:
970 return "bootloader";
971 case kCsDevice:
972 return "device";
973 case kCsHost:
974 return "host";
975 case kCsRecovery:
976 return "recovery";
977 case kCsNoPerm:
978 return UsbNoPermissionsShortHelpText();
979 case kCsSideload:
980 return "sideload";
981 case kCsUnauthorized:
982 return "unauthorized";
Josh Gao704494b2018-05-04 16:04:49 -0700983 case kCsAuthorizing:
984 return "authorizing";
985 case kCsConnecting:
986 return "connecting";
Josh Gao1290fbf2016-11-22 14:32:34 -0800987 default:
988 return "unknown";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800989 }
990}
991
Tamas Berghammer3d2904c2015-07-13 19:12:28 +0100992void atransport::update_version(int version, size_t payload) {
993 protocol_version = std::min(version, A_VERSION);
994 max_payload = std::min(payload, MAX_PAYLOAD);
995}
996
997int atransport::get_protocol_version() const {
998 return protocol_version;
999}
1000
1001size_t atransport::get_max_payload() const {
1002 return max_payload;
1003}
1004
Dan Albert1792c232015-05-18 13:06:53 -07001005const FeatureSet& supported_features() {
David Pursell4e2fd362015-09-22 10:43:08 -07001006 // Local static allocation to avoid global non-POD variables.
1007 static const FeatureSet* features = new FeatureSet{
Alex Buynytskyy01a65ee2019-01-17 13:13:56 -08001008 kFeatureShell2, kFeatureCmd, kFeatureStat2,
1009 kFeatureFixedPushMkdir, kFeatureApex, kFeatureAbb,
Josh Gao919b70c2018-11-08 22:39:43 -08001010 // Increment ADB_SERVER_VERSION when adding a feature that adbd needs
1011 // to know about. Otherwise, the client can be stuck running an old
1012 // version of the server even after upgrading their copy of adb.
1013 // (http://b/24370690)
David Pursell4e2fd362015-09-22 10:43:08 -07001014 };
1015
1016 return *features;
1017}
1018
1019std::string FeatureSetToString(const FeatureSet& features) {
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001020 return android::base::Join(features, ',');
David Pursell4e2fd362015-09-22 10:43:08 -07001021}
1022
1023FeatureSet StringToFeatureSet(const std::string& features_string) {
David Purselld2b588e2015-09-25 13:04:21 -07001024 if (features_string.empty()) {
1025 return FeatureSet();
1026 }
1027
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001028 auto names = android::base::Split(features_string, ",");
David Pursell4e2fd362015-09-22 10:43:08 -07001029 return FeatureSet(names.begin(), names.end());
Dan Albert1792c232015-05-18 13:06:53 -07001030}
1031
David Pursell70ef7b42015-09-30 13:35:42 -07001032bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001033 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell70ef7b42015-09-30 13:35:42 -07001034}
1035
Dan Albert1792c232015-05-18 13:06:53 -07001036bool atransport::has_feature(const std::string& feature) const {
1037 return features_.count(feature) > 0;
1038}
1039
David Pursell4e2fd362015-09-22 10:43:08 -07001040void atransport::SetFeatures(const std::string& features_string) {
1041 features_ = StringToFeatureSet(features_string);
Dan Albert1792c232015-05-18 13:06:53 -07001042}
1043
Yabin Cuib3298242015-08-28 15:09:44 -07001044void atransport::AddDisconnect(adisconnect* disconnect) {
1045 disconnects_.push_back(disconnect);
1046}
1047
1048void atransport::RemoveDisconnect(adisconnect* disconnect) {
1049 disconnects_.remove(disconnect);
1050}
1051
1052void atransport::RunDisconnects() {
Elliott Hughes65fe2512015-10-07 15:59:35 -07001053 for (const auto& disconnect : disconnects_) {
Yabin Cuib3298242015-08-28 15:09:44 -07001054 disconnect->func(disconnect->opaque, this);
1055 }
1056 disconnects_.clear();
1057}
1058
David Pursell3f902aa2016-03-01 08:58:26 -08001059bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001060 if (!serial.empty()) {
David Pursell3f902aa2016-03-01 08:58:26 -08001061 if (target == serial) {
1062 return true;
1063 } else if (type == kTransportLocal) {
1064 // Local transports can match [tcp:|udp:]<hostname>[:port].
1065 const char* local_target_ptr = target.c_str();
1066
1067 // For fastboot compatibility, ignore protocol prefixes.
1068 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao1290fbf2016-11-22 14:32:34 -08001069 android::base::StartsWith(target, "udp:")) {
David Pursell3f902aa2016-03-01 08:58:26 -08001070 local_target_ptr += 4;
1071 }
1072
1073 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1074 std::string serial_host, error;
1075 int serial_port = -1;
Josh Gao1290fbf2016-11-22 14:32:34 -08001076 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursell3f902aa2016-03-01 08:58:26 -08001077 // |target| may omit the port to default to ours.
1078 std::string target_host;
1079 int target_port = serial_port;
1080 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1081 nullptr, &error) &&
Josh Gao1290fbf2016-11-22 14:32:34 -08001082 serial_host == target_host && serial_port == target_port) {
David Pursell3f902aa2016-03-01 08:58:26 -08001083 return true;
1084 }
1085 }
1086 }
1087 }
1088
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001089 return (target == devpath) || qual_match(target, "product:", product, false) ||
1090 qual_match(target, "model:", model, true) ||
1091 qual_match(target, "device:", device, false);
David Pursell3f902aa2016-03-01 08:58:26 -08001092}
1093
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001094void atransport::SetConnectionEstablished(bool success) {
1095 connection_waitable_->SetConnectionEstablished(success);
1096}
1097
Josh Gaofc2e56f2018-08-30 11:37:00 -07001098ReconnectResult atransport::Reconnect() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001099 return reconnect_(this);
1100}
1101
Elliott Hughese67f1f82015-04-30 17:32:03 -07001102#if ADB_HOST
1103
Josh Gaob122b172017-08-16 16:57:01 -07001104// We use newline as our delimiter, make sure to never output it.
1105static std::string sanitize(std::string str, bool alphanumeric) {
1106 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1107 : [](const char c) { return c == '\n'; };
1108 std::replace_if(str.begin(), str.end(), pred, '_');
1109 return str;
1110}
1111
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001112static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob122b172017-08-16 16:57:01 -07001113 bool alphanumeric) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001114 if (value.empty()) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001115 return;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001116 }
1117
Elliott Hughese67f1f82015-04-30 17:32:03 -07001118 *result += ' ';
1119 *result += key;
Josh Gaob122b172017-08-16 16:57:01 -07001120 *result += sanitize(value, alphanumeric);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001121}
1122
Josh Gao1290fbf2016-11-22 14:32:34 -08001123static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001124 std::string serial = t->serial;
1125 if (serial.empty()) {
Dan Albertd99d9022015-05-06 16:48:52 -07001126 serial = "(no serial number)";
Elliott Hughese67f1f82015-04-30 17:32:03 -07001127 }
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001128
1129 if (!long_listing) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001130 *result += serial;
1131 *result += '\t';
1132 *result += t->connection_state_name();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001133 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001134 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1135 t->connection_state_name().c_str());
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001136
Elliott Hughese67f1f82015-04-30 17:32:03 -07001137 append_transport_info(result, "", t->devpath, false);
1138 append_transport_info(result, "product:", t->product, false);
1139 append_transport_info(result, "model:", t->model, true);
1140 append_transport_info(result, "device:", t->device, false);
Josh Gaob122b172017-08-16 16:57:01 -07001141
1142 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1143 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1144 *result += " transport_id:";
1145 *result += std::to_string(t->id);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001146 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001147 *result += '\n';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001148}
1149
Elliott Hughese67f1f82015-04-30 17:32:03 -07001150std::string list_transports(bool long_listing) {
Josh Gao1db71af2017-08-17 13:50:51 -07001151 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov04398a92017-12-17 10:56:07 +00001152
1153 auto sorted_transport_list = transport_list;
1154 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1155 if (x->type != y->type) {
1156 return x->type < y->type;
1157 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001158 return x->serial < y->serial;
Artem Iglikov04398a92017-12-17 10:56:07 +00001159 });
1160
1161 std::string result;
1162 for (const auto& t : sorted_transport_list) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001163 append_transport(t, &result, long_listing);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001164 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001165 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001166}
1167
Josh Gao22d2b3e2016-10-27 14:01:08 -07001168void close_usb_devices(std::function<bool(const atransport*)> predicate) {
Josh Gao1db71af2017-08-17 13:50:51 -07001169 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao22d2b3e2016-10-27 14:01:08 -07001170 for (auto& t : transport_list) {
1171 if (predicate(t)) {
1172 t->Kick();
1173 }
1174 }
1175}
1176
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001177/* hack for osx */
Dan Albertc7915a32015-05-18 16:46:31 -07001178void close_usb_devices() {
Josh Gao22d2b3e2016-10-27 14:01:08 -07001179 close_usb_devices([](const atransport*) { return true; });
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001180}
Josh Gao1290fbf2016-11-22 14:32:34 -08001181#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001182
Josh Gao362e6962018-08-08 16:20:14 -07001183bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
1184 atransport::ReconnectCallback reconnect, int* error) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001185 atransport* t = new atransport(std::move(reconnect), kCsOffline);
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +01001186
Josh Gao3b4de3c2018-08-02 13:58:24 -07001187 D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
Josh Gao56300c92018-07-25 17:21:49 -07001188 if (init_socket_transport(t, std::move(s), port, local) < 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001189 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001190 if (error) *error = errno;
1191 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001192 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001193
Josh Gao1db71af2017-08-17 13:50:51 -07001194 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes65fe2512015-10-07 15:59:35 -07001195 for (const auto& transport : pending_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001196 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001197 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001198 << " is already in pending_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001199 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001200 if (error) *error = EALREADY;
1201 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001202 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001203 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001204
Elliott Hughes65fe2512015-10-07 15:59:35 -07001205 for (const auto& transport : transport_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001206 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001207 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001208 << " is already in transport_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001209 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001210 if (error) *error = EALREADY;
1211 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001212 }
1213 }
1214
Josh Gao3b4de3c2018-08-02 13:58:24 -07001215 t->serial = std::move(serial);
Dan Albertc7915a32015-05-18 16:46:31 -07001216 pending_list.push_front(t);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001217
1218 lock.unlock();
Benoit Goby1c45ee92013-03-29 18:22:36 -07001219
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001220 auto waitable = t->connection_waitable();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001221 register_transport(t);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001222
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001223 if (local == 1) {
1224 // Do not wait for emulator transports.
Josh Gao362e6962018-08-08 16:20:14 -07001225 return true;
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001226 }
1227
Josh Gao362e6962018-08-08 16:20:14 -07001228 if (!waitable->WaitForConnection(std::chrono::seconds(10))) {
1229 if (error) *error = ETIMEDOUT;
1230 return false;
1231 }
1232
1233 if (t->GetConnectionState() == kCsUnauthorized) {
1234 if (error) *error = EPERM;
1235 return false;
1236 }
1237
1238 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001239}
1240
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001241#if ADB_HOST
Josh Gao1290fbf2016-11-22 14:32:34 -08001242atransport* find_transport(const char* serial) {
Dan Albertc7915a32015-05-18 16:46:31 -07001243 atransport* result = nullptr;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001244
Josh Gao1db71af2017-08-17 13:50:51 -07001245 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001246 for (auto& t : transport_list) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001247 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001248 result = t;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001249 break;
1250 }
Dan Albertc7915a32015-05-18 16:46:31 -07001251 }
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001252
Dan Albertc7915a32015-05-18 16:46:31 -07001253 return result;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001254}
1255
Yabin Cuif4b99282015-08-27 12:03:11 -07001256void kick_all_tcp_devices() {
Josh Gao1db71af2017-08-17 13:50:51 -07001257 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001258 for (auto& t : transport_list) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001259 if (t->IsTcpDevice()) {
Yabin Cuid6ab3c22015-08-31 11:50:24 -07001260 // Kicking breaks the read_transport thread of this transport out of any read, then
1261 // the read_transport thread will notify the main thread to make this transport
1262 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cuif4b99282015-08-27 12:03:11 -07001263 // Finally, this transport will be closed and freed in the main thread.
Yabin Cui7f274902016-04-18 11:22:34 -07001264 t->Kick();
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001265 }
Dan Albertc7915a32015-05-18 16:46:31 -07001266 }
Josh Gao902dace2018-08-10 14:44:54 -07001267#if ADB_HOST
1268 reconnect_handler.CheckForKicked();
1269#endif
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001270}
1271
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001272#endif
1273
Josh Gao1290fbf2016-11-22 14:32:34 -08001274void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1275 unsigned writeable) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001276 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertc7915a32015-05-18 16:46:31 -07001277
Josh Gao1290fbf2016-11-22 14:32:34 -08001278 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cuib5e11412017-03-10 16:01:01 -08001279 init_usb_transport(t, usb);
Josh Gao1290fbf2016-11-22 14:32:34 -08001280 if (serial) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001281 t->serial = serial;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001282 }
Dan Albertc7915a32015-05-18 16:46:31 -07001283
1284 if (devpath) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001285 t->devpath = devpath;
Scott Andersone109d262012-04-20 11:21:14 -07001286 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001287
Josh Gao0cd3ae12016-09-21 12:37:10 -07001288 {
Josh Gao1db71af2017-08-17 13:50:51 -07001289 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001290 pending_list.push_front(t);
1291 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001292
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001293 register_transport(t);
1294}
1295
Josh Gaoc51726c2018-10-11 16:33:05 -07001296#if ADB_HOST
Dan Albertdcd78a12015-05-18 16:43:57 -07001297// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao1290fbf2016-11-22 14:32:34 -08001298void unregister_usb_transport(usb_handle* usb) {
Josh Gao1db71af2017-08-17 13:50:51 -07001299 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaob800d882018-01-28 20:32:46 -08001300 transport_list.remove_if([usb](atransport* t) {
Josh Gaoce5ce872018-12-11 13:11:52 -08001301 return t->GetUsbHandle() == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gaob800d882018-01-28 20:32:46 -08001302 });
Mike Lockwood0927bf92009-08-08 12:37:44 -04001303}
Josh Gaoc51726c2018-10-11 16:33:05 -07001304#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001305
Josh Gao36dadca2017-05-16 15:02:45 -07001306bool check_header(apacket* p, atransport* t) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001307 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cuib5e11412017-03-10 16:01:01 -08001308 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1309 << ", magic = " << p->msg.magic;
Josh Gao36dadca2017-05-16 15:02:45 -07001310 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001311 }
1312
Josh Gao1290fbf2016-11-22 14:32:34 -08001313 if (p->msg.data_length > t->get_max_payload()) {
1314 VLOG(RWX) << "check_header(): " << p->msg.data_length
1315 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao36dadca2017-05-16 15:02:45 -07001316 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001317 }
1318
Josh Gao36dadca2017-05-16 15:02:45 -07001319 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001320}
1321
Josh Gao3bd28792016-10-05 19:02:29 -07001322#if ADB_HOST
Josh Gao2e671202016-08-18 22:00:12 -07001323std::shared_ptr<RSA> atransport::NextKey() {
Josh Gao4414e4c2018-12-04 01:07:50 -08001324 if (keys_.empty()) {
1325 LOG(INFO) << "fetching keys for transport " << this->serial_name();
1326 keys_ = adb_auth_get_private_keys();
1327
1328 // We should have gotten at least one key: the one that's automatically generated.
1329 CHECK(!keys_.empty());
1330 }
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001331
Josh Gao2e671202016-08-18 22:00:12 -07001332 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001333 keys_.pop_front();
1334 return result;
1335}
Josh Gao4414e4c2018-12-04 01:07:50 -08001336
1337void atransport::ResetKeys() {
1338 keys_.clear();
1339}
Josh Gao3bd28792016-10-05 19:02:29 -07001340#endif