blob: 03a9f3042d572731ef38076ce57c45dd339417a8 [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
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070055static void remove_transport(atransport* transport);
56static void transport_unref(atransport* transport);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080057
Josh Gaob122b172017-08-16 16:57:01 -070058// TODO: unordered_map<TransportId, atransport*>
Josh Gaob7b1edf2015-11-11 17:56:12 -080059static auto& transport_list = *new std::list<atransport*>();
60static auto& pending_list = *new std::list<atransport*>();
Benoit Goby1c45ee92013-03-29 18:22:36 -070061
Josh Gao1db71af2017-08-17 13:50:51 -070062static auto& transport_lock = *new std::recursive_mutex();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080063
Todd Kennedy51c05ec2015-11-10 00:03:25 +000064const char* const kFeatureShell2 = "shell_v2";
65const char* const kFeatureCmd = "cmd";
Josh Gao5a1e3fd2016-12-05 17:11:34 -080066const char* const kFeatureStat2 = "stat_v2";
Josh Gao5d1756c2017-02-22 17:07:01 -080067const char* const kFeatureLibusb = "libusb";
Dan Albert5176df82017-05-23 14:30:00 -070068const char* const kFeaturePushSync = "push_sync";
Dario Freni29814de2018-10-04 16:26:40 +010069const char* const kFeatureApex = "apex";
Josh Gaofb085102018-10-22 13:00:05 -070070const char* const kFeatureFixedPushMkdir = "fixed_push_mkdir";
Todd Kennedy51c05ec2015-11-10 00:03:25 +000071
Luis Hector Chavez56fe7532018-04-17 14:25:04 -070072namespace {
73
74// A class that helps the Clang Thread Safety Analysis deal with
75// std::unique_lock. Given that std::unique_lock is movable, and the analysis
76// can not currently perform alias analysis, it is not annotated. In order to
77// assert that the mutex is held, a ScopedAssumeLocked can be created just after
78// the std::unique_lock.
79class SCOPED_CAPABILITY ScopedAssumeLocked {
80 public:
81 ScopedAssumeLocked(std::mutex& mutex) ACQUIRE(mutex) {}
82 ~ScopedAssumeLocked() RELEASE() {}
83};
84
Josh Gaodef91c02018-07-31 18:28:32 -070085#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070086// Tracks and handles atransport*s that are attempting reconnection.
87class ReconnectHandler {
88 public:
89 ReconnectHandler() = default;
90 ~ReconnectHandler() = default;
91
92 // Starts the ReconnectHandler thread.
93 void Start();
94
95 // Requests the ReconnectHandler thread to stop.
96 void Stop();
97
98 // Adds the atransport* to the queue of reconnect attempts.
99 void TrackTransport(atransport* transport);
100
Josh Gao902dace2018-08-10 14:44:54 -0700101 // Wake up the ReconnectHandler thread to have it check for kicked transports.
102 void CheckForKicked();
103
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700104 private:
105 // The main thread loop.
106 void Run();
107
108 // Tracks a reconnection attempt.
109 struct ReconnectAttempt {
110 atransport* transport;
Josh Gao95af6412018-07-30 18:51:55 -0700111 std::chrono::steady_clock::time_point reconnect_time;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700112 size_t attempts_left;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700113
114 bool operator<(const ReconnectAttempt& rhs) const {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700115 if (reconnect_time == rhs.reconnect_time) {
116 return reinterpret_cast<uintptr_t>(transport) <
117 reinterpret_cast<uintptr_t>(rhs.transport);
118 }
119 return reconnect_time < rhs.reconnect_time;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700120 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700121 };
122
123 // Only retry for up to one minute.
Josh Gaoe445a6d2018-07-31 14:12:59 -0700124 static constexpr const std::chrono::seconds kDefaultTimeout = 10s;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700125 static constexpr const size_t kMaxAttempts = 6;
126
127 // Protects all members.
128 std::mutex reconnect_mutex_;
129 bool running_ GUARDED_BY(reconnect_mutex_) = true;
130 std::thread handler_thread_;
131 std::condition_variable reconnect_cv_;
Josh Gao8a40c8a2018-08-10 14:28:24 -0700132 std::set<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700133
134 DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
135};
136
137void ReconnectHandler::Start() {
138 check_main_thread();
139 handler_thread_ = std::thread(&ReconnectHandler::Run, this);
140}
141
142void ReconnectHandler::Stop() {
143 check_main_thread();
144 {
145 std::lock_guard<std::mutex> lock(reconnect_mutex_);
146 running_ = false;
147 }
148 reconnect_cv_.notify_one();
149 handler_thread_.join();
150
151 // Drain the queue to free all resources.
152 std::lock_guard<std::mutex> lock(reconnect_mutex_);
153 while (!reconnect_queue_.empty()) {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700154 ReconnectAttempt attempt = *reconnect_queue_.begin();
155 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700156 remove_transport(attempt.transport);
157 }
158}
159
160void ReconnectHandler::TrackTransport(atransport* transport) {
161 check_main_thread();
162 {
163 std::lock_guard<std::mutex> lock(reconnect_mutex_);
164 if (!running_) return;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700165 // Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
166 auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
167 reconnect_queue_.emplace(
168 ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700169 }
170 reconnect_cv_.notify_one();
171}
172
Josh Gao902dace2018-08-10 14:44:54 -0700173void ReconnectHandler::CheckForKicked() {
174 reconnect_cv_.notify_one();
175}
176
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700177void ReconnectHandler::Run() {
178 while (true) {
179 ReconnectAttempt attempt;
180 {
181 std::unique_lock<std::mutex> lock(reconnect_mutex_);
182 ScopedAssumeLocked assume_lock(reconnect_mutex_);
183
Josh Gao95af6412018-07-30 18:51:55 -0700184 if (!reconnect_queue_.empty()) {
185 // FIXME: libstdc++ (used on Windows) implements condition_variable with
186 // system_clock as its clock, so we're probably hosed if the clock changes,
187 // even if we use steady_clock throughout. This problem goes away once we
188 // switch to libc++.
Josh Gao8a40c8a2018-08-10 14:28:24 -0700189 reconnect_cv_.wait_until(lock, reconnect_queue_.begin()->reconnect_time);
Josh Gao95af6412018-07-30 18:51:55 -0700190 } else {
191 reconnect_cv_.wait(lock);
192 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700193
194 if (!running_) return;
Josh Gao902dace2018-08-10 14:44:54 -0700195
196 // Scan the whole list for kicked transports, so that we immediately handle an explicit
197 // disconnect request.
198 bool kicked = false;
199 for (auto it = reconnect_queue_.begin(); it != reconnect_queue_.end();) {
200 if (it->transport->kicked()) {
201 D("transport %s was kicked. giving up on it.", it->transport->serial.c_str());
202 remove_transport(it->transport);
203 it = reconnect_queue_.erase(it);
204 } else {
205 ++it;
206 }
207 kicked = true;
208 }
209
Josh Gao95af6412018-07-30 18:51:55 -0700210 if (reconnect_queue_.empty()) continue;
211
Josh Gao902dace2018-08-10 14:44:54 -0700212 // Go back to sleep if we either woke up spuriously, or we were woken up to remove
213 // a kicked transport, and the first transport isn't ready for reconnection yet.
Josh Gao95af6412018-07-30 18:51:55 -0700214 auto now = std::chrono::steady_clock::now();
Josh Gao8a40c8a2018-08-10 14:28:24 -0700215 if (reconnect_queue_.begin()->reconnect_time > now) {
Josh Gao95af6412018-07-30 18:51:55 -0700216 continue;
217 }
218
Josh Gao8a40c8a2018-08-10 14:28:24 -0700219 attempt = *reconnect_queue_.begin();
220 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700221 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700222 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700223
Josh Gaofc2e56f2018-08-30 11:37:00 -0700224 switch (attempt.transport->Reconnect()) {
225 case ReconnectResult::Retry: {
226 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
227 if (attempt.attempts_left == 0) {
228 D("transport %s exceeded the number of retry attempts. giving up on it.",
229 attempt.transport->serial.c_str());
230 remove_transport(attempt.transport);
231 continue;
232 }
233
234 std::lock_guard<std::mutex> lock(reconnect_mutex_);
235 reconnect_queue_.emplace(ReconnectAttempt{
236 attempt.transport,
237 std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
238 attempt.attempts_left - 1});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700239 continue;
240 }
241
Josh Gaofc2e56f2018-08-30 11:37:00 -0700242 case ReconnectResult::Success:
243 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
244 register_transport(attempt.transport);
245 continue;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700246
Josh Gaofc2e56f2018-08-30 11:37:00 -0700247 case ReconnectResult::Abort:
248 D("cancelling reconnection attempt to %s.", attempt.transport->serial.c_str());
249 remove_transport(attempt.transport);
250 continue;
251 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700252 }
253}
254
255static auto& reconnect_handler = *new ReconnectHandler();
256
Josh Gaodef91c02018-07-31 18:28:32 -0700257#endif
258
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700259} // namespace
260
Josh Gaob122b172017-08-16 16:57:01 -0700261TransportId NextTransportId() {
262 static std::atomic<TransportId> next(1);
263 return next++;
264}
265
Josh Gao0bbf69c2018-02-16 13:24:58 -0800266BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
267 : underlying_(std::move(connection)) {}
268
269BlockingConnectionAdapter::~BlockingConnectionAdapter() {
270 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
271 Stop();
272}
273
274void BlockingConnectionAdapter::Start() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700275 std::lock_guard<std::mutex> lock(mutex_);
276 if (started_) {
277 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
278 << "): started multiple times";
279 }
280
Josh Gao0bbf69c2018-02-16 13:24:58 -0800281 read_thread_ = std::thread([this]() {
282 LOG(INFO) << this->transport_name_ << ": read thread spawning";
283 while (true) {
Josh Gao31b5be62018-03-07 16:51:08 -0800284 auto packet = std::make_unique<apacket>();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800285 if (!underlying_->Read(packet.get())) {
286 PLOG(INFO) << this->transport_name_ << ": read failed";
287 break;
288 }
289 read_callback_(this, std::move(packet));
290 }
291 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
292 });
293
294 write_thread_ = std::thread([this]() {
295 LOG(INFO) << this->transport_name_ << ": write thread spawning";
296 while (true) {
297 std::unique_lock<std::mutex> lock(mutex_);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700298 ScopedAssumeLocked assume_locked(mutex_);
Josh Gaoc251ec52018-04-03 12:55:18 -0700299 cv_.wait(lock, [this]() REQUIRES(mutex_) {
300 return this->stopped_ || !this->write_queue_.empty();
301 });
302
Josh Gao0bbf69c2018-02-16 13:24:58 -0800303 if (this->stopped_) {
304 return;
305 }
306
307 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
308 this->write_queue_.pop_front();
309 lock.unlock();
310
311 if (!this->underlying_->Write(packet.get())) {
312 break;
313 }
314 }
315 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
316 });
Josh Gaoc251ec52018-04-03 12:55:18 -0700317
318 started_ = true;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800319}
320
321void BlockingConnectionAdapter::Stop() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700322 {
323 std::lock_guard<std::mutex> lock(mutex_);
324 if (!started_) {
325 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
326 return;
327 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800328
Josh Gaoc251ec52018-04-03 12:55:18 -0700329 if (stopped_) {
330 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
331 << "): already stopped";
332 return;
333 }
334
335 stopped_ = true;
336 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800337
338 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
339
340 this->underlying_->Close();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800341 this->cv_.notify_one();
Josh Gaoc251ec52018-04-03 12:55:18 -0700342
343 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
344 std::thread read_thread;
345 std::thread write_thread;
346
347 {
348 std::lock_guard<std::mutex> lock(mutex_);
349 read_thread = std::move(read_thread_);
350 write_thread = std::move(write_thread_);
351 }
352
353 read_thread.join();
354 write_thread.join();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800355
356 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
357 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
358}
359
360bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
361 {
Josh Gaoc251ec52018-04-03 12:55:18 -0700362 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800363 write_queue_.emplace_back(std::move(packet));
364 }
365
366 cv_.notify_one();
367 return true;
368}
369
Josh Gaob800d882018-01-28 20:32:46 -0800370bool FdConnection::Read(apacket* packet) {
371 if (!ReadFdExactly(fd_.get(), &packet->msg, sizeof(amessage))) {
372 D("remote local: read terminated (message)");
373 return false;
374 }
375
Josh Gaof571fcb2018-02-05 18:49:10 -0800376 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gao5caaebd2018-02-02 14:38:04 -0800377 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
378 return false;
379 }
380
Josh Gaof571fcb2018-02-05 18:49:10 -0800381 packet->payload.resize(packet->msg.data_length);
382
383 if (!ReadFdExactly(fd_.get(), &packet->payload[0], packet->payload.size())) {
Josh Gaob800d882018-01-28 20:32:46 -0800384 D("remote local: terminated (data)");
385 return false;
386 }
387
388 return true;
389}
390
391bool FdConnection::Write(apacket* packet) {
Josh Gaof571fcb2018-02-05 18:49:10 -0800392 if (!WriteFdExactly(fd_.get(), &packet->msg, sizeof(packet->msg))) {
Josh Gaob800d882018-01-28 20:32:46 -0800393 D("remote local: write terminated");
394 return false;
395 }
396
Josh Gaof571fcb2018-02-05 18:49:10 -0800397 if (packet->msg.data_length) {
398 if (!WriteFdExactly(fd_.get(), &packet->payload[0], packet->msg.data_length)) {
399 D("remote local: write terminated");
400 return false;
401 }
402 }
403
Josh Gaob800d882018-01-28 20:32:46 -0800404 return true;
405}
406
407void FdConnection::Close() {
408 adb_shutdown(fd_.get());
409 fd_.reset();
410}
411
Josh Gao06d61d42016-10-06 13:31:44 -0700412void send_packet(apacket* p, atransport* t) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800413 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayde471942017-12-07 11:40:00 -0800414 // compute a checksum for connection/auth packets for compatibility reasons
415 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
416 p->msg.data_check = 0;
417 } else {
418 p->msg.data_check = calculate_apacket_checksum(p);
419 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800420
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700421 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800422
Yi Kongaed415c2018-07-13 18:15:16 -0700423 if (t == nullptr) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700424 LOG(FATAL) << "Transport is null";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800425 }
426
Josh Gao0bbf69c2018-02-16 13:24:58 -0800427 if (t->Write(p) != 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700428 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800429 t->Kick();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800430 }
431}
432
Yabin Cuif4b99282015-08-27 12:03:11 -0700433void kick_transport(atransport* t) {
Josh Gao1db71af2017-08-17 13:50:51 -0700434 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui1f4ec192016-04-05 13:50:44 -0700435 // As kick_transport() can be called from threads without guarantee that t is valid,
436 // check if the transport is in transport_list first.
Josh Gaob122b172017-08-16 16:57:01 -0700437 //
438 // TODO(jmgao): WTF? Is this actually true?
Yabin Cui1f4ec192016-04-05 13:50:44 -0700439 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Yabin Cui7f274902016-04-18 11:22:34 -0700440 t->Kick();
Yabin Cui1f4ec192016-04-05 13:50:44 -0700441 }
Josh Gao902dace2018-08-10 14:44:54 -0700442
443#if ADB_HOST
444 reconnect_handler.CheckForKicked();
445#endif
Yabin Cuif4b99282015-08-27 12:03:11 -0700446}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800447
448static int transport_registration_send = -1;
449static int transport_registration_recv = -1;
Josh Gao71f775a2018-05-14 11:14:33 -0700450static fdevent* transport_registration_fde;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800451
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800452#if ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800453
454/* this adds support required by the 'track-devices' service.
455 * this is used to send the content of "list_transport" to any
456 * number of client connections that want it through a single
457 * live TCP connection
458 */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800459struct device_tracker {
Josh Gao1290fbf2016-11-22 14:32:34 -0800460 asocket socket;
Josh Gaoe0361d12018-02-12 17:24:00 -0800461 bool update_needed = false;
462 bool long_output = false;
463 device_tracker* next = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800464};
465
466/* linked list of all device trackers */
Josh Gao1290fbf2016-11-22 14:32:34 -0800467static device_tracker* device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800468
Josh Gao1290fbf2016-11-22 14:32:34 -0800469static void device_tracker_remove(device_tracker* tracker) {
470 device_tracker** pnode = &device_tracker_list;
471 device_tracker* node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800472
Josh Gao1db71af2017-08-17 13:50:51 -0700473 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800474 while (node) {
475 if (node == tracker) {
476 *pnode = node->next;
477 break;
478 }
479 pnode = &node->next;
Josh Gao1290fbf2016-11-22 14:32:34 -0800480 node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800481 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800482}
483
Josh Gao1290fbf2016-11-22 14:32:34 -0800484static void device_tracker_close(asocket* socket) {
485 device_tracker* tracker = (device_tracker*)socket;
486 asocket* peer = socket->peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800487
Josh Gao1290fbf2016-11-22 14:32:34 -0800488 D("device tracker %p removed", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800489 if (peer) {
Yi Kongaed415c2018-07-13 18:15:16 -0700490 peer->peer = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800491 peer->close(peer);
492 }
493 device_tracker_remove(tracker);
Josh Gaoe0361d12018-02-12 17:24:00 -0800494 delete tracker;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800495}
496
Josh Gao1ce99572018-03-07 16:52:28 -0800497static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800498 /* you can't read from a device tracker, close immediately */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800499 device_tracker_close(socket);
500 return -1;
501}
502
Elliott Hughese67f1f82015-04-30 17:32:03 -0700503static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700504 asocket* peer = tracker->socket.peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800505
Josh Gao1ce99572018-03-07 16:52:28 -0800506 apacket::payload_type data;
Josh Gao27cb7dc2018-02-01 13:17:50 -0800507 data.resize(4 + string.size());
508 char buf[5];
509 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
510 memcpy(&data[0], buf, 4);
511 memcpy(&data[4], string.data(), string.size());
512 return peer->enqueue(peer, std::move(data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800513}
514
Elliott Hughese67f1f82015-04-30 17:32:03 -0700515static void device_tracker_ready(asocket* socket) {
516 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800517
Elliott Hughese67f1f82015-04-30 17:32:03 -0700518 // We want to send the device list when the tracker connects
519 // for the first time, even if no update occurred.
Josh Gaob0c18022017-08-14 18:57:54 -0700520 if (tracker->update_needed) {
521 tracker->update_needed = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800522
Josh Gaob0c18022017-08-14 18:57:54 -0700523 std::string transports = list_transports(tracker->long_output);
Elliott Hughese67f1f82015-04-30 17:32:03 -0700524 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800525 }
526}
527
Josh Gaob0c18022017-08-14 18:57:54 -0700528asocket* create_device_tracker(bool long_output) {
Josh Gaoe0361d12018-02-12 17:24:00 -0800529 device_tracker* tracker = new device_tracker();
Elliott Hughes4679a392018-10-19 13:59:44 -0700530 if (tracker == nullptr) LOG(FATAL) << "cannot allocate device tracker";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800531
Josh Gao1290fbf2016-11-22 14:32:34 -0800532 D("device tracker %p created", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800533
534 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao1290fbf2016-11-22 14:32:34 -0800535 tracker->socket.ready = device_tracker_ready;
536 tracker->socket.close = device_tracker_close;
Josh Gaob0c18022017-08-14 18:57:54 -0700537 tracker->update_needed = true;
538 tracker->long_output = long_output;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800539
Josh Gao1290fbf2016-11-22 14:32:34 -0800540 tracker->next = device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800541 device_tracker_list = tracker;
542
543 return &tracker->socket;
544}
545
Josh Gaofd713e52017-05-03 22:37:10 -0700546// Check if all of the USB transports are connected.
547bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gao1db71af2017-08-17 13:50:51 -0700548 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaofd713e52017-05-03 22:37:10 -0700549 for (const auto& t : transport_list) {
550 if (!fn(t)) {
551 return false;
552 }
553 }
554 for (const auto& t : pending_list) {
555 if (!fn(t)) {
556 return false;
557 }
558 }
559 return true;
560}
561
Elliott Hughese67f1f82015-04-30 17:32:03 -0700562// Call this function each time the transport list has changed.
563void update_transports() {
Josh Gaofd713e52017-05-03 22:37:10 -0700564 update_transport_status();
565
566 // Notify `adb track-devices` clients.
Elliott Hughese67f1f82015-04-30 17:32:03 -0700567 std::string transports = list_transports(false);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800568
Elliott Hughese67f1f82015-04-30 17:32:03 -0700569 device_tracker* tracker = device_tracker_list;
570 while (tracker != nullptr) {
571 device_tracker* next = tracker->next;
572 // This may destroy the tracker if the connection is closed.
573 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800574 tracker = next;
575 }
576}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700577
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800578#else
Elliott Hughese67f1f82015-04-30 17:32:03 -0700579
580void update_transports() {
581 // Nothing to do on the device side.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800582}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700583
Josh Gao1290fbf2016-11-22 14:32:34 -0800584#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800585
Josh Gao1290fbf2016-11-22 14:32:34 -0800586struct tmsg {
587 atransport* transport;
588 int action;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800589};
590
Josh Gao1290fbf2016-11-22 14:32:34 -0800591static int transport_read_action(int fd, struct tmsg* m) {
592 char* p = (char*)m;
593 int len = sizeof(*m);
594 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800595
Josh Gao1290fbf2016-11-22 14:32:34 -0800596 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800597 r = adb_read(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800598 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800599 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800600 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800601 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700602 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800603 return -1;
604 }
605 }
606 return 0;
607}
608
Josh Gao1290fbf2016-11-22 14:32:34 -0800609static int transport_write_action(int fd, struct tmsg* m) {
610 char* p = (char*)m;
611 int len = sizeof(*m);
612 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800613
Josh Gao1290fbf2016-11-22 14:32:34 -0800614 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800615 r = adb_write(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800616 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800617 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800618 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800619 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700620 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800621 return -1;
622 }
623 }
624 return 0;
625}
626
Josh Gao0bbf69c2018-02-16 13:24:58 -0800627static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800628 tmsg m;
Josh Gao1290fbf2016-11-22 14:32:34 -0800629 atransport* t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800630
Josh Gao1290fbf2016-11-22 14:32:34 -0800631 if (!(ev & FDE_READ)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800632 return;
633 }
634
Josh Gao1290fbf2016-11-22 14:32:34 -0800635 if (transport_read_action(_fd, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700636 PLOG(FATAL) << "cannot read transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800637 }
638
639 t = m.transport;
640
Dan Albert1792c232015-05-18 13:06:53 -0700641 if (m.action == 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700642 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800643
Josh Gao0cd3ae12016-09-21 12:37:10 -0700644 {
Josh Gao1db71af2017-08-17 13:50:51 -0700645 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700646 transport_list.remove(t);
647 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800648
Dan Albertc7915a32015-05-18 16:46:31 -0700649 delete t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800650
651 update_transports();
652 return;
653 }
654
Mike Lockwood0927bf92009-08-08 12:37:44 -0400655 /* don't create transport threads for inaccessible devices */
Yabin Cuib5e11412017-03-10 16:01:01 -0800656 if (t->GetConnectionState() != kCsNoPerm) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700657 // The connection gets a reference to the atransport. It will release it
658 // upon a read/write error.
659 t->ref_count++;
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700660 t->connection()->SetTransportName(t->serial_name());
661 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao0bbf69c2018-02-16 13:24:58 -0800662 if (!check_header(p.get(), t)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700663 D("%s: remote read: bad header", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800664 return false;
665 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800666
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700667 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "from remote", p.get());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800668 apacket* packet = p.release();
Mike Lockwood0927bf92009-08-08 12:37:44 -0400669
Josh Gao0bbf69c2018-02-16 13:24:58 -0800670 // TODO: Does this need to run on the main thread?
671 fdevent_run_on_main_thread([packet, t]() { handle_packet(packet, t); });
672 return true;
673 });
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700674 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700675 LOG(INFO) << t->serial_name() << ": connection terminated: " << error;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800676 fdevent_run_on_main_thread([t]() {
677 handle_offline(t);
678 transport_unref(t);
679 });
680 });
Mike Lockwood0927bf92009-08-08 12:37:44 -0400681
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700682 t->connection()->Start();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800683#if ADB_HOST
684 send_connect(t);
685#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800686 }
687
Josh Gao0cd3ae12016-09-21 12:37:10 -0700688 {
Josh Gao1db71af2017-08-17 13:50:51 -0700689 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700690 auto it = std::find(pending_list.begin(), pending_list.end(), t);
691 if (it != pending_list.end()) {
692 pending_list.remove(t);
693 transport_list.push_front(t);
694 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700695 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800696
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800697 update_transports();
698}
699
Josh Gaodef91c02018-07-31 18:28:32 -0700700#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700701void init_reconnect_handler(void) {
702 reconnect_handler.Start();
703}
Josh Gaodef91c02018-07-31 18:28:32 -0700704#endif
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700705
Josh Gao1290fbf2016-11-22 14:32:34 -0800706void init_transport_registration(void) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800707 int s[2];
708
Josh Gao1290fbf2016-11-22 14:32:34 -0800709 if (adb_socketpair(s)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700710 PLOG(FATAL) << "cannot open transport registration socketpair";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800711 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700712 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800713
714 transport_registration_send = s[0];
715 transport_registration_recv = s[1];
716
Josh Gao71f775a2018-05-14 11:14:33 -0700717 transport_registration_fde =
Yi Kongaed415c2018-07-13 18:15:16 -0700718 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao71f775a2018-05-14 11:14:33 -0700719 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao01b7bc42017-05-09 13:43:35 -0700720}
721
722void kick_all_transports() {
Josh Gaodef91c02018-07-31 18:28:32 -0700723#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700724 reconnect_handler.Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700725#endif
Josh Gao01b7bc42017-05-09 13:43:35 -0700726 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gao1db71af2017-08-17 13:50:51 -0700727 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao01b7bc42017-05-09 13:43:35 -0700728 for (auto t : transport_list) {
729 t->Kick();
730 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800731}
732
733/* the fdevent select pump is single threaded */
Josh Gaoc51726c2018-10-11 16:33:05 -0700734void register_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800735 tmsg m;
736 m.transport = transport;
737 m.action = 1;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700738 D("transport: %s registered", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800739 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700740 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800741 }
742}
743
Josh Gao1290fbf2016-11-22 14:32:34 -0800744static void remove_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800745 tmsg m;
746 m.transport = transport;
747 m.action = 0;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700748 D("transport: %s removed", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800749 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700750 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800751 }
752}
753
Yabin Cuif4b99282015-08-27 12:03:11 -0700754static void transport_unref(atransport* t) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700755 check_main_thread();
Yabin Cuif4b99282015-08-27 12:03:11 -0700756 CHECK(t != nullptr);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700757
Josh Gaoe48ecce2017-09-13 13:40:57 -0700758 std::lock_guard<std::recursive_mutex> lock(transport_lock);
759 CHECK_GT(t->ref_count, 0u);
760 t->ref_count--;
761 if (t->ref_count == 0) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700762 LOG(INFO) << "destroying transport " << t->serial_name();
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700763 t->connection()->Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700764#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700765 if (t->IsTcpDevice() && !t->kicked()) {
Josh Gaodef91c02018-07-31 18:28:32 -0700766 D("transport: %s unref (attempting reconnection)", t->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700767 reconnect_handler.TrackTransport(t);
768 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700769 D("transport: %s unref (kicking and closing)", t->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700770 remove_transport(t);
771 }
Josh Gaodef91c02018-07-31 18:28:32 -0700772#else
773 D("transport: %s unref (kicking and closing)", t->serial.c_str());
774 remove_transport(t);
775#endif
776
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100777 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700778 D("transport: %s unref (count=%zu)", t->serial.c_str(), t->ref_count);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -0400779 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800780}
781
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700782static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao1290fbf2016-11-22 14:32:34 -0800783 bool sanitize_qual) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700784 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
785 return qual.empty();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700786
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700787 if (qual.empty()) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700788
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700789 const char* ptr = to_test.c_str();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700790 if (prefix) {
791 while (*prefix) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700792 if (*prefix++ != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700793 }
794 }
795
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700796 for (char ch : qual) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800797 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700798 if (ch != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700799 }
800
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700801 /* Everything matched so far. Return true if *ptr is a NUL. */
802 return !*ptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700803}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800804
Josh Gaob122b172017-08-16 16:57:01 -0700805atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
806 bool* is_ambiguous, std::string* error_out,
807 bool accept_any_state) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700808 atransport* result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800809
Josh Gaob122b172017-08-16 16:57:01 -0700810 if (transport_id != 0) {
811 *error_out =
812 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
813 } else if (serial) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700814 *error_out = android::base::StringPrintf("device '%s' not found", serial);
815 } else if (type == kTransportLocal) {
816 *error_out = "no emulators found";
817 } else if (type == kTransportAny) {
818 *error_out = "no devices/emulators found";
819 } else {
820 *error_out = "no devices found";
821 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800822
Josh Gao1db71af2017-08-17 13:50:51 -0700823 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes8d28e192015-10-07 14:55:10 -0700824 for (const auto& t : transport_list) {
Yabin Cuib5e11412017-03-10 16:01:01 -0800825 if (t->GetConnectionState() == kCsNoPerm) {
David Purselld2acbd12015-12-02 15:14:31 -0800826 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwood37d31112009-08-08 13:53:16 -0400827 continue;
828 }
Mike Lockwood0927bf92009-08-08 12:37:44 -0400829
Josh Gaob122b172017-08-16 16:57:01 -0700830 if (transport_id) {
831 if (t->id == transport_id) {
832 result = t;
833 break;
834 }
835 } else if (serial) {
David Pursell3f902aa2016-03-01 08:58:26 -0800836 if (t->MatchesTarget(serial)) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700837 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700838 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700839 if (is_ambiguous) *is_ambiguous = true;
840 result = nullptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700841 break;
842 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800843 result = t;
Scott Andersone109d262012-04-20 11:21:14 -0700844 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800845 } else {
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700846 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800847 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700848 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700849 if (is_ambiguous) *is_ambiguous = true;
850 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800851 break;
852 }
853 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700854 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800855 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700856 *error_out = "more than one emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700857 if (is_ambiguous) *is_ambiguous = true;
858 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800859 break;
860 }
861 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700862 } else if (type == kTransportAny) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800863 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700864 *error_out = "more than one device/emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700865 if (is_ambiguous) *is_ambiguous = true;
866 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800867 break;
868 }
869 result = t;
870 }
871 }
872 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700873 lock.unlock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800874
Josh Gao704494b2018-05-04 16:04:49 -0700875 if (result && !accept_any_state) {
876 // The caller requires an active transport.
877 // Make sure that we're actually connected.
878 ConnectionState state = result->GetConnectionState();
879 switch (state) {
880 case kCsConnecting:
881 *error_out = "device still connecting";
882 result = nullptr;
883 break;
Benoit Goby77e8e582013-01-15 12:36:47 -0800884
Josh Gao704494b2018-05-04 16:04:49 -0700885 case kCsAuthorizing:
886 *error_out = "device still authorizing";
887 result = nullptr;
888 break;
889
890 case kCsUnauthorized: {
891 *error_out = "device unauthorized.\n";
892 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
893 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
894 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
895 *error_out += "\n";
896 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
897 *error_out += "Otherwise check for a confirmation dialog on your device.";
898 result = nullptr;
899 break;
900 }
901
902 case kCsOffline:
903 *error_out = "device offline";
904 result = nullptr;
905 break;
906
907 default:
908 break;
909 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800910 }
911
912 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700913 *error_out = "success";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800914 }
915
916 return result;
917}
918
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700919bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
920 std::unique_lock<std::mutex> lock(mutex_);
921 ScopedAssumeLocked assume_locked(mutex_);
922 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
923 return connection_established_ready_;
924 }) && connection_established_;
925}
926
927void ConnectionWaitable::SetConnectionEstablished(bool success) {
928 {
929 std::lock_guard<std::mutex> lock(mutex_);
930 if (connection_established_ready_) return;
931 connection_established_ready_ = true;
932 connection_established_ = success;
933 D("connection established with %d", success);
934 }
935 cv_.notify_one();
936}
937
938atransport::~atransport() {
939 // If the connection callback had not been run before, run it now.
940 SetConnectionEstablished(false);
941}
942
Yabin Cuib5e11412017-03-10 16:01:01 -0800943int atransport::Write(apacket* p) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700944 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cuib5e11412017-03-10 16:01:01 -0800945}
946
Yabin Cui7f274902016-04-18 11:22:34 -0700947void atransport::Kick() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700948 if (!kicked_.exchange(true)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700949 D("kicking transport %p %s", this, this->serial.c_str());
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700950 this->connection()->Stop();
Yabin Cui7f274902016-04-18 11:22:34 -0700951 }
952}
953
Yabin Cuib5e11412017-03-10 16:01:01 -0800954ConnectionState atransport::GetConnectionState() const {
955 return connection_state_;
956}
957
958void atransport::SetConnectionState(ConnectionState state) {
959 check_main_thread();
960 connection_state_ = state;
961}
962
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700963void atransport::SetConnection(std::unique_ptr<Connection> connection) {
964 std::lock_guard<std::mutex> lock(mutex_);
965 connection_ = std::shared_ptr<Connection>(std::move(connection));
966}
967
Josh Gaoffbd3362018-02-28 14:44:23 -0800968std::string atransport::connection_state_name() const {
Yabin Cuib5e11412017-03-10 16:01:01 -0800969 ConnectionState state = GetConnectionState();
970 switch (state) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800971 case kCsOffline:
972 return "offline";
973 case kCsBootloader:
974 return "bootloader";
975 case kCsDevice:
976 return "device";
977 case kCsHost:
978 return "host";
979 case kCsRecovery:
980 return "recovery";
981 case kCsNoPerm:
982 return UsbNoPermissionsShortHelpText();
983 case kCsSideload:
984 return "sideload";
985 case kCsUnauthorized:
986 return "unauthorized";
Josh Gao704494b2018-05-04 16:04:49 -0700987 case kCsAuthorizing:
988 return "authorizing";
989 case kCsConnecting:
990 return "connecting";
Josh Gao1290fbf2016-11-22 14:32:34 -0800991 default:
992 return "unknown";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800993 }
994}
995
Tamas Berghammer3d2904c2015-07-13 19:12:28 +0100996void atransport::update_version(int version, size_t payload) {
997 protocol_version = std::min(version, A_VERSION);
998 max_payload = std::min(payload, MAX_PAYLOAD);
999}
1000
1001int atransport::get_protocol_version() const {
1002 return protocol_version;
1003}
1004
1005size_t atransport::get_max_payload() const {
1006 return max_payload;
1007}
1008
Dan Albert1792c232015-05-18 13:06:53 -07001009const FeatureSet& supported_features() {
David Pursell4e2fd362015-09-22 10:43:08 -07001010 // Local static allocation to avoid global non-POD variables.
1011 static const FeatureSet* features = new FeatureSet{
Josh Gaofb085102018-10-22 13:00:05 -07001012 kFeatureShell2, kFeatureCmd, kFeatureStat2, kFeatureFixedPushMkdir,
Dario Freni29814de2018-10-04 16:26:40 +01001013#if ADB_HOST
1014 kFeatureApex
1015#endif
David Pursellbbe3d212015-09-25 08:37:13 -07001016 // Increment ADB_SERVER_VERSION whenever the feature list changes to
1017 // make sure that the adb client and server features stay in sync
1018 // (http://b/24370690).
David Pursell4e2fd362015-09-22 10:43:08 -07001019 };
1020
1021 return *features;
1022}
1023
1024std::string FeatureSetToString(const FeatureSet& features) {
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001025 return android::base::Join(features, ',');
David Pursell4e2fd362015-09-22 10:43:08 -07001026}
1027
1028FeatureSet StringToFeatureSet(const std::string& features_string) {
David Purselld2b588e2015-09-25 13:04:21 -07001029 if (features_string.empty()) {
1030 return FeatureSet();
1031 }
1032
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001033 auto names = android::base::Split(features_string, ",");
David Pursell4e2fd362015-09-22 10:43:08 -07001034 return FeatureSet(names.begin(), names.end());
Dan Albert1792c232015-05-18 13:06:53 -07001035}
1036
David Pursell70ef7b42015-09-30 13:35:42 -07001037bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001038 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell70ef7b42015-09-30 13:35:42 -07001039}
1040
Dan Albert1792c232015-05-18 13:06:53 -07001041bool atransport::has_feature(const std::string& feature) const {
1042 return features_.count(feature) > 0;
1043}
1044
David Pursell4e2fd362015-09-22 10:43:08 -07001045void atransport::SetFeatures(const std::string& features_string) {
1046 features_ = StringToFeatureSet(features_string);
Dan Albert1792c232015-05-18 13:06:53 -07001047}
1048
Yabin Cuib3298242015-08-28 15:09:44 -07001049void atransport::AddDisconnect(adisconnect* disconnect) {
1050 disconnects_.push_back(disconnect);
1051}
1052
1053void atransport::RemoveDisconnect(adisconnect* disconnect) {
1054 disconnects_.remove(disconnect);
1055}
1056
1057void atransport::RunDisconnects() {
Elliott Hughes65fe2512015-10-07 15:59:35 -07001058 for (const auto& disconnect : disconnects_) {
Yabin Cuib3298242015-08-28 15:09:44 -07001059 disconnect->func(disconnect->opaque, this);
1060 }
1061 disconnects_.clear();
1062}
1063
David Pursell3f902aa2016-03-01 08:58:26 -08001064bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001065 if (!serial.empty()) {
David Pursell3f902aa2016-03-01 08:58:26 -08001066 if (target == serial) {
1067 return true;
1068 } else if (type == kTransportLocal) {
1069 // Local transports can match [tcp:|udp:]<hostname>[:port].
1070 const char* local_target_ptr = target.c_str();
1071
1072 // For fastboot compatibility, ignore protocol prefixes.
1073 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao1290fbf2016-11-22 14:32:34 -08001074 android::base::StartsWith(target, "udp:")) {
David Pursell3f902aa2016-03-01 08:58:26 -08001075 local_target_ptr += 4;
1076 }
1077
1078 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1079 std::string serial_host, error;
1080 int serial_port = -1;
Josh Gao1290fbf2016-11-22 14:32:34 -08001081 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursell3f902aa2016-03-01 08:58:26 -08001082 // |target| may omit the port to default to ours.
1083 std::string target_host;
1084 int target_port = serial_port;
1085 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1086 nullptr, &error) &&
Josh Gao1290fbf2016-11-22 14:32:34 -08001087 serial_host == target_host && serial_port == target_port) {
David Pursell3f902aa2016-03-01 08:58:26 -08001088 return true;
1089 }
1090 }
1091 }
1092 }
1093
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001094 return (target == devpath) || qual_match(target, "product:", product, false) ||
1095 qual_match(target, "model:", model, true) ||
1096 qual_match(target, "device:", device, false);
David Pursell3f902aa2016-03-01 08:58:26 -08001097}
1098
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001099void atransport::SetConnectionEstablished(bool success) {
1100 connection_waitable_->SetConnectionEstablished(success);
1101}
1102
Josh Gaofc2e56f2018-08-30 11:37:00 -07001103ReconnectResult atransport::Reconnect() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001104 return reconnect_(this);
1105}
1106
Elliott Hughese67f1f82015-04-30 17:32:03 -07001107#if ADB_HOST
1108
Josh Gaob122b172017-08-16 16:57:01 -07001109// We use newline as our delimiter, make sure to never output it.
1110static std::string sanitize(std::string str, bool alphanumeric) {
1111 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1112 : [](const char c) { return c == '\n'; };
1113 std::replace_if(str.begin(), str.end(), pred, '_');
1114 return str;
1115}
1116
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001117static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob122b172017-08-16 16:57:01 -07001118 bool alphanumeric) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001119 if (value.empty()) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001120 return;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001121 }
1122
Elliott Hughese67f1f82015-04-30 17:32:03 -07001123 *result += ' ';
1124 *result += key;
Josh Gaob122b172017-08-16 16:57:01 -07001125 *result += sanitize(value, alphanumeric);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001126}
1127
Josh Gao1290fbf2016-11-22 14:32:34 -08001128static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001129 std::string serial = t->serial;
1130 if (serial.empty()) {
Dan Albertd99d9022015-05-06 16:48:52 -07001131 serial = "(no serial number)";
Elliott Hughese67f1f82015-04-30 17:32:03 -07001132 }
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001133
1134 if (!long_listing) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001135 *result += serial;
1136 *result += '\t';
1137 *result += t->connection_state_name();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001138 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001139 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1140 t->connection_state_name().c_str());
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001141
Elliott Hughese67f1f82015-04-30 17:32:03 -07001142 append_transport_info(result, "", t->devpath, false);
1143 append_transport_info(result, "product:", t->product, false);
1144 append_transport_info(result, "model:", t->model, true);
1145 append_transport_info(result, "device:", t->device, false);
Josh Gaob122b172017-08-16 16:57:01 -07001146
1147 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1148 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1149 *result += " transport_id:";
1150 *result += std::to_string(t->id);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001151 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001152 *result += '\n';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001153}
1154
Elliott Hughese67f1f82015-04-30 17:32:03 -07001155std::string list_transports(bool long_listing) {
Josh Gao1db71af2017-08-17 13:50:51 -07001156 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov04398a92017-12-17 10:56:07 +00001157
1158 auto sorted_transport_list = transport_list;
1159 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1160 if (x->type != y->type) {
1161 return x->type < y->type;
1162 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001163 return x->serial < y->serial;
Artem Iglikov04398a92017-12-17 10:56:07 +00001164 });
1165
1166 std::string result;
1167 for (const auto& t : sorted_transport_list) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001168 append_transport(t, &result, long_listing);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001169 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001170 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001171}
1172
Josh Gao22d2b3e2016-10-27 14:01:08 -07001173void close_usb_devices(std::function<bool(const atransport*)> predicate) {
Josh Gao1db71af2017-08-17 13:50:51 -07001174 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao22d2b3e2016-10-27 14:01:08 -07001175 for (auto& t : transport_list) {
1176 if (predicate(t)) {
1177 t->Kick();
1178 }
1179 }
1180}
1181
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001182/* hack for osx */
Dan Albertc7915a32015-05-18 16:46:31 -07001183void close_usb_devices() {
Josh Gao22d2b3e2016-10-27 14:01:08 -07001184 close_usb_devices([](const atransport*) { return true; });
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001185}
Josh Gao1290fbf2016-11-22 14:32:34 -08001186#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001187
Josh Gao362e6962018-08-08 16:20:14 -07001188bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
1189 atransport::ReconnectCallback reconnect, int* error) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001190 atransport* t = new atransport(std::move(reconnect), kCsOffline);
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +01001191
Josh Gao3b4de3c2018-08-02 13:58:24 -07001192 D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
Josh Gao56300c92018-07-25 17:21:49 -07001193 if (init_socket_transport(t, std::move(s), port, local) < 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001194 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001195 if (error) *error = errno;
1196 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001197 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001198
Josh Gao1db71af2017-08-17 13:50:51 -07001199 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes65fe2512015-10-07 15:59:35 -07001200 for (const auto& transport : pending_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001201 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001202 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001203 << " is already in pending_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001204 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001205 if (error) *error = EALREADY;
1206 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001207 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001208 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001209
Elliott Hughes65fe2512015-10-07 15:59:35 -07001210 for (const auto& transport : transport_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001211 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001212 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001213 << " is already in transport_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001214 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001215 if (error) *error = EALREADY;
1216 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001217 }
1218 }
1219
Josh Gao3b4de3c2018-08-02 13:58:24 -07001220 t->serial = std::move(serial);
Dan Albertc7915a32015-05-18 16:46:31 -07001221 pending_list.push_front(t);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001222
1223 lock.unlock();
Benoit Goby1c45ee92013-03-29 18:22:36 -07001224
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001225 auto waitable = t->connection_waitable();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001226 register_transport(t);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001227
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001228 if (local == 1) {
1229 // Do not wait for emulator transports.
Josh Gao362e6962018-08-08 16:20:14 -07001230 return true;
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001231 }
1232
Josh Gao362e6962018-08-08 16:20:14 -07001233 if (!waitable->WaitForConnection(std::chrono::seconds(10))) {
1234 if (error) *error = ETIMEDOUT;
1235 return false;
1236 }
1237
1238 if (t->GetConnectionState() == kCsUnauthorized) {
1239 if (error) *error = EPERM;
1240 return false;
1241 }
1242
1243 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001244}
1245
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001246#if ADB_HOST
Josh Gao1290fbf2016-11-22 14:32:34 -08001247atransport* find_transport(const char* serial) {
Dan Albertc7915a32015-05-18 16:46:31 -07001248 atransport* result = nullptr;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001249
Josh Gao1db71af2017-08-17 13:50:51 -07001250 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001251 for (auto& t : transport_list) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001252 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001253 result = t;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001254 break;
1255 }
Dan Albertc7915a32015-05-18 16:46:31 -07001256 }
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001257
Dan Albertc7915a32015-05-18 16:46:31 -07001258 return result;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001259}
1260
Yabin Cuif4b99282015-08-27 12:03:11 -07001261void kick_all_tcp_devices() {
Josh Gao1db71af2017-08-17 13:50:51 -07001262 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001263 for (auto& t : transport_list) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001264 if (t->IsTcpDevice()) {
Yabin Cuid6ab3c22015-08-31 11:50:24 -07001265 // Kicking breaks the read_transport thread of this transport out of any read, then
1266 // the read_transport thread will notify the main thread to make this transport
1267 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cuif4b99282015-08-27 12:03:11 -07001268 // Finally, this transport will be closed and freed in the main thread.
Yabin Cui7f274902016-04-18 11:22:34 -07001269 t->Kick();
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001270 }
Dan Albertc7915a32015-05-18 16:46:31 -07001271 }
Josh Gao902dace2018-08-10 14:44:54 -07001272#if ADB_HOST
1273 reconnect_handler.CheckForKicked();
1274#endif
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001275}
1276
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001277#endif
1278
Josh Gao1290fbf2016-11-22 14:32:34 -08001279void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1280 unsigned writeable) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001281 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertc7915a32015-05-18 16:46:31 -07001282
Josh Gao1290fbf2016-11-22 14:32:34 -08001283 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cuib5e11412017-03-10 16:01:01 -08001284 init_usb_transport(t, usb);
Josh Gao1290fbf2016-11-22 14:32:34 -08001285 if (serial) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001286 t->serial = serial;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001287 }
Dan Albertc7915a32015-05-18 16:46:31 -07001288
1289 if (devpath) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001290 t->devpath = devpath;
Scott Andersone109d262012-04-20 11:21:14 -07001291 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001292
Josh Gao0cd3ae12016-09-21 12:37:10 -07001293 {
Josh Gao1db71af2017-08-17 13:50:51 -07001294 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001295 pending_list.push_front(t);
1296 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001297
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001298 register_transport(t);
1299}
1300
Josh Gaoc51726c2018-10-11 16:33:05 -07001301#if ADB_HOST
Dan Albertdcd78a12015-05-18 16:43:57 -07001302// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao1290fbf2016-11-22 14:32:34 -08001303void unregister_usb_transport(usb_handle* usb) {
Josh Gao1db71af2017-08-17 13:50:51 -07001304 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaob800d882018-01-28 20:32:46 -08001305 transport_list.remove_if([usb](atransport* t) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -07001306 auto connection = t->connection();
1307 if (auto usb_connection = dynamic_cast<UsbConnection*>(connection.get())) {
1308 return usb_connection->handle_ == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gaob800d882018-01-28 20:32:46 -08001309 }
1310 return false;
1311 });
Mike Lockwood0927bf92009-08-08 12:37:44 -04001312}
Josh Gaoc51726c2018-10-11 16:33:05 -07001313#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001314
Josh Gao36dadca2017-05-16 15:02:45 -07001315bool check_header(apacket* p, atransport* t) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001316 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cuib5e11412017-03-10 16:01:01 -08001317 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1318 << ", magic = " << p->msg.magic;
Josh Gao36dadca2017-05-16 15:02:45 -07001319 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001320 }
1321
Josh Gao1290fbf2016-11-22 14:32:34 -08001322 if (p->msg.data_length > t->get_max_payload()) {
1323 VLOG(RWX) << "check_header(): " << p->msg.data_length
1324 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao36dadca2017-05-16 15:02:45 -07001325 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001326 }
1327
Josh Gao36dadca2017-05-16 15:02:45 -07001328 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001329}
1330
Josh Gao3bd28792016-10-05 19:02:29 -07001331#if ADB_HOST
Josh Gao2e671202016-08-18 22:00:12 -07001332std::shared_ptr<RSA> atransport::NextKey() {
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001333 if (keys_.empty()) keys_ = adb_auth_get_private_keys();
1334
Josh Gao2e671202016-08-18 22:00:12 -07001335 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001336 keys_.pop_front();
1337 return result;
1338}
Josh Gao3bd28792016-10-05 19:02:29 -07001339#endif