blob: d9749ac3544c924d1ede463751de5e52de18fcb8 [file] [log] [blame]
The Android Open Source Project9ca14dc2009-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 Cui19bec5b2015-09-22 15:52:57 -070017#define TRACE_TAG TRANSPORT
Dan Albertb302d122015-02-24 15:51:19 -080018
Dan Albertdb6fe642015-03-19 15:21:08 -070019#include "sysdeps.h"
Josh Gaof2a988c2018-03-07 16:51:08 -080020
Dan Albertb302d122015-02-24 15:51:19 -080021#include "transport.h"
22
Dan Albert4895c522015-02-20 17:24:58 -080023#include <ctype.h>
Dan Albertb302d122015-02-24 15:51:19 -080024#include <errno.h>
Josh Gaob39e4152017-08-16 16:57:01 -070025#include <inttypes.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080026#include <stdio.h>
27#include <stdlib.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080028#include <string.h>
Dan Albertb302d122015-02-24 15:51:19 -080029#include <unistd.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080030
Spencer Low28bc2cb2015-11-07 18:51:54 -080031#include <algorithm>
Josh Gao715fe602018-02-16 13:24:58 -080032#include <deque>
Dan Albertecce5032015-05-18 16:46:31 -070033#include <list>
Pirama Arumuga Nainar5231aff2018-08-08 10:33:24 -070034#include <memory>
Josh Gaoe7daf572016-09-21 12:37:10 -070035#include <mutex>
Josh Gaod2ea0652018-08-10 14:28:24 -070036#include <set>
Josh Gao0f3312a2017-04-12 17:00:49 -070037#include <thread>
Dan Albertecce5032015-05-18 16:46:31 -070038
Elliott Hughesf55ead92015-12-04 22:00:26 -080039#include <android-base/logging.h>
David Pursellc929c6f2016-03-01 08:58:26 -080040#include <android-base/parsenetaddress.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080041#include <android-base/stringprintf.h>
42#include <android-base/strings.h>
Josh Gaob39e4152017-08-16 16:57:01 -070043#include <android-base/thread_annotations.h>
Elliott Hughes88b4c852015-04-30 17:32:03 -070044
Josh Gao361148b2018-01-02 12:01:43 -080045#include <diagnose_usb.h>
46
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080047#include "adb.h"
Elliott Hughes801066a2016-06-29 17:42:01 -070048#include "adb_auth.h"
Josh Gao395b86a2018-01-28 20:32:46 -080049#include "adb_io.h"
Josh Gao9e09a972016-11-29 09:40:29 -080050#include "adb_trace.h"
Elliott Hughes88b4c852015-04-30 17:32:03 -070051#include "adb_utils.h"
Josh Gaob51193a2019-06-28 13:50:37 -070052#include "fdevent/fdevent.h"
Josh Gaob0182892018-07-31 14:12:59 -070053#include "sysdeps/chrono.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080054
Josh Gao8aa57d22019-02-12 13:59:03 -080055using android::base::ScopedLockAssertion;
56
Luis Hector Chavez0aeda102018-04-20 10:31:29 -070057static void remove_transport(atransport* transport);
58static void transport_unref(atransport* transport);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080059
Josh Gaob39e4152017-08-16 16:57:01 -070060// TODO: unordered_map<TransportId, atransport*>
Josh Gaoe3a87d02015-11-11 17:56:12 -080061static auto& transport_list = *new std::list<atransport*>();
62static auto& pending_list = *new std::list<atransport*>();
Benoit Goby3f9f9ce2013-03-29 18:22:36 -070063
Josh Gaoaaa82f72017-08-17 13:50:51 -070064static auto& transport_lock = *new std::recursive_mutex();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080065
Todd Kennedyaff9c672015-11-10 00:03:25 +000066const char* const kFeatureShell2 = "shell_v2";
67const char* const kFeatureCmd = "cmd";
Josh Gaoa2cf3752016-12-05 17:11:34 -080068const char* const kFeatureStat2 = "stat_v2";
Josh Gao210b63f2017-02-22 17:07:01 -080069const char* const kFeatureLibusb = "libusb";
Dan Albert27983bc2017-05-23 14:30:00 -070070const char* const kFeaturePushSync = "push_sync";
Dario Frenidcb4c362018-10-04 16:26:40 +010071const char* const kFeatureApex = "apex";
Josh Gao281aab72018-10-22 13:00:05 -070072const char* const kFeatureFixedPushMkdir = "fixed_push_mkdir";
Alex Buynytskyye1fa8142019-01-17 13:13:56 -080073const char* const kFeatureAbb = "abb";
Josh Gao9eeb9f72019-02-20 13:01:40 -080074const char* const kFeatureFixedPushSymlinkTimestamp = "fixed_push_symlink_timestamp";
Alex Buynytskyy4f3fa052019-02-21 14:22:51 -080075const char* const kFeatureAbbExec = "abb_exec";
Josh Gaof764d572019-07-11 14:15:32 -070076const char* const kFeatureRemountShell = "remount_shell";
Todd Kennedyaff9c672015-11-10 00:03:25 +000077
Luis Hector Chavezda74b902018-04-17 14:25:04 -070078namespace {
79
Josh Gao5c47e9f2018-07-31 18:28:32 -070080#if ADB_HOST
Luis Hector Chavez0aeda102018-04-20 10:31:29 -070081// Tracks and handles atransport*s that are attempting reconnection.
82class ReconnectHandler {
83 public:
84 ReconnectHandler() = default;
85 ~ReconnectHandler() = default;
86
87 // Starts the ReconnectHandler thread.
88 void Start();
89
90 // Requests the ReconnectHandler thread to stop.
91 void Stop();
92
93 // Adds the atransport* to the queue of reconnect attempts.
94 void TrackTransport(atransport* transport);
95
Josh Gao13cb8c02018-08-10 14:44:54 -070096 // Wake up the ReconnectHandler thread to have it check for kicked transports.
97 void CheckForKicked();
98
Luis Hector Chavez0aeda102018-04-20 10:31:29 -070099 private:
100 // The main thread loop.
101 void Run();
102
103 // Tracks a reconnection attempt.
104 struct ReconnectAttempt {
105 atransport* transport;
Josh Gaoc4deb392018-07-30 18:51:55 -0700106 std::chrono::steady_clock::time_point reconnect_time;
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700107 size_t attempts_left;
Josh Gaob0182892018-07-31 14:12:59 -0700108
109 bool operator<(const ReconnectAttempt& rhs) const {
Josh Gaod2ea0652018-08-10 14:28:24 -0700110 if (reconnect_time == rhs.reconnect_time) {
111 return reinterpret_cast<uintptr_t>(transport) <
112 reinterpret_cast<uintptr_t>(rhs.transport);
113 }
114 return reconnect_time < rhs.reconnect_time;
Josh Gaob0182892018-07-31 14:12:59 -0700115 }
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700116 };
117
118 // Only retry for up to one minute.
Josh Gaob0182892018-07-31 14:12:59 -0700119 static constexpr const std::chrono::seconds kDefaultTimeout = 10s;
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700120 static constexpr const size_t kMaxAttempts = 6;
121
122 // Protects all members.
123 std::mutex reconnect_mutex_;
124 bool running_ GUARDED_BY(reconnect_mutex_) = true;
125 std::thread handler_thread_;
126 std::condition_variable reconnect_cv_;
Josh Gaod2ea0652018-08-10 14:28:24 -0700127 std::set<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700128
129 DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
130};
131
132void ReconnectHandler::Start() {
133 check_main_thread();
134 handler_thread_ = std::thread(&ReconnectHandler::Run, this);
135}
136
137void ReconnectHandler::Stop() {
138 check_main_thread();
139 {
140 std::lock_guard<std::mutex> lock(reconnect_mutex_);
141 running_ = false;
142 }
143 reconnect_cv_.notify_one();
144 handler_thread_.join();
145
146 // Drain the queue to free all resources.
147 std::lock_guard<std::mutex> lock(reconnect_mutex_);
148 while (!reconnect_queue_.empty()) {
Josh Gaod2ea0652018-08-10 14:28:24 -0700149 ReconnectAttempt attempt = *reconnect_queue_.begin();
150 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700151 remove_transport(attempt.transport);
152 }
153}
154
155void ReconnectHandler::TrackTransport(atransport* transport) {
156 check_main_thread();
157 {
158 std::lock_guard<std::mutex> lock(reconnect_mutex_);
159 if (!running_) return;
Josh Gaob0182892018-07-31 14:12:59 -0700160 // Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
161 auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
162 reconnect_queue_.emplace(
163 ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700164 }
165 reconnect_cv_.notify_one();
166}
167
Josh Gao13cb8c02018-08-10 14:44:54 -0700168void ReconnectHandler::CheckForKicked() {
169 reconnect_cv_.notify_one();
170}
171
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700172void ReconnectHandler::Run() {
173 while (true) {
174 ReconnectAttempt attempt;
175 {
176 std::unique_lock<std::mutex> lock(reconnect_mutex_);
Josh Gao8aa57d22019-02-12 13:59:03 -0800177 ScopedLockAssertion assume_lock(reconnect_mutex_);
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700178
Josh Gaoc4deb392018-07-30 18:51:55 -0700179 if (!reconnect_queue_.empty()) {
180 // FIXME: libstdc++ (used on Windows) implements condition_variable with
181 // system_clock as its clock, so we're probably hosed if the clock changes,
182 // even if we use steady_clock throughout. This problem goes away once we
183 // switch to libc++.
Josh Gaod2ea0652018-08-10 14:28:24 -0700184 reconnect_cv_.wait_until(lock, reconnect_queue_.begin()->reconnect_time);
Josh Gaoc4deb392018-07-30 18:51:55 -0700185 } else {
186 reconnect_cv_.wait(lock);
187 }
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700188
189 if (!running_) return;
Josh Gao13cb8c02018-08-10 14:44:54 -0700190
191 // Scan the whole list for kicked transports, so that we immediately handle an explicit
192 // disconnect request.
193 bool kicked = false;
194 for (auto it = reconnect_queue_.begin(); it != reconnect_queue_.end();) {
195 if (it->transport->kicked()) {
196 D("transport %s was kicked. giving up on it.", it->transport->serial.c_str());
197 remove_transport(it->transport);
198 it = reconnect_queue_.erase(it);
199 } else {
200 ++it;
201 }
202 kicked = true;
203 }
204
Josh Gaoc4deb392018-07-30 18:51:55 -0700205 if (reconnect_queue_.empty()) continue;
206
Josh Gao13cb8c02018-08-10 14:44:54 -0700207 // Go back to sleep if we either woke up spuriously, or we were woken up to remove
208 // a kicked transport, and the first transport isn't ready for reconnection yet.
Josh Gaoc4deb392018-07-30 18:51:55 -0700209 auto now = std::chrono::steady_clock::now();
Josh Gaod2ea0652018-08-10 14:28:24 -0700210 if (reconnect_queue_.begin()->reconnect_time > now) {
Josh Gaoc4deb392018-07-30 18:51:55 -0700211 continue;
212 }
213
Josh Gaod2ea0652018-08-10 14:28:24 -0700214 attempt = *reconnect_queue_.begin();
215 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700216 }
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700217 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700218
Josh Gaod24580d2018-08-30 11:37:00 -0700219 switch (attempt.transport->Reconnect()) {
220 case ReconnectResult::Retry: {
221 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
222 if (attempt.attempts_left == 0) {
223 D("transport %s exceeded the number of retry attempts. giving up on it.",
224 attempt.transport->serial.c_str());
225 remove_transport(attempt.transport);
226 continue;
227 }
228
229 std::lock_guard<std::mutex> lock(reconnect_mutex_);
230 reconnect_queue_.emplace(ReconnectAttempt{
231 attempt.transport,
232 std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
233 attempt.attempts_left - 1});
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700234 continue;
235 }
236
Josh Gaod24580d2018-08-30 11:37:00 -0700237 case ReconnectResult::Success:
238 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
239 register_transport(attempt.transport);
240 continue;
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700241
Josh Gaod24580d2018-08-30 11:37:00 -0700242 case ReconnectResult::Abort:
243 D("cancelling reconnection attempt to %s.", attempt.transport->serial.c_str());
244 remove_transport(attempt.transport);
245 continue;
246 }
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700247 }
248}
249
250static auto& reconnect_handler = *new ReconnectHandler();
251
Josh Gao5c47e9f2018-07-31 18:28:32 -0700252#endif
253
Luis Hector Chavezda74b902018-04-17 14:25:04 -0700254} // namespace
255
Josh Gaob39e4152017-08-16 16:57:01 -0700256TransportId NextTransportId() {
257 static std::atomic<TransportId> next(1);
258 return next++;
259}
260
Josh Gao3a2172b2019-03-28 15:47:44 -0700261void Connection::Reset() {
262 LOG(INFO) << "Connection::Reset(): stopping";
263 Stop();
264}
265
Josh Gao715fe602018-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 Gao13781e82018-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 Gao715fe602018-02-16 13:24:58 -0800281 read_thread_ = std::thread([this]() {
282 LOG(INFO) << this->transport_name_ << ": read thread spawning";
283 while (true) {
Josh Gaof2a988c2018-03-07 16:51:08 -0800284 auto packet = std::make_unique<apacket>();
Josh Gao715fe602018-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_);
Josh Gao8aa57d22019-02-12 13:59:03 -0800298 ScopedLockAssertion assume_locked(mutex_);
Josh Gao13781e82018-04-03 12:55:18 -0700299 cv_.wait(lock, [this]() REQUIRES(mutex_) {
300 return this->stopped_ || !this->write_queue_.empty();
301 });
302
Josh Gao715fe602018-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 Gao13781e82018-04-03 12:55:18 -0700317
318 started_ = true;
Josh Gao715fe602018-02-16 13:24:58 -0800319}
320
Josh Gao3a2172b2019-03-28 15:47:44 -0700321void BlockingConnectionAdapter::Reset() {
322 {
323 std::lock_guard<std::mutex> lock(mutex_);
324 if (!started_) {
325 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
326 return;
327 }
328
329 if (stopped_) {
330 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
331 << "): already stopped";
332 return;
333 }
334 }
335
336 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): resetting";
337 this->underlying_->Reset();
338 Stop();
339}
340
Josh Gao715fe602018-02-16 13:24:58 -0800341void BlockingConnectionAdapter::Stop() {
Josh Gao13781e82018-04-03 12:55:18 -0700342 {
343 std::lock_guard<std::mutex> lock(mutex_);
344 if (!started_) {
345 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
346 return;
347 }
Josh Gao715fe602018-02-16 13:24:58 -0800348
Josh Gao13781e82018-04-03 12:55:18 -0700349 if (stopped_) {
350 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
351 << "): already stopped";
352 return;
353 }
354
355 stopped_ = true;
356 }
Josh Gao715fe602018-02-16 13:24:58 -0800357
358 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
359
360 this->underlying_->Close();
Josh Gao715fe602018-02-16 13:24:58 -0800361 this->cv_.notify_one();
Josh Gao13781e82018-04-03 12:55:18 -0700362
363 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
364 std::thread read_thread;
365 std::thread write_thread;
366
367 {
368 std::lock_guard<std::mutex> lock(mutex_);
369 read_thread = std::move(read_thread_);
370 write_thread = std::move(write_thread_);
371 }
372
373 read_thread.join();
374 write_thread.join();
Josh Gao715fe602018-02-16 13:24:58 -0800375
376 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
377 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
378}
379
380bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
381 {
Josh Gao13781e82018-04-03 12:55:18 -0700382 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao715fe602018-02-16 13:24:58 -0800383 write_queue_.emplace_back(std::move(packet));
384 }
385
386 cv_.notify_one();
387 return true;
388}
389
Josh Gao395b86a2018-01-28 20:32:46 -0800390bool FdConnection::Read(apacket* packet) {
391 if (!ReadFdExactly(fd_.get(), &packet->msg, sizeof(amessage))) {
392 D("remote local: read terminated (message)");
393 return false;
394 }
395
Josh Gao839b9322018-02-05 18:49:10 -0800396 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gaob14756a2018-02-02 14:38:04 -0800397 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
398 return false;
399 }
400
Josh Gao839b9322018-02-05 18:49:10 -0800401 packet->payload.resize(packet->msg.data_length);
402
403 if (!ReadFdExactly(fd_.get(), &packet->payload[0], packet->payload.size())) {
Josh Gao395b86a2018-01-28 20:32:46 -0800404 D("remote local: terminated (data)");
405 return false;
406 }
407
408 return true;
409}
410
411bool FdConnection::Write(apacket* packet) {
Josh Gao839b9322018-02-05 18:49:10 -0800412 if (!WriteFdExactly(fd_.get(), &packet->msg, sizeof(packet->msg))) {
Josh Gao395b86a2018-01-28 20:32:46 -0800413 D("remote local: write terminated");
414 return false;
415 }
416
Josh Gao839b9322018-02-05 18:49:10 -0800417 if (packet->msg.data_length) {
418 if (!WriteFdExactly(fd_.get(), &packet->payload[0], packet->msg.data_length)) {
419 D("remote local: write terminated");
420 return false;
421 }
422 }
423
Josh Gao395b86a2018-01-28 20:32:46 -0800424 return true;
425}
426
427void FdConnection::Close() {
428 adb_shutdown(fd_.get());
429 fd_.reset();
430}
431
Josh Gao67ac3792016-10-06 13:31:44 -0700432void send_packet(apacket* p, atransport* t) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800433 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayee7b44d2017-12-07 11:40:00 -0800434 // compute a checksum for connection/auth packets for compatibility reasons
435 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
436 p->msg.data_check = 0;
437 } else {
438 p->msg.data_check = calculate_apacket_checksum(p);
439 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800440
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700441 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800442
Yi Kong86e67182018-07-13 18:15:16 -0700443 if (t == nullptr) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700444 LOG(FATAL) << "Transport is null";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800445 }
446
Josh Gao715fe602018-02-16 13:24:58 -0800447 if (t->Write(p) != 0) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700448 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao715fe602018-02-16 13:24:58 -0800449 t->Kick();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800450 }
451}
452
Josh Gao3a2172b2019-03-28 15:47:44 -0700453void kick_transport(atransport* t, bool reset) {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700454 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuid78ed222016-04-05 13:50:44 -0700455 // As kick_transport() can be called from threads without guarantee that t is valid,
456 // check if the transport is in transport_list first.
Josh Gaob39e4152017-08-16 16:57:01 -0700457 //
458 // TODO(jmgao): WTF? Is this actually true?
Yabin Cuid78ed222016-04-05 13:50:44 -0700459 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Josh Gao3a2172b2019-03-28 15:47:44 -0700460 if (reset) {
461 t->Reset();
462 } else {
463 t->Kick();
464 }
Yabin Cuid78ed222016-04-05 13:50:44 -0700465 }
Josh Gao13cb8c02018-08-10 14:44:54 -0700466
467#if ADB_HOST
468 reconnect_handler.CheckForKicked();
469#endif
Yabin Cui4d64fd82015-08-27 12:03:11 -0700470}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800471
472static int transport_registration_send = -1;
473static int transport_registration_recv = -1;
Josh Gao9528df22018-05-14 11:14:33 -0700474static fdevent* transport_registration_fde;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800475
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800476#if ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800477
478/* this adds support required by the 'track-devices' service.
479 * this is used to send the content of "list_transport" to any
480 * number of client connections that want it through a single
481 * live TCP connection
482 */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800483struct device_tracker {
Josh Gao0d6aa992016-11-22 14:32:34 -0800484 asocket socket;
Josh Gao5cb76ce2018-02-12 17:24:00 -0800485 bool update_needed = false;
486 bool long_output = false;
487 device_tracker* next = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800488};
489
490/* linked list of all device trackers */
Josh Gao0d6aa992016-11-22 14:32:34 -0800491static device_tracker* device_tracker_list;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800492
Josh Gao0d6aa992016-11-22 14:32:34 -0800493static void device_tracker_remove(device_tracker* tracker) {
494 device_tracker** pnode = &device_tracker_list;
495 device_tracker* node = *pnode;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800496
Josh Gaoaaa82f72017-08-17 13:50:51 -0700497 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800498 while (node) {
499 if (node == tracker) {
500 *pnode = node->next;
501 break;
502 }
503 pnode = &node->next;
Josh Gao0d6aa992016-11-22 14:32:34 -0800504 node = *pnode;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800505 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800506}
507
Josh Gao0d6aa992016-11-22 14:32:34 -0800508static void device_tracker_close(asocket* socket) {
509 device_tracker* tracker = (device_tracker*)socket;
510 asocket* peer = socket->peer;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800511
Josh Gao0d6aa992016-11-22 14:32:34 -0800512 D("device tracker %p removed", tracker);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800513 if (peer) {
Yi Kong86e67182018-07-13 18:15:16 -0700514 peer->peer = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800515 peer->close(peer);
516 }
517 device_tracker_remove(tracker);
Josh Gao5cb76ce2018-02-12 17:24:00 -0800518 delete tracker;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800519}
520
Josh Gaocd2a5292018-03-07 16:52:28 -0800521static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800522 /* you can't read from a device tracker, close immediately */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800523 device_tracker_close(socket);
524 return -1;
525}
526
Elliott Hughes88b4c852015-04-30 17:32:03 -0700527static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughes88b4c852015-04-30 17:32:03 -0700528 asocket* peer = tracker->socket.peer;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800529
Josh Gaocd2a5292018-03-07 16:52:28 -0800530 apacket::payload_type data;
Josh Gaoa7d9d712018-02-01 13:17:50 -0800531 data.resize(4 + string.size());
532 char buf[5];
533 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
534 memcpy(&data[0], buf, 4);
535 memcpy(&data[4], string.data(), string.size());
536 return peer->enqueue(peer, std::move(data));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800537}
538
Elliott Hughes88b4c852015-04-30 17:32:03 -0700539static void device_tracker_ready(asocket* socket) {
540 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800541
Elliott Hughes88b4c852015-04-30 17:32:03 -0700542 // We want to send the device list when the tracker connects
543 // for the first time, even if no update occurred.
Josh Gao32124632017-08-14 18:57:54 -0700544 if (tracker->update_needed) {
545 tracker->update_needed = false;
Elliott Hughes3d792f42019-07-31 14:13:57 -0700546 device_tracker_send(tracker, list_transports(tracker->long_output));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800547 }
548}
549
Josh Gao32124632017-08-14 18:57:54 -0700550asocket* create_device_tracker(bool long_output) {
Josh Gao5cb76ce2018-02-12 17:24:00 -0800551 device_tracker* tracker = new device_tracker();
Elliott Hughese64126b2018-10-19 13:59:44 -0700552 if (tracker == nullptr) LOG(FATAL) << "cannot allocate device tracker";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800553
Josh Gao0d6aa992016-11-22 14:32:34 -0800554 D("device tracker %p created", tracker);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800555
556 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao0d6aa992016-11-22 14:32:34 -0800557 tracker->socket.ready = device_tracker_ready;
558 tracker->socket.close = device_tracker_close;
Josh Gao32124632017-08-14 18:57:54 -0700559 tracker->update_needed = true;
560 tracker->long_output = long_output;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800561
Josh Gao0d6aa992016-11-22 14:32:34 -0800562 tracker->next = device_tracker_list;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800563 device_tracker_list = tracker;
564
565 return &tracker->socket;
566}
567
Josh Gao1e3bf732017-05-03 22:37:10 -0700568// Check if all of the USB transports are connected.
569bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700570 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao1e3bf732017-05-03 22:37:10 -0700571 for (const auto& t : transport_list) {
572 if (!fn(t)) {
573 return false;
574 }
575 }
576 for (const auto& t : pending_list) {
577 if (!fn(t)) {
578 return false;
579 }
580 }
581 return true;
582}
583
Elliott Hughes88b4c852015-04-30 17:32:03 -0700584// Call this function each time the transport list has changed.
585void update_transports() {
Josh Gao1e3bf732017-05-03 22:37:10 -0700586 update_transport_status();
587
588 // Notify `adb track-devices` clients.
Elliott Hughes88b4c852015-04-30 17:32:03 -0700589 device_tracker* tracker = device_tracker_list;
590 while (tracker != nullptr) {
591 device_tracker* next = tracker->next;
592 // This may destroy the tracker if the connection is closed.
Elliott Hughes3d792f42019-07-31 14:13:57 -0700593 device_tracker_send(tracker, list_transports(tracker->long_output));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800594 tracker = next;
595 }
596}
Elliott Hughes88b4c852015-04-30 17:32:03 -0700597
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800598#else
Elliott Hughes88b4c852015-04-30 17:32:03 -0700599
600void update_transports() {
601 // Nothing to do on the device side.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800602}
Elliott Hughes88b4c852015-04-30 17:32:03 -0700603
Josh Gao0d6aa992016-11-22 14:32:34 -0800604#endif // ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800605
Josh Gao0d6aa992016-11-22 14:32:34 -0800606struct tmsg {
607 atransport* transport;
608 int action;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800609};
610
Josh Gao0d6aa992016-11-22 14:32:34 -0800611static int transport_read_action(int fd, struct tmsg* m) {
612 char* p = (char*)m;
613 int len = sizeof(*m);
614 int r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800615
Josh Gao0d6aa992016-11-22 14:32:34 -0800616 while (len > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800617 r = adb_read(fd, p, len);
Josh Gao0d6aa992016-11-22 14:32:34 -0800618 if (r > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800619 len -= r;
Josh Gao0d6aa992016-11-22 14:32:34 -0800620 p += r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800621 } else {
Yabin Cui815ad882015-09-02 17:44:28 -0700622 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800623 return -1;
624 }
625 }
626 return 0;
627}
628
Josh Gao0d6aa992016-11-22 14:32:34 -0800629static int transport_write_action(int fd, struct tmsg* m) {
630 char* p = (char*)m;
631 int len = sizeof(*m);
632 int r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800633
Josh Gao0d6aa992016-11-22 14:32:34 -0800634 while (len > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800635 r = adb_write(fd, p, len);
Josh Gao0d6aa992016-11-22 14:32:34 -0800636 if (r > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800637 len -= r;
Josh Gao0d6aa992016-11-22 14:32:34 -0800638 p += r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800639 } else {
Yabin Cui815ad882015-09-02 17:44:28 -0700640 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800641 return -1;
642 }
643 }
644 return 0;
645}
646
Josh Gao715fe602018-02-16 13:24:58 -0800647static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800648 tmsg m;
Josh Gao0d6aa992016-11-22 14:32:34 -0800649 atransport* t;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800650
Josh Gao0d6aa992016-11-22 14:32:34 -0800651 if (!(ev & FDE_READ)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800652 return;
653 }
654
Josh Gao0d6aa992016-11-22 14:32:34 -0800655 if (transport_read_action(_fd, &m)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700656 PLOG(FATAL) << "cannot read transport registration socket";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800657 }
658
659 t = m.transport;
660
Dan Albertbe8e54b2015-05-18 13:06:53 -0700661 if (m.action == 0) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700662 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800663
Josh Gaoe7daf572016-09-21 12:37:10 -0700664 {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700665 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaoe7daf572016-09-21 12:37:10 -0700666 transport_list.remove(t);
667 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800668
Dan Albertecce5032015-05-18 16:46:31 -0700669 delete t;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800670
671 update_transports();
672 return;
673 }
674
Mike Lockwoode45583f2009-08-08 12:37:44 -0400675 /* don't create transport threads for inaccessible devices */
Yabin Cui3cf1b362017-03-10 16:01:01 -0800676 if (t->GetConnectionState() != kCsNoPerm) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700677 // The connection gets a reference to the atransport. It will release it
678 // upon a read/write error.
679 t->ref_count++;
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700680 t->connection()->SetTransportName(t->serial_name());
681 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao715fe602018-02-16 13:24:58 -0800682 if (!check_header(p.get(), t)) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700683 D("%s: remote read: bad header", t->serial.c_str());
Josh Gao715fe602018-02-16 13:24:58 -0800684 return false;
685 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800686
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700687 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "from remote", p.get());
Josh Gao715fe602018-02-16 13:24:58 -0800688 apacket* packet = p.release();
Mike Lockwoode45583f2009-08-08 12:37:44 -0400689
Josh Gao715fe602018-02-16 13:24:58 -0800690 // TODO: Does this need to run on the main thread?
691 fdevent_run_on_main_thread([packet, t]() { handle_packet(packet, t); });
692 return true;
693 });
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700694 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Josh Gao3a34bc52018-10-11 16:33:05 -0700695 LOG(INFO) << t->serial_name() << ": connection terminated: " << error;
Josh Gao715fe602018-02-16 13:24:58 -0800696 fdevent_run_on_main_thread([t]() {
697 handle_offline(t);
698 transport_unref(t);
699 });
700 });
Mike Lockwoode45583f2009-08-08 12:37:44 -0400701
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700702 t->connection()->Start();
Josh Gao715fe602018-02-16 13:24:58 -0800703#if ADB_HOST
704 send_connect(t);
705#endif
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800706 }
707
Josh Gaoe7daf572016-09-21 12:37:10 -0700708 {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700709 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700710 auto it = std::find(pending_list.begin(), pending_list.end(), t);
711 if (it != pending_list.end()) {
712 pending_list.remove(t);
713 transport_list.push_front(t);
714 }
Josh Gaoe7daf572016-09-21 12:37:10 -0700715 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800716
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800717 update_transports();
718}
719
Josh Gao5c47e9f2018-07-31 18:28:32 -0700720#if ADB_HOST
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700721void init_reconnect_handler(void) {
722 reconnect_handler.Start();
723}
Josh Gao5c47e9f2018-07-31 18:28:32 -0700724#endif
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700725
Josh Gao0d6aa992016-11-22 14:32:34 -0800726void init_transport_registration(void) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800727 int s[2];
728
Josh Gao0d6aa992016-11-22 14:32:34 -0800729 if (adb_socketpair(s)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700730 PLOG(FATAL) << "cannot open transport registration socketpair";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800731 }
Yabin Cui815ad882015-09-02 17:44:28 -0700732 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800733
734 transport_registration_send = s[0];
735 transport_registration_recv = s[1];
736
Josh Gao9528df22018-05-14 11:14:33 -0700737 transport_registration_fde =
Yi Kong86e67182018-07-13 18:15:16 -0700738 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao9528df22018-05-14 11:14:33 -0700739 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao165460f2017-05-09 13:43:35 -0700740}
741
742void kick_all_transports() {
Josh Gao5c47e9f2018-07-31 18:28:32 -0700743#if ADB_HOST
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700744 reconnect_handler.Stop();
Josh Gao5c47e9f2018-07-31 18:28:32 -0700745#endif
Josh Gao165460f2017-05-09 13:43:35 -0700746 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gaoaaa82f72017-08-17 13:50:51 -0700747 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao165460f2017-05-09 13:43:35 -0700748 for (auto t : transport_list) {
749 t->Kick();
750 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800751}
752
753/* the fdevent select pump is single threaded */
Josh Gao3a34bc52018-10-11 16:33:05 -0700754void register_transport(atransport* transport) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800755 tmsg m;
756 m.transport = transport;
757 m.action = 1;
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700758 D("transport: %s registered", transport->serial.c_str());
Josh Gao0d6aa992016-11-22 14:32:34 -0800759 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700760 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800761 }
762}
763
Josh Gao0d6aa992016-11-22 14:32:34 -0800764static void remove_transport(atransport* transport) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800765 tmsg m;
766 m.transport = transport;
767 m.action = 0;
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700768 D("transport: %s removed", transport->serial.c_str());
Josh Gao0d6aa992016-11-22 14:32:34 -0800769 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700770 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800771 }
772}
773
Yabin Cui4d64fd82015-08-27 12:03:11 -0700774static void transport_unref(atransport* t) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700775 check_main_thread();
Yabin Cui4d64fd82015-08-27 12:03:11 -0700776 CHECK(t != nullptr);
Josh Gaoe7daf572016-09-21 12:37:10 -0700777
Josh Gao4d299742017-09-13 13:40:57 -0700778 std::lock_guard<std::recursive_mutex> lock(transport_lock);
779 CHECK_GT(t->ref_count, 0u);
780 t->ref_count--;
781 if (t->ref_count == 0) {
Josh Gao3a34bc52018-10-11 16:33:05 -0700782 LOG(INFO) << "destroying transport " << t->serial_name();
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700783 t->connection()->Stop();
Josh Gao5c47e9f2018-07-31 18:28:32 -0700784#if ADB_HOST
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700785 if (t->IsTcpDevice() && !t->kicked()) {
Josh Gao5c47e9f2018-07-31 18:28:32 -0700786 D("transport: %s unref (attempting reconnection)", t->serial.c_str());
Josh Gaoeb656522018-12-04 01:07:50 -0800787
788 // We need to clear the transport's keys, so that on the next connection, it tries
789 // again from the beginning.
790 t->ResetKeys();
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700791 reconnect_handler.TrackTransport(t);
792 } else {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700793 D("transport: %s unref (kicking and closing)", t->serial.c_str());
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700794 remove_transport(t);
795 }
Josh Gao5c47e9f2018-07-31 18:28:32 -0700796#else
797 D("transport: %s unref (kicking and closing)", t->serial.c_str());
798 remove_transport(t);
799#endif
800
David 'Digit' Turner58f59682011-01-06 14:11:07 +0100801 } else {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700802 D("transport: %s unref (count=%zu)", t->serial.c_str(), t->ref_count);
Mike Lockwood01c2c302010-05-24 10:44:35 -0400803 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800804}
805
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700806static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao0d6aa992016-11-22 14:32:34 -0800807 bool sanitize_qual) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700808 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
809 return qual.empty();
Scott Anderson27042382012-05-30 18:11:27 -0700810
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700811 if (qual.empty()) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700812
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700813 const char* ptr = to_test.c_str();
Scott Anderson27042382012-05-30 18:11:27 -0700814 if (prefix) {
815 while (*prefix) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700816 if (*prefix++ != *ptr++) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700817 }
818 }
819
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700820 for (char ch : qual) {
Josh Gao0d6aa992016-11-22 14:32:34 -0800821 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700822 if (ch != *ptr++) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700823 }
824
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700825 /* Everything matched so far. Return true if *ptr is a NUL. */
826 return !*ptr;
Scott Anderson27042382012-05-30 18:11:27 -0700827}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800828
Josh Gaob39e4152017-08-16 16:57:01 -0700829atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
830 bool* is_ambiguous, std::string* error_out,
831 bool accept_any_state) {
Elliott Hughes67943d12015-10-07 14:55:10 -0700832 atransport* result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800833
Josh Gaob39e4152017-08-16 16:57:01 -0700834 if (transport_id != 0) {
835 *error_out =
836 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
837 } else if (serial) {
Elliott Hughes67943d12015-10-07 14:55:10 -0700838 *error_out = android::base::StringPrintf("device '%s' not found", serial);
839 } else if (type == kTransportLocal) {
840 *error_out = "no emulators found";
841 } else if (type == kTransportAny) {
842 *error_out = "no devices/emulators found";
843 } else {
844 *error_out = "no devices found";
845 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800846
Josh Gaoaaa82f72017-08-17 13:50:51 -0700847 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes67943d12015-10-07 14:55:10 -0700848 for (const auto& t : transport_list) {
Yabin Cui3cf1b362017-03-10 16:01:01 -0800849 if (t->GetConnectionState() == kCsNoPerm) {
David Pursell6e5c7eb2015-12-02 15:14:31 -0800850 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwoodadc16b32009-08-08 13:53:16 -0400851 continue;
852 }
Mike Lockwoode45583f2009-08-08 12:37:44 -0400853
Josh Gaob39e4152017-08-16 16:57:01 -0700854 if (transport_id) {
855 if (t->id == transport_id) {
856 result = t;
857 break;
858 }
859 } else if (serial) {
David Pursellc929c6f2016-03-01 08:58:26 -0800860 if (t->MatchesTarget(serial)) {
Scott Anderson27042382012-05-30 18:11:27 -0700861 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700862 *error_out = "more than one device";
Elliott Hughes67943d12015-10-07 14:55:10 -0700863 if (is_ambiguous) *is_ambiguous = true;
864 result = nullptr;
Scott Anderson27042382012-05-30 18:11:27 -0700865 break;
866 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800867 result = t;
Scott Anderson6dfaf4b2012-04-20 11:21:14 -0700868 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800869 } else {
Elliott Hughes3aec2ba2015-05-05 13:10:43 -0700870 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800871 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700872 *error_out = "more than one device";
Elliott Hughes67943d12015-10-07 14:55:10 -0700873 if (is_ambiguous) *is_ambiguous = true;
874 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800875 break;
876 }
877 result = t;
Elliott Hughes3aec2ba2015-05-05 13:10:43 -0700878 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800879 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700880 *error_out = "more than one emulator";
Elliott Hughes67943d12015-10-07 14:55:10 -0700881 if (is_ambiguous) *is_ambiguous = true;
882 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800883 break;
884 }
885 result = t;
Elliott Hughes3aec2ba2015-05-05 13:10:43 -0700886 } else if (type == kTransportAny) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800887 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700888 *error_out = "more than one device/emulator";
Elliott Hughes67943d12015-10-07 14:55:10 -0700889 if (is_ambiguous) *is_ambiguous = true;
890 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800891 break;
892 }
893 result = t;
894 }
895 }
896 }
Josh Gaoe7daf572016-09-21 12:37:10 -0700897 lock.unlock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800898
Josh Gao7a7c5cb2018-05-04 16:04:49 -0700899 if (result && !accept_any_state) {
900 // The caller requires an active transport.
901 // Make sure that we're actually connected.
902 ConnectionState state = result->GetConnectionState();
903 switch (state) {
904 case kCsConnecting:
905 *error_out = "device still connecting";
906 result = nullptr;
907 break;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -0700908
Josh Gao7a7c5cb2018-05-04 16:04:49 -0700909 case kCsAuthorizing:
910 *error_out = "device still authorizing";
911 result = nullptr;
912 break;
913
914 case kCsUnauthorized: {
915 *error_out = "device unauthorized.\n";
916 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
917 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
918 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
919 *error_out += "\n";
920 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
921 *error_out += "Otherwise check for a confirmation dialog on your device.";
922 result = nullptr;
923 break;
924 }
925
926 case kCsOffline:
927 *error_out = "device offline";
928 result = nullptr;
929 break;
930
931 default:
932 break;
933 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800934 }
935
936 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700937 *error_out = "success";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800938 }
939
940 return result;
941}
942
Luis Hector Chavezda74b902018-04-17 14:25:04 -0700943bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
944 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao8aa57d22019-02-12 13:59:03 -0800945 ScopedLockAssertion assume_locked(mutex_);
Luis Hector Chavezda74b902018-04-17 14:25:04 -0700946 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
947 return connection_established_ready_;
948 }) && connection_established_;
949}
950
951void ConnectionWaitable::SetConnectionEstablished(bool success) {
952 {
953 std::lock_guard<std::mutex> lock(mutex_);
954 if (connection_established_ready_) return;
955 connection_established_ready_ = true;
956 connection_established_ = success;
957 D("connection established with %d", success);
958 }
959 cv_.notify_one();
960}
961
962atransport::~atransport() {
963 // If the connection callback had not been run before, run it now.
964 SetConnectionEstablished(false);
965}
966
Yabin Cui3cf1b362017-03-10 16:01:01 -0800967int atransport::Write(apacket* p) {
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700968 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cui3cf1b362017-03-10 16:01:01 -0800969}
970
Josh Gao3a2172b2019-03-28 15:47:44 -0700971void atransport::Reset() {
972 if (!kicked_.exchange(true)) {
973 LOG(INFO) << "resetting transport " << this << " " << this->serial;
974 this->connection()->Reset();
975 }
976}
977
Yabin Cuif2a9f9b2016-04-18 11:22:34 -0700978void atransport::Kick() {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -0700979 if (!kicked_.exchange(true)) {
Josh Gao3a2172b2019-03-28 15:47:44 -0700980 LOG(INFO) << "kicking transport " << this << " " << this->serial;
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700981 this->connection()->Stop();
Yabin Cuif2a9f9b2016-04-18 11:22:34 -0700982 }
983}
984
Yabin Cui3cf1b362017-03-10 16:01:01 -0800985ConnectionState atransport::GetConnectionState() const {
986 return connection_state_;
987}
988
989void atransport::SetConnectionState(ConnectionState state) {
990 check_main_thread();
991 connection_state_ = state;
992}
993
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700994void atransport::SetConnection(std::unique_ptr<Connection> connection) {
995 std::lock_guard<std::mutex> lock(mutex_);
996 connection_ = std::shared_ptr<Connection>(std::move(connection));
997}
998
Josh Gao3cd03be2018-02-28 14:44:23 -0800999std::string atransport::connection_state_name() const {
Yabin Cui3cf1b362017-03-10 16:01:01 -08001000 ConnectionState state = GetConnectionState();
1001 switch (state) {
Josh Gao0d6aa992016-11-22 14:32:34 -08001002 case kCsOffline:
1003 return "offline";
1004 case kCsBootloader:
1005 return "bootloader";
1006 case kCsDevice:
1007 return "device";
1008 case kCsHost:
1009 return "host";
1010 case kCsRecovery:
1011 return "recovery";
Tao Bao9d6eca52019-04-07 23:24:03 -07001012 case kCsRescue:
1013 return "rescue";
Josh Gao0d6aa992016-11-22 14:32:34 -08001014 case kCsNoPerm:
1015 return UsbNoPermissionsShortHelpText();
1016 case kCsSideload:
1017 return "sideload";
1018 case kCsUnauthorized:
1019 return "unauthorized";
Josh Gao7a7c5cb2018-05-04 16:04:49 -07001020 case kCsAuthorizing:
1021 return "authorizing";
1022 case kCsConnecting:
1023 return "connecting";
Josh Gao0d6aa992016-11-22 14:32:34 -08001024 default:
1025 return "unknown";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001026 }
1027}
1028
Tamas Berghammera1c60c02015-07-13 19:12:28 +01001029void atransport::update_version(int version, size_t payload) {
1030 protocol_version = std::min(version, A_VERSION);
1031 max_payload = std::min(payload, MAX_PAYLOAD);
1032}
1033
1034int atransport::get_protocol_version() const {
1035 return protocol_version;
1036}
1037
1038size_t atransport::get_max_payload() const {
1039 return max_payload;
1040}
1041
Dan Albertbe8e54b2015-05-18 13:06:53 -07001042const FeatureSet& supported_features() {
David Pursella07dbad2015-09-22 10:43:08 -07001043 // Local static allocation to avoid global non-POD variables.
1044 static const FeatureSet* features = new FeatureSet{
Josh Gao9eeb9f72019-02-20 13:01:40 -08001045 kFeatureShell2,
1046 kFeatureCmd,
1047 kFeatureStat2,
1048 kFeatureFixedPushMkdir,
1049 kFeatureApex,
1050 kFeatureAbb,
1051 kFeatureFixedPushSymlinkTimestamp,
Alex Buynytskyy4f3fa052019-02-21 14:22:51 -08001052 kFeatureAbbExec,
Josh Gaof764d572019-07-11 14:15:32 -07001053 kFeatureRemountShell,
Josh Gao62add5b2018-11-08 22:39:43 -08001054 // Increment ADB_SERVER_VERSION when adding a feature that adbd needs
1055 // to know about. Otherwise, the client can be stuck running an old
1056 // version of the server even after upgrading their copy of adb.
1057 // (http://b/24370690)
David Pursella07dbad2015-09-22 10:43:08 -07001058 };
1059
1060 return *features;
1061}
1062
1063std::string FeatureSetToString(const FeatureSet& features) {
Elliott Hughesc3462f42018-09-05 12:13:11 -07001064 return android::base::Join(features, ',');
David Pursella07dbad2015-09-22 10:43:08 -07001065}
1066
1067FeatureSet StringToFeatureSet(const std::string& features_string) {
David Pursell3d9072b2015-09-25 13:04:21 -07001068 if (features_string.empty()) {
1069 return FeatureSet();
1070 }
1071
Elliott Hughesc3462f42018-09-05 12:13:11 -07001072 auto names = android::base::Split(features_string, ",");
David Pursella07dbad2015-09-22 10:43:08 -07001073 return FeatureSet(names.begin(), names.end());
Dan Albertbe8e54b2015-05-18 13:06:53 -07001074}
1075
David Pursell22fc5e92015-09-30 13:35:42 -07001076bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao0d6aa992016-11-22 14:32:34 -08001077 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell22fc5e92015-09-30 13:35:42 -07001078}
1079
Dan Albertbe8e54b2015-05-18 13:06:53 -07001080bool atransport::has_feature(const std::string& feature) const {
1081 return features_.count(feature) > 0;
1082}
1083
David Pursella07dbad2015-09-22 10:43:08 -07001084void atransport::SetFeatures(const std::string& features_string) {
1085 features_ = StringToFeatureSet(features_string);
Dan Albertbe8e54b2015-05-18 13:06:53 -07001086}
1087
Yabin Cui2d4c1982015-08-28 15:09:44 -07001088void atransport::AddDisconnect(adisconnect* disconnect) {
1089 disconnects_.push_back(disconnect);
1090}
1091
1092void atransport::RemoveDisconnect(adisconnect* disconnect) {
1093 disconnects_.remove(disconnect);
1094}
1095
1096void atransport::RunDisconnects() {
Elliott Hughes85952832015-10-07 15:59:35 -07001097 for (const auto& disconnect : disconnects_) {
Yabin Cui2d4c1982015-08-28 15:09:44 -07001098 disconnect->func(disconnect->opaque, this);
1099 }
1100 disconnects_.clear();
1101}
1102
David Pursellc929c6f2016-03-01 08:58:26 -08001103bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001104 if (!serial.empty()) {
David Pursellc929c6f2016-03-01 08:58:26 -08001105 if (target == serial) {
1106 return true;
1107 } else if (type == kTransportLocal) {
1108 // Local transports can match [tcp:|udp:]<hostname>[:port].
1109 const char* local_target_ptr = target.c_str();
1110
1111 // For fastboot compatibility, ignore protocol prefixes.
1112 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao0d6aa992016-11-22 14:32:34 -08001113 android::base::StartsWith(target, "udp:")) {
David Pursellc929c6f2016-03-01 08:58:26 -08001114 local_target_ptr += 4;
1115 }
1116
1117 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1118 std::string serial_host, error;
1119 int serial_port = -1;
Josh Gao0d6aa992016-11-22 14:32:34 -08001120 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursellc929c6f2016-03-01 08:58:26 -08001121 // |target| may omit the port to default to ours.
1122 std::string target_host;
1123 int target_port = serial_port;
1124 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1125 nullptr, &error) &&
Josh Gao0d6aa992016-11-22 14:32:34 -08001126 serial_host == target_host && serial_port == target_port) {
David Pursellc929c6f2016-03-01 08:58:26 -08001127 return true;
1128 }
1129 }
1130 }
1131 }
1132
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001133 return (target == devpath) || qual_match(target, "product:", product, false) ||
1134 qual_match(target, "model:", model, true) ||
1135 qual_match(target, "device:", device, false);
David Pursellc929c6f2016-03-01 08:58:26 -08001136}
1137
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001138void atransport::SetConnectionEstablished(bool success) {
1139 connection_waitable_->SetConnectionEstablished(success);
1140}
1141
Josh Gaod24580d2018-08-30 11:37:00 -07001142ReconnectResult atransport::Reconnect() {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001143 return reconnect_(this);
1144}
1145
Elliott Hughes88b4c852015-04-30 17:32:03 -07001146#if ADB_HOST
1147
Josh Gaob39e4152017-08-16 16:57:01 -07001148// We use newline as our delimiter, make sure to never output it.
1149static std::string sanitize(std::string str, bool alphanumeric) {
1150 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1151 : [](const char c) { return c == '\n'; };
1152 std::replace_if(str.begin(), str.end(), pred, '_');
1153 return str;
1154}
1155
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001156static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob39e4152017-08-16 16:57:01 -07001157 bool alphanumeric) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001158 if (value.empty()) {
Scott Anderson27042382012-05-30 18:11:27 -07001159 return;
Scott Anderson27042382012-05-30 18:11:27 -07001160 }
1161
Elliott Hughes88b4c852015-04-30 17:32:03 -07001162 *result += ' ';
1163 *result += key;
Josh Gaob39e4152017-08-16 16:57:01 -07001164 *result += sanitize(value, alphanumeric);
Scott Anderson27042382012-05-30 18:11:27 -07001165}
1166
Josh Gao0d6aa992016-11-22 14:32:34 -08001167static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001168 std::string serial = t->serial;
1169 if (serial.empty()) {
Dan Alberta8c34142015-05-06 16:48:52 -07001170 serial = "(no serial number)";
Elliott Hughes88b4c852015-04-30 17:32:03 -07001171 }
Scott Anderson27042382012-05-30 18:11:27 -07001172
1173 if (!long_listing) {
Elliott Hughes88b4c852015-04-30 17:32:03 -07001174 *result += serial;
1175 *result += '\t';
1176 *result += t->connection_state_name();
Scott Anderson27042382012-05-30 18:11:27 -07001177 } else {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001178 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1179 t->connection_state_name().c_str());
Scott Anderson27042382012-05-30 18:11:27 -07001180
Elliott Hughes88b4c852015-04-30 17:32:03 -07001181 append_transport_info(result, "", t->devpath, false);
1182 append_transport_info(result, "product:", t->product, false);
1183 append_transport_info(result, "model:", t->model, true);
1184 append_transport_info(result, "device:", t->device, false);
Josh Gaob39e4152017-08-16 16:57:01 -07001185
1186 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1187 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1188 *result += " transport_id:";
1189 *result += std::to_string(t->id);
Scott Anderson27042382012-05-30 18:11:27 -07001190 }
Elliott Hughes88b4c852015-04-30 17:32:03 -07001191 *result += '\n';
Scott Anderson27042382012-05-30 18:11:27 -07001192}
1193
Elliott Hughes88b4c852015-04-30 17:32:03 -07001194std::string list_transports(bool long_listing) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001195 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov4dd35012017-12-17 10:56:07 +00001196
1197 auto sorted_transport_list = transport_list;
1198 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1199 if (x->type != y->type) {
1200 return x->type < y->type;
1201 }
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001202 return x->serial < y->serial;
Artem Iglikov4dd35012017-12-17 10:56:07 +00001203 });
1204
1205 std::string result;
1206 for (const auto& t : sorted_transport_list) {
Elliott Hughes88b4c852015-04-30 17:32:03 -07001207 append_transport(t, &result, long_listing);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001208 }
Elliott Hughes88b4c852015-04-30 17:32:03 -07001209 return result;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001210}
1211
Josh Gao3a2172b2019-03-28 15:47:44 -07001212void close_usb_devices(std::function<bool(const atransport*)> predicate, bool reset) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001213 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao4e562502016-10-27 14:01:08 -07001214 for (auto& t : transport_list) {
1215 if (predicate(t)) {
Josh Gao3a2172b2019-03-28 15:47:44 -07001216 if (reset) {
1217 t->Reset();
1218 } else {
1219 t->Kick();
1220 }
Josh Gao4e562502016-10-27 14:01:08 -07001221 }
1222 }
1223}
1224
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001225/* hack for osx */
Josh Gao3a2172b2019-03-28 15:47:44 -07001226void close_usb_devices(bool reset) {
1227 close_usb_devices([](const atransport*) { return true; }, reset);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001228}
Josh Gao0d6aa992016-11-22 14:32:34 -08001229#endif // ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001230
Josh Gao597044d2018-08-08 16:20:14 -07001231bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
1232 atransport::ReconnectCallback reconnect, int* error) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001233 atransport* t = new atransport(std::move(reconnect), kCsOffline);
David 'Digit' Turner58f59682011-01-06 14:11:07 +01001234
Josh Gaoa3a71472018-08-02 13:58:24 -07001235 D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
Josh Gaofa3107e2018-07-25 17:21:49 -07001236 if (init_socket_transport(t, std::move(s), port, local) < 0) {
Dan Albertecce5032015-05-18 16:46:31 -07001237 delete t;
Josh Gao597044d2018-08-08 16:20:14 -07001238 if (error) *error = errno;
1239 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001240 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001241
Josh Gaoaaa82f72017-08-17 13:50:51 -07001242 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes85952832015-10-07 15:59:35 -07001243 for (const auto& transport : pending_list) {
Josh Gaoa3a71472018-08-02 13:58:24 -07001244 if (serial == transport->serial) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001245 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao0d6aa992016-11-22 14:32:34 -08001246 << " is already in pending_list and fails to register";
Dan Albertecce5032015-05-18 16:46:31 -07001247 delete t;
Josh Gao597044d2018-08-08 16:20:14 -07001248 if (error) *error = EALREADY;
1249 return false;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001250 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001251 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001252
Elliott Hughes85952832015-10-07 15:59:35 -07001253 for (const auto& transport : transport_list) {
Josh Gaoa3a71472018-08-02 13:58:24 -07001254 if (serial == transport->serial) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001255 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao0d6aa992016-11-22 14:32:34 -08001256 << " is already in transport_list and fails to register";
Dan Albertecce5032015-05-18 16:46:31 -07001257 delete t;
Josh Gao597044d2018-08-08 16:20:14 -07001258 if (error) *error = EALREADY;
1259 return false;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001260 }
1261 }
1262
Josh Gaoa3a71472018-08-02 13:58:24 -07001263 t->serial = std::move(serial);
Dan Albertecce5032015-05-18 16:46:31 -07001264 pending_list.push_front(t);
Josh Gaoe7daf572016-09-21 12:37:10 -07001265
1266 lock.unlock();
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001267
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001268 auto waitable = t->connection_waitable();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001269 register_transport(t);
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001270
Luis Hector Chavez25bc41c2018-05-01 17:12:16 -07001271 if (local == 1) {
1272 // Do not wait for emulator transports.
Josh Gao597044d2018-08-08 16:20:14 -07001273 return true;
Luis Hector Chavez25bc41c2018-05-01 17:12:16 -07001274 }
1275
Josh Gao597044d2018-08-08 16:20:14 -07001276 if (!waitable->WaitForConnection(std::chrono::seconds(10))) {
1277 if (error) *error = ETIMEDOUT;
1278 return false;
1279 }
1280
1281 if (t->GetConnectionState() == kCsUnauthorized) {
1282 if (error) *error = EPERM;
1283 return false;
1284 }
1285
1286 return true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001287}
1288
Mike Lockwood81ffe172009-10-11 23:04:18 -04001289#if ADB_HOST
Josh Gao0d6aa992016-11-22 14:32:34 -08001290atransport* find_transport(const char* serial) {
Dan Albertecce5032015-05-18 16:46:31 -07001291 atransport* result = nullptr;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001292
Josh Gaoaaa82f72017-08-17 13:50:51 -07001293 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui4d64fd82015-08-27 12:03:11 -07001294 for (auto& t : transport_list) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001295 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertecce5032015-05-18 16:46:31 -07001296 result = t;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001297 break;
1298 }
Dan Albertecce5032015-05-18 16:46:31 -07001299 }
Mike Lockwood81ffe172009-10-11 23:04:18 -04001300
Dan Albertecce5032015-05-18 16:46:31 -07001301 return result;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001302}
1303
Yabin Cui4d64fd82015-08-27 12:03:11 -07001304void kick_all_tcp_devices() {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001305 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui4d64fd82015-08-27 12:03:11 -07001306 for (auto& t : transport_list) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001307 if (t->IsTcpDevice()) {
Yabin Cui4e222292015-08-31 11:50:24 -07001308 // Kicking breaks the read_transport thread of this transport out of any read, then
1309 // the read_transport thread will notify the main thread to make this transport
1310 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cui4d64fd82015-08-27 12:03:11 -07001311 // Finally, this transport will be closed and freed in the main thread.
Yabin Cuif2a9f9b2016-04-18 11:22:34 -07001312 t->Kick();
Mike Lockwood01c2c302010-05-24 10:44:35 -04001313 }
Dan Albertecce5032015-05-18 16:46:31 -07001314 }
Josh Gao13cb8c02018-08-10 14:44:54 -07001315#if ADB_HOST
1316 reconnect_handler.CheckForKicked();
1317#endif
Mike Lockwood01c2c302010-05-24 10:44:35 -04001318}
1319
Mike Lockwood81ffe172009-10-11 23:04:18 -04001320#endif
1321
Josh Gao0d6aa992016-11-22 14:32:34 -08001322void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1323 unsigned writeable) {
Luis Hector Chavez0aeda102018-04-20 10:31:29 -07001324 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertecce5032015-05-18 16:46:31 -07001325
Josh Gao0d6aa992016-11-22 14:32:34 -08001326 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cui3cf1b362017-03-10 16:01:01 -08001327 init_usb_transport(t, usb);
Josh Gao0d6aa992016-11-22 14:32:34 -08001328 if (serial) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001329 t->serial = serial;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001330 }
Dan Albertecce5032015-05-18 16:46:31 -07001331
1332 if (devpath) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001333 t->devpath = devpath;
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001334 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001335
Josh Gaoe7daf572016-09-21 12:37:10 -07001336 {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001337 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaoe7daf572016-09-21 12:37:10 -07001338 pending_list.push_front(t);
1339 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001340
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001341 register_transport(t);
1342}
1343
Josh Gao3a34bc52018-10-11 16:33:05 -07001344#if ADB_HOST
Dan Albert9a50f4c2015-05-18 16:43:57 -07001345// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao0d6aa992016-11-22 14:32:34 -08001346void unregister_usb_transport(usb_handle* usb) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001347 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao395b86a2018-01-28 20:32:46 -08001348 transport_list.remove_if([usb](atransport* t) {
Josh Gao68f2c382018-12-11 13:11:52 -08001349 return t->GetUsbHandle() == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gao395b86a2018-01-28 20:32:46 -08001350 });
Mike Lockwoode45583f2009-08-08 12:37:44 -04001351}
Josh Gao3a34bc52018-10-11 16:33:05 -07001352#endif
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001353
Josh Gao67b683a2017-05-16 15:02:45 -07001354bool check_header(apacket* p, atransport* t) {
Josh Gao0d6aa992016-11-22 14:32:34 -08001355 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cui3cf1b362017-03-10 16:01:01 -08001356 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1357 << ", magic = " << p->msg.magic;
Josh Gao67b683a2017-05-16 15:02:45 -07001358 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001359 }
1360
Josh Gao0d6aa992016-11-22 14:32:34 -08001361 if (p->msg.data_length > t->get_max_payload()) {
1362 VLOG(RWX) << "check_header(): " << p->msg.data_length
1363 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao67b683a2017-05-16 15:02:45 -07001364 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001365 }
1366
Josh Gao67b683a2017-05-16 15:02:45 -07001367 return true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001368}
1369
Josh Gaoeac20582016-10-05 19:02:29 -07001370#if ADB_HOST
Josh Gao22cb70b2016-08-18 22:00:12 -07001371std::shared_ptr<RSA> atransport::NextKey() {
Josh Gaoeb656522018-12-04 01:07:50 -08001372 if (keys_.empty()) {
1373 LOG(INFO) << "fetching keys for transport " << this->serial_name();
1374 keys_ = adb_auth_get_private_keys();
1375
1376 // We should have gotten at least one key: the one that's automatically generated.
1377 CHECK(!keys_.empty());
1378 }
Elliott Hughes801066a2016-06-29 17:42:01 -07001379
Josh Gao22cb70b2016-08-18 22:00:12 -07001380 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes801066a2016-06-29 17:42:01 -07001381 keys_.pop_front();
1382 return result;
1383}
Josh Gaoeb656522018-12-04 01:07:50 -08001384
1385void atransport::ResetKeys() {
1386 keys_.clear();
1387}
Josh Gaoeac20582016-10-05 19:02:29 -07001388#endif