blob: 9dd6ec642424aa3798d8a8c0dbb9822525f8dfe1 [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"
Josh Gao57e09b12019-06-28 13:50:37 -070052#include "fdevent/fdevent.h"
Josh Gaoe445a6d2018-07-31 14:12:59 -070053#include "sysdeps/chrono.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080054
Josh Gao982f7bd2019-02-12 13:59:03 -080055using android::base::ScopedLockAssertion;
56
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070057static void remove_transport(atransport* transport);
Josh Gao9a8366b2019-12-09 13:45:31 -080058static void transport_destroy(atransport* transport);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080059
Josh Gaob122b172017-08-16 16:57:01 -070060// TODO: unordered_map<TransportId, atransport*>
Josh Gaob7b1edf2015-11-11 17:56:12 -080061static auto& transport_list = *new std::list<atransport*>();
62static auto& pending_list = *new std::list<atransport*>();
Benoit Goby1c45ee92013-03-29 18:22:36 -070063
Josh Gao1db71af2017-08-17 13:50:51 -070064static auto& transport_lock = *new std::recursive_mutex();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080065
Todd Kennedy51c05ec2015-11-10 00:03:25 +000066const char* const kFeatureShell2 = "shell_v2";
67const char* const kFeatureCmd = "cmd";
Josh Gao5a1e3fd2016-12-05 17:11:34 -080068const char* const kFeatureStat2 = "stat_v2";
Josh Gao34a478f2019-08-07 14:23:17 -070069const char* const kFeatureLs2 = "ls_v2";
Josh Gao5d1756c2017-02-22 17:07:01 -080070const char* const kFeatureLibusb = "libusb";
Dan Albert5176df82017-05-23 14:30:00 -070071const char* const kFeaturePushSync = "push_sync";
Dario Freni29814de2018-10-04 16:26:40 +010072const char* const kFeatureApex = "apex";
Josh Gaofb085102018-10-22 13:00:05 -070073const char* const kFeatureFixedPushMkdir = "fixed_push_mkdir";
Alex Buynytskyy01a65ee2019-01-17 13:13:56 -080074const char* const kFeatureAbb = "abb";
Josh Gao7b1cb662019-02-20 13:01:40 -080075const char* const kFeatureFixedPushSymlinkTimestamp = "fixed_push_symlink_timestamp";
Alex Buynytskyy05626c12019-02-21 14:22:51 -080076const char* const kFeatureAbbExec = "abb_exec";
Josh Gao8c2198c2019-07-11 14:15:32 -070077const char* const kFeatureRemountShell = "remount_shell";
Todd Kennedy51c05ec2015-11-10 00:03:25 +000078
Luis Hector Chavez56fe7532018-04-17 14:25:04 -070079namespace {
80
Josh Gaodef91c02018-07-31 18:28:32 -070081#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070082// Tracks and handles atransport*s that are attempting reconnection.
83class ReconnectHandler {
84 public:
85 ReconnectHandler() = default;
86 ~ReconnectHandler() = default;
87
88 // Starts the ReconnectHandler thread.
89 void Start();
90
91 // Requests the ReconnectHandler thread to stop.
92 void Stop();
93
94 // Adds the atransport* to the queue of reconnect attempts.
95 void TrackTransport(atransport* transport);
96
Josh Gao902dace2018-08-10 14:44:54 -070097 // Wake up the ReconnectHandler thread to have it check for kicked transports.
98 void CheckForKicked();
99
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700100 private:
101 // The main thread loop.
102 void Run();
103
104 // Tracks a reconnection attempt.
105 struct ReconnectAttempt {
106 atransport* transport;
Josh Gao95af6412018-07-30 18:51:55 -0700107 std::chrono::steady_clock::time_point reconnect_time;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700108 size_t attempts_left;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700109
110 bool operator<(const ReconnectAttempt& rhs) const {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700111 if (reconnect_time == rhs.reconnect_time) {
112 return reinterpret_cast<uintptr_t>(transport) <
113 reinterpret_cast<uintptr_t>(rhs.transport);
114 }
115 return reconnect_time < rhs.reconnect_time;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700116 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700117 };
118
119 // Only retry for up to one minute.
Josh Gaoe445a6d2018-07-31 14:12:59 -0700120 static constexpr const std::chrono::seconds kDefaultTimeout = 10s;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700121 static constexpr const size_t kMaxAttempts = 6;
122
123 // Protects all members.
124 std::mutex reconnect_mutex_;
125 bool running_ GUARDED_BY(reconnect_mutex_) = true;
126 std::thread handler_thread_;
127 std::condition_variable reconnect_cv_;
Josh Gao8a40c8a2018-08-10 14:28:24 -0700128 std::set<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700129
130 DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
131};
132
133void ReconnectHandler::Start() {
134 check_main_thread();
135 handler_thread_ = std::thread(&ReconnectHandler::Run, this);
136}
137
138void ReconnectHandler::Stop() {
139 check_main_thread();
140 {
141 std::lock_guard<std::mutex> lock(reconnect_mutex_);
142 running_ = false;
143 }
144 reconnect_cv_.notify_one();
145 handler_thread_.join();
146
147 // Drain the queue to free all resources.
148 std::lock_guard<std::mutex> lock(reconnect_mutex_);
149 while (!reconnect_queue_.empty()) {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700150 ReconnectAttempt attempt = *reconnect_queue_.begin();
151 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700152 remove_transport(attempt.transport);
153 }
154}
155
156void ReconnectHandler::TrackTransport(atransport* transport) {
157 check_main_thread();
158 {
159 std::lock_guard<std::mutex> lock(reconnect_mutex_);
160 if (!running_) return;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700161 // Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
162 auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
163 reconnect_queue_.emplace(
164 ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700165 }
166 reconnect_cv_.notify_one();
167}
168
Josh Gao902dace2018-08-10 14:44:54 -0700169void ReconnectHandler::CheckForKicked() {
170 reconnect_cv_.notify_one();
171}
172
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700173void ReconnectHandler::Run() {
174 while (true) {
175 ReconnectAttempt attempt;
176 {
177 std::unique_lock<std::mutex> lock(reconnect_mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800178 ScopedLockAssertion assume_lock(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700179
Josh Gao95af6412018-07-30 18:51:55 -0700180 if (!reconnect_queue_.empty()) {
181 // FIXME: libstdc++ (used on Windows) implements condition_variable with
182 // system_clock as its clock, so we're probably hosed if the clock changes,
183 // even if we use steady_clock throughout. This problem goes away once we
184 // switch to libc++.
Josh Gao8a40c8a2018-08-10 14:28:24 -0700185 reconnect_cv_.wait_until(lock, reconnect_queue_.begin()->reconnect_time);
Josh Gao95af6412018-07-30 18:51:55 -0700186 } else {
187 reconnect_cv_.wait(lock);
188 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700189
190 if (!running_) return;
Josh Gao902dace2018-08-10 14:44:54 -0700191
192 // Scan the whole list for kicked transports, so that we immediately handle an explicit
193 // disconnect request.
194 bool kicked = false;
195 for (auto it = reconnect_queue_.begin(); it != reconnect_queue_.end();) {
196 if (it->transport->kicked()) {
197 D("transport %s was kicked. giving up on it.", it->transport->serial.c_str());
198 remove_transport(it->transport);
199 it = reconnect_queue_.erase(it);
200 } else {
201 ++it;
202 }
203 kicked = true;
204 }
205
Josh Gao95af6412018-07-30 18:51:55 -0700206 if (reconnect_queue_.empty()) continue;
207
Josh Gao902dace2018-08-10 14:44:54 -0700208 // Go back to sleep if we either woke up spuriously, or we were woken up to remove
209 // a kicked transport, and the first transport isn't ready for reconnection yet.
Josh Gao95af6412018-07-30 18:51:55 -0700210 auto now = std::chrono::steady_clock::now();
Josh Gao8a40c8a2018-08-10 14:28:24 -0700211 if (reconnect_queue_.begin()->reconnect_time > now) {
Josh Gao95af6412018-07-30 18:51:55 -0700212 continue;
213 }
214
Josh Gao8a40c8a2018-08-10 14:28:24 -0700215 attempt = *reconnect_queue_.begin();
216 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700217 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700218 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700219
Josh Gaofc2e56f2018-08-30 11:37:00 -0700220 switch (attempt.transport->Reconnect()) {
221 case ReconnectResult::Retry: {
222 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
223 if (attempt.attempts_left == 0) {
224 D("transport %s exceeded the number of retry attempts. giving up on it.",
225 attempt.transport->serial.c_str());
226 remove_transport(attempt.transport);
227 continue;
228 }
229
230 std::lock_guard<std::mutex> lock(reconnect_mutex_);
231 reconnect_queue_.emplace(ReconnectAttempt{
232 attempt.transport,
233 std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
234 attempt.attempts_left - 1});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700235 continue;
236 }
237
Josh Gaofc2e56f2018-08-30 11:37:00 -0700238 case ReconnectResult::Success:
239 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
240 register_transport(attempt.transport);
241 continue;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700242
Josh Gaofc2e56f2018-08-30 11:37:00 -0700243 case ReconnectResult::Abort:
244 D("cancelling reconnection attempt to %s.", attempt.transport->serial.c_str());
245 remove_transport(attempt.transport);
246 continue;
247 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700248 }
249}
250
251static auto& reconnect_handler = *new ReconnectHandler();
252
Josh Gaodef91c02018-07-31 18:28:32 -0700253#endif
254
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700255} // namespace
256
Josh Gaob122b172017-08-16 16:57:01 -0700257TransportId NextTransportId() {
258 static std::atomic<TransportId> next(1);
259 return next++;
260}
261
Josh Gao3705b342019-03-28 15:47:44 -0700262void Connection::Reset() {
263 LOG(INFO) << "Connection::Reset(): stopping";
264 Stop();
265}
266
Josh Gao0bbf69c2018-02-16 13:24:58 -0800267BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
268 : underlying_(std::move(connection)) {}
269
270BlockingConnectionAdapter::~BlockingConnectionAdapter() {
271 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
272 Stop();
273}
274
275void BlockingConnectionAdapter::Start() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700276 std::lock_guard<std::mutex> lock(mutex_);
277 if (started_) {
278 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
279 << "): started multiple times";
280 }
281
Josh Gao0bbf69c2018-02-16 13:24:58 -0800282 read_thread_ = std::thread([this]() {
283 LOG(INFO) << this->transport_name_ << ": read thread spawning";
284 while (true) {
Josh Gao31b5be62018-03-07 16:51:08 -0800285 auto packet = std::make_unique<apacket>();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800286 if (!underlying_->Read(packet.get())) {
287 PLOG(INFO) << this->transport_name_ << ": read failed";
288 break;
289 }
290 read_callback_(this, std::move(packet));
291 }
292 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
293 });
294
295 write_thread_ = std::thread([this]() {
296 LOG(INFO) << this->transport_name_ << ": write thread spawning";
297 while (true) {
298 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800299 ScopedLockAssertion assume_locked(mutex_);
Josh Gaoc251ec52018-04-03 12:55:18 -0700300 cv_.wait(lock, [this]() REQUIRES(mutex_) {
301 return this->stopped_ || !this->write_queue_.empty();
302 });
303
Josh Gao0bbf69c2018-02-16 13:24:58 -0800304 if (this->stopped_) {
305 return;
306 }
307
308 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
309 this->write_queue_.pop_front();
310 lock.unlock();
311
312 if (!this->underlying_->Write(packet.get())) {
313 break;
314 }
315 }
316 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
317 });
Josh Gaoc251ec52018-04-03 12:55:18 -0700318
319 started_ = true;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800320}
321
Josh Gao3705b342019-03-28 15:47:44 -0700322void BlockingConnectionAdapter::Reset() {
323 {
324 std::lock_guard<std::mutex> lock(mutex_);
325 if (!started_) {
326 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
327 return;
328 }
329
330 if (stopped_) {
331 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
332 << "): already stopped";
333 return;
334 }
335 }
336
337 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): resetting";
338 this->underlying_->Reset();
339 Stop();
340}
341
Josh Gao0bbf69c2018-02-16 13:24:58 -0800342void BlockingConnectionAdapter::Stop() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700343 {
344 std::lock_guard<std::mutex> lock(mutex_);
345 if (!started_) {
346 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
347 return;
348 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800349
Josh Gaoc251ec52018-04-03 12:55:18 -0700350 if (stopped_) {
351 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
352 << "): already stopped";
353 return;
354 }
355
356 stopped_ = true;
357 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800358
359 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
360
361 this->underlying_->Close();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800362 this->cv_.notify_one();
Josh Gaoc251ec52018-04-03 12:55:18 -0700363
364 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
365 std::thread read_thread;
366 std::thread write_thread;
367
368 {
369 std::lock_guard<std::mutex> lock(mutex_);
370 read_thread = std::move(read_thread_);
371 write_thread = std::move(write_thread_);
372 }
373
374 read_thread.join();
375 write_thread.join();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800376
377 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
378 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
379}
380
381bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
382 {
Josh Gaoc251ec52018-04-03 12:55:18 -0700383 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800384 write_queue_.emplace_back(std::move(packet));
385 }
386
387 cv_.notify_one();
388 return true;
389}
390
Josh Gaob800d882018-01-28 20:32:46 -0800391bool FdConnection::Read(apacket* packet) {
392 if (!ReadFdExactly(fd_.get(), &packet->msg, sizeof(amessage))) {
393 D("remote local: read terminated (message)");
394 return false;
395 }
396
Josh Gaof571fcb2018-02-05 18:49:10 -0800397 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gao5caaebd2018-02-02 14:38:04 -0800398 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
399 return false;
400 }
401
Josh Gaof571fcb2018-02-05 18:49:10 -0800402 packet->payload.resize(packet->msg.data_length);
403
404 if (!ReadFdExactly(fd_.get(), &packet->payload[0], packet->payload.size())) {
Josh Gaob800d882018-01-28 20:32:46 -0800405 D("remote local: terminated (data)");
406 return false;
407 }
408
409 return true;
410}
411
412bool FdConnection::Write(apacket* packet) {
Josh Gaof571fcb2018-02-05 18:49:10 -0800413 if (!WriteFdExactly(fd_.get(), &packet->msg, sizeof(packet->msg))) {
Josh Gaob800d882018-01-28 20:32:46 -0800414 D("remote local: write terminated");
415 return false;
416 }
417
Josh Gaof571fcb2018-02-05 18:49:10 -0800418 if (packet->msg.data_length) {
419 if (!WriteFdExactly(fd_.get(), &packet->payload[0], packet->msg.data_length)) {
420 D("remote local: write terminated");
421 return false;
422 }
423 }
424
Josh Gaob800d882018-01-28 20:32:46 -0800425 return true;
426}
427
428void FdConnection::Close() {
429 adb_shutdown(fd_.get());
430 fd_.reset();
431}
432
Josh Gao06d61d42016-10-06 13:31:44 -0700433void send_packet(apacket* p, atransport* t) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800434 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayde471942017-12-07 11:40:00 -0800435 // compute a checksum for connection/auth packets for compatibility reasons
436 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
437 p->msg.data_check = 0;
438 } else {
439 p->msg.data_check = calculate_apacket_checksum(p);
440 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800441
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700442 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800443
Yi Kongaed415c2018-07-13 18:15:16 -0700444 if (t == nullptr) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700445 LOG(FATAL) << "Transport is null";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800446 }
447
Josh Gao0bbf69c2018-02-16 13:24:58 -0800448 if (t->Write(p) != 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700449 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800450 t->Kick();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800451 }
452}
453
Josh Gao3705b342019-03-28 15:47:44 -0700454void kick_transport(atransport* t, bool reset) {
Josh Gao1db71af2017-08-17 13:50:51 -0700455 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui1f4ec192016-04-05 13:50:44 -0700456 // As kick_transport() can be called from threads without guarantee that t is valid,
457 // check if the transport is in transport_list first.
Josh Gaob122b172017-08-16 16:57:01 -0700458 //
459 // TODO(jmgao): WTF? Is this actually true?
Yabin Cui1f4ec192016-04-05 13:50:44 -0700460 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Josh Gao3705b342019-03-28 15:47:44 -0700461 if (reset) {
462 t->Reset();
463 } else {
464 t->Kick();
465 }
Yabin Cui1f4ec192016-04-05 13:50:44 -0700466 }
Josh Gao902dace2018-08-10 14:44:54 -0700467
468#if ADB_HOST
469 reconnect_handler.CheckForKicked();
470#endif
Yabin Cuif4b99282015-08-27 12:03:11 -0700471}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800472
473static int transport_registration_send = -1;
474static int transport_registration_recv = -1;
Josh Gao71f775a2018-05-14 11:14:33 -0700475static fdevent* transport_registration_fde;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800476
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800477#if ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800478
479/* this adds support required by the 'track-devices' service.
480 * this is used to send the content of "list_transport" to any
481 * number of client connections that want it through a single
482 * live TCP connection
483 */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800484struct device_tracker {
Josh Gao1290fbf2016-11-22 14:32:34 -0800485 asocket socket;
Josh Gaoe0361d12018-02-12 17:24:00 -0800486 bool update_needed = false;
487 bool long_output = false;
488 device_tracker* next = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800489};
490
491/* linked list of all device trackers */
Josh Gao1290fbf2016-11-22 14:32:34 -0800492static device_tracker* device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800493
Josh Gao1290fbf2016-11-22 14:32:34 -0800494static void device_tracker_remove(device_tracker* tracker) {
495 device_tracker** pnode = &device_tracker_list;
496 device_tracker* node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800497
Josh Gao1db71af2017-08-17 13:50:51 -0700498 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800499 while (node) {
500 if (node == tracker) {
501 *pnode = node->next;
502 break;
503 }
504 pnode = &node->next;
Josh Gao1290fbf2016-11-22 14:32:34 -0800505 node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800506 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800507}
508
Josh Gao1290fbf2016-11-22 14:32:34 -0800509static void device_tracker_close(asocket* socket) {
510 device_tracker* tracker = (device_tracker*)socket;
511 asocket* peer = socket->peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800512
Josh Gao1290fbf2016-11-22 14:32:34 -0800513 D("device tracker %p removed", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800514 if (peer) {
Yi Kongaed415c2018-07-13 18:15:16 -0700515 peer->peer = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800516 peer->close(peer);
517 }
518 device_tracker_remove(tracker);
Josh Gaoe0361d12018-02-12 17:24:00 -0800519 delete tracker;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800520}
521
Josh Gao1ce99572018-03-07 16:52:28 -0800522static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800523 /* you can't read from a device tracker, close immediately */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800524 device_tracker_close(socket);
525 return -1;
526}
527
Elliott Hughese67f1f82015-04-30 17:32:03 -0700528static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700529 asocket* peer = tracker->socket.peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800530
Josh Gao1ce99572018-03-07 16:52:28 -0800531 apacket::payload_type data;
Josh Gao27cb7dc2018-02-01 13:17:50 -0800532 data.resize(4 + string.size());
533 char buf[5];
534 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
535 memcpy(&data[0], buf, 4);
536 memcpy(&data[4], string.data(), string.size());
537 return peer->enqueue(peer, std::move(data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800538}
539
Elliott Hughese67f1f82015-04-30 17:32:03 -0700540static void device_tracker_ready(asocket* socket) {
541 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800542
Elliott Hughese67f1f82015-04-30 17:32:03 -0700543 // We want to send the device list when the tracker connects
544 // for the first time, even if no update occurred.
Josh Gaob0c18022017-08-14 18:57:54 -0700545 if (tracker->update_needed) {
546 tracker->update_needed = false;
Elliott Hughesfc2f5f62019-07-31 14:13:57 -0700547 device_tracker_send(tracker, list_transports(tracker->long_output));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800548 }
549}
550
Josh Gaob0c18022017-08-14 18:57:54 -0700551asocket* create_device_tracker(bool long_output) {
Josh Gaoe0361d12018-02-12 17:24:00 -0800552 device_tracker* tracker = new device_tracker();
Elliott Hughes4679a392018-10-19 13:59:44 -0700553 if (tracker == nullptr) LOG(FATAL) << "cannot allocate device tracker";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800554
Josh Gao1290fbf2016-11-22 14:32:34 -0800555 D("device tracker %p created", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800556
557 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao1290fbf2016-11-22 14:32:34 -0800558 tracker->socket.ready = device_tracker_ready;
559 tracker->socket.close = device_tracker_close;
Josh Gaob0c18022017-08-14 18:57:54 -0700560 tracker->update_needed = true;
561 tracker->long_output = long_output;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800562
Josh Gao1290fbf2016-11-22 14:32:34 -0800563 tracker->next = device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800564 device_tracker_list = tracker;
565
566 return &tracker->socket;
567}
568
Josh Gaofd713e52017-05-03 22:37:10 -0700569// Check if all of the USB transports are connected.
570bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gao1db71af2017-08-17 13:50:51 -0700571 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaofd713e52017-05-03 22:37:10 -0700572 for (const auto& t : transport_list) {
573 if (!fn(t)) {
574 return false;
575 }
576 }
577 for (const auto& t : pending_list) {
578 if (!fn(t)) {
579 return false;
580 }
581 }
582 return true;
583}
584
Elliott Hughese67f1f82015-04-30 17:32:03 -0700585// Call this function each time the transport list has changed.
586void update_transports() {
Josh Gaofd713e52017-05-03 22:37:10 -0700587 update_transport_status();
588
589 // Notify `adb track-devices` clients.
Elliott Hughese67f1f82015-04-30 17:32:03 -0700590 device_tracker* tracker = device_tracker_list;
591 while (tracker != nullptr) {
592 device_tracker* next = tracker->next;
593 // This may destroy the tracker if the connection is closed.
Elliott Hughesfc2f5f62019-07-31 14:13:57 -0700594 device_tracker_send(tracker, list_transports(tracker->long_output));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800595 tracker = next;
596 }
597}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700598
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800599#else
Elliott Hughese67f1f82015-04-30 17:32:03 -0700600
601void update_transports() {
602 // Nothing to do on the device side.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800603}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700604
Josh Gao1290fbf2016-11-22 14:32:34 -0800605#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800606
Josh Gao1290fbf2016-11-22 14:32:34 -0800607struct tmsg {
608 atransport* transport;
609 int action;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800610};
611
Josh Gao1290fbf2016-11-22 14:32:34 -0800612static int transport_read_action(int fd, struct tmsg* m) {
613 char* p = (char*)m;
614 int len = sizeof(*m);
615 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800616
Josh Gao1290fbf2016-11-22 14:32:34 -0800617 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800618 r = adb_read(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800619 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800620 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800621 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800622 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700623 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800624 return -1;
625 }
626 }
627 return 0;
628}
629
Josh Gao1290fbf2016-11-22 14:32:34 -0800630static int transport_write_action(int fd, struct tmsg* m) {
631 char* p = (char*)m;
632 int len = sizeof(*m);
633 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800634
Josh Gao1290fbf2016-11-22 14:32:34 -0800635 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800636 r = adb_write(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800637 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800638 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800639 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800640 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700641 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800642 return -1;
643 }
644 }
645 return 0;
646}
647
Josh Gao0bbf69c2018-02-16 13:24:58 -0800648static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800649 tmsg m;
Josh Gao1290fbf2016-11-22 14:32:34 -0800650 atransport* t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800651
Josh Gao1290fbf2016-11-22 14:32:34 -0800652 if (!(ev & FDE_READ)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800653 return;
654 }
655
Josh Gao1290fbf2016-11-22 14:32:34 -0800656 if (transport_read_action(_fd, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700657 PLOG(FATAL) << "cannot read transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800658 }
659
660 t = m.transport;
661
Dan Albert1792c232015-05-18 13:06:53 -0700662 if (m.action == 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700663 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800664
Josh Gao0cd3ae12016-09-21 12:37:10 -0700665 {
Josh Gao1db71af2017-08-17 13:50:51 -0700666 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700667 transport_list.remove(t);
668 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800669
Dan Albertc7915a32015-05-18 16:46:31 -0700670 delete t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800671
672 update_transports();
673 return;
674 }
675
Mike Lockwood0927bf92009-08-08 12:37:44 -0400676 /* don't create transport threads for inaccessible devices */
Yabin Cuib5e11412017-03-10 16:01:01 -0800677 if (t->GetConnectionState() != kCsNoPerm) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700678 // The connection gets a reference to the atransport. It will release it
679 // upon a read/write error.
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700680 t->connection()->SetTransportName(t->serial_name());
681 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao0bbf69c2018-02-16 13:24:58 -0800682 if (!check_header(p.get(), t)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700683 D("%s: remote read: bad header", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800684 return false;
685 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800686
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700687 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "from remote", p.get());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800688 apacket* packet = p.release();
Mike Lockwood0927bf92009-08-08 12:37:44 -0400689
Josh Gao0bbf69c2018-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 Chavez9a388d52018-04-25 08:56:41 -0700694 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700695 LOG(INFO) << t->serial_name() << ": connection terminated: " << error;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800696 fdevent_run_on_main_thread([t]() {
697 handle_offline(t);
Josh Gao9a8366b2019-12-09 13:45:31 -0800698 transport_destroy(t);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800699 });
700 });
Mike Lockwood0927bf92009-08-08 12:37:44 -0400701
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700702 t->connection()->Start();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800703#if ADB_HOST
704 send_connect(t);
705#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800706 }
707
Josh Gao0cd3ae12016-09-21 12:37:10 -0700708 {
Josh Gao1db71af2017-08-17 13:50:51 -0700709 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez454bc7c2018-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 Gao0cd3ae12016-09-21 12:37:10 -0700715 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800716
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800717 update_transports();
718}
719
Josh Gaodef91c02018-07-31 18:28:32 -0700720#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700721void init_reconnect_handler(void) {
722 reconnect_handler.Start();
723}
Josh Gaodef91c02018-07-31 18:28:32 -0700724#endif
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700725
Josh Gao1290fbf2016-11-22 14:32:34 -0800726void init_transport_registration(void) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800727 int s[2];
728
Josh Gao1290fbf2016-11-22 14:32:34 -0800729 if (adb_socketpair(s)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700730 PLOG(FATAL) << "cannot open transport registration socketpair";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800731 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700732 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800733
734 transport_registration_send = s[0];
735 transport_registration_recv = s[1];
736
Josh Gao71f775a2018-05-14 11:14:33 -0700737 transport_registration_fde =
Yi Kongaed415c2018-07-13 18:15:16 -0700738 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao71f775a2018-05-14 11:14:33 -0700739 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao01b7bc42017-05-09 13:43:35 -0700740}
741
742void kick_all_transports() {
Josh Gaodef91c02018-07-31 18:28:32 -0700743#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700744 reconnect_handler.Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700745#endif
Josh Gao01b7bc42017-05-09 13:43:35 -0700746 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gao1db71af2017-08-17 13:50:51 -0700747 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao01b7bc42017-05-09 13:43:35 -0700748 for (auto t : transport_list) {
749 t->Kick();
750 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800751}
752
753/* the fdevent select pump is single threaded */
Josh Gaoc51726c2018-10-11 16:33:05 -0700754void register_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800755 tmsg m;
756 m.transport = transport;
757 m.action = 1;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700758 D("transport: %s registered", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800759 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700760 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800761 }
762}
763
Josh Gao1290fbf2016-11-22 14:32:34 -0800764static void remove_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800765 tmsg m;
766 m.transport = transport;
767 m.action = 0;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700768 D("transport: %s removed", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800769 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700770 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800771 }
772}
773
Josh Gao9a8366b2019-12-09 13:45:31 -0800774static void transport_destroy(atransport* t) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700775 check_main_thread();
Yabin Cuif4b99282015-08-27 12:03:11 -0700776 CHECK(t != nullptr);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700777
Josh Gaoe48ecce2017-09-13 13:40:57 -0700778 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao9a8366b2019-12-09 13:45:31 -0800779 LOG(INFO) << "destroying transport " << t->serial_name();
780 t->connection()->Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700781#if ADB_HOST
Josh Gao9a8366b2019-12-09 13:45:31 -0800782 if (t->IsTcpDevice() && !t->kicked()) {
783 D("transport: %s destroy (attempting reconnection)", t->serial.c_str());
Josh Gao4414e4c2018-12-04 01:07:50 -0800784
Josh Gao9a8366b2019-12-09 13:45:31 -0800785 // We need to clear the transport's keys, so that on the next connection, it tries
786 // again from the beginning.
787 t->ResetKeys();
788 reconnect_handler.TrackTransport(t);
789 return;
790 }
Josh Gaodef91c02018-07-31 18:28:32 -0700791#endif
792
Josh Gao9a8366b2019-12-09 13:45:31 -0800793 D("transport: %s destroy (kicking and closing)", t->serial.c_str());
794 remove_transport(t);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800795}
796
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700797static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao1290fbf2016-11-22 14:32:34 -0800798 bool sanitize_qual) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700799 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
800 return qual.empty();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700801
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700802 if (qual.empty()) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700803
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700804 const char* ptr = to_test.c_str();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700805 if (prefix) {
806 while (*prefix) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700807 if (*prefix++ != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700808 }
809 }
810
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700811 for (char ch : qual) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800812 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700813 if (ch != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700814 }
815
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700816 /* Everything matched so far. Return true if *ptr is a NUL. */
817 return !*ptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700818}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800819
Josh Gaob122b172017-08-16 16:57:01 -0700820atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
821 bool* is_ambiguous, std::string* error_out,
822 bool accept_any_state) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700823 atransport* result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800824
Josh Gaob122b172017-08-16 16:57:01 -0700825 if (transport_id != 0) {
826 *error_out =
827 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
828 } else if (serial) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700829 *error_out = android::base::StringPrintf("device '%s' not found", serial);
830 } else if (type == kTransportLocal) {
831 *error_out = "no emulators found";
832 } else if (type == kTransportAny) {
833 *error_out = "no devices/emulators found";
834 } else {
835 *error_out = "no devices found";
836 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800837
Josh Gao1db71af2017-08-17 13:50:51 -0700838 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes8d28e192015-10-07 14:55:10 -0700839 for (const auto& t : transport_list) {
Yabin Cuib5e11412017-03-10 16:01:01 -0800840 if (t->GetConnectionState() == kCsNoPerm) {
David Purselld2acbd12015-12-02 15:14:31 -0800841 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwood37d31112009-08-08 13:53:16 -0400842 continue;
843 }
Mike Lockwood0927bf92009-08-08 12:37:44 -0400844
Josh Gaob122b172017-08-16 16:57:01 -0700845 if (transport_id) {
846 if (t->id == transport_id) {
847 result = t;
848 break;
849 }
850 } else if (serial) {
David Pursell3f902aa2016-03-01 08:58:26 -0800851 if (t->MatchesTarget(serial)) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700852 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700853 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700854 if (is_ambiguous) *is_ambiguous = true;
855 result = nullptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700856 break;
857 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800858 result = t;
Scott Andersone109d262012-04-20 11:21:14 -0700859 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800860 } else {
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700861 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800862 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700863 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700864 if (is_ambiguous) *is_ambiguous = true;
865 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800866 break;
867 }
868 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700869 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800870 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700871 *error_out = "more than one emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700872 if (is_ambiguous) *is_ambiguous = true;
873 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800874 break;
875 }
876 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700877 } else if (type == kTransportAny) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800878 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700879 *error_out = "more than one device/emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700880 if (is_ambiguous) *is_ambiguous = true;
881 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800882 break;
883 }
884 result = t;
885 }
886 }
887 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700888 lock.unlock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800889
Josh Gao704494b2018-05-04 16:04:49 -0700890 if (result && !accept_any_state) {
891 // The caller requires an active transport.
892 // Make sure that we're actually connected.
893 ConnectionState state = result->GetConnectionState();
894 switch (state) {
895 case kCsConnecting:
896 *error_out = "device still connecting";
897 result = nullptr;
898 break;
Benoit Goby77e8e582013-01-15 12:36:47 -0800899
Josh Gao704494b2018-05-04 16:04:49 -0700900 case kCsAuthorizing:
901 *error_out = "device still authorizing";
902 result = nullptr;
903 break;
904
905 case kCsUnauthorized: {
906 *error_out = "device unauthorized.\n";
907 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
908 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
909 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
910 *error_out += "\n";
911 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
912 *error_out += "Otherwise check for a confirmation dialog on your device.";
913 result = nullptr;
914 break;
915 }
916
917 case kCsOffline:
918 *error_out = "device offline";
919 result = nullptr;
920 break;
921
922 default:
923 break;
924 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800925 }
926
927 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700928 *error_out = "success";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800929 }
930
931 return result;
932}
933
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700934bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
935 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800936 ScopedLockAssertion assume_locked(mutex_);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700937 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
938 return connection_established_ready_;
939 }) && connection_established_;
940}
941
942void ConnectionWaitable::SetConnectionEstablished(bool success) {
943 {
944 std::lock_guard<std::mutex> lock(mutex_);
945 if (connection_established_ready_) return;
946 connection_established_ready_ = true;
947 connection_established_ = success;
948 D("connection established with %d", success);
949 }
950 cv_.notify_one();
951}
952
953atransport::~atransport() {
954 // If the connection callback had not been run before, run it now.
955 SetConnectionEstablished(false);
956}
957
Yabin Cuib5e11412017-03-10 16:01:01 -0800958int atransport::Write(apacket* p) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700959 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cuib5e11412017-03-10 16:01:01 -0800960}
961
Josh Gao3705b342019-03-28 15:47:44 -0700962void atransport::Reset() {
963 if (!kicked_.exchange(true)) {
964 LOG(INFO) << "resetting transport " << this << " " << this->serial;
965 this->connection()->Reset();
966 }
967}
968
Yabin Cui7f274902016-04-18 11:22:34 -0700969void atransport::Kick() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700970 if (!kicked_.exchange(true)) {
Josh Gao3705b342019-03-28 15:47:44 -0700971 LOG(INFO) << "kicking transport " << this << " " << this->serial;
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700972 this->connection()->Stop();
Yabin Cui7f274902016-04-18 11:22:34 -0700973 }
974}
975
Yabin Cuib5e11412017-03-10 16:01:01 -0800976ConnectionState atransport::GetConnectionState() const {
977 return connection_state_;
978}
979
980void atransport::SetConnectionState(ConnectionState state) {
981 check_main_thread();
982 connection_state_ = state;
983}
984
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700985void atransport::SetConnection(std::unique_ptr<Connection> connection) {
986 std::lock_guard<std::mutex> lock(mutex_);
987 connection_ = std::shared_ptr<Connection>(std::move(connection));
988}
989
Josh Gaoffbd3362018-02-28 14:44:23 -0800990std::string atransport::connection_state_name() const {
Yabin Cuib5e11412017-03-10 16:01:01 -0800991 ConnectionState state = GetConnectionState();
992 switch (state) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800993 case kCsOffline:
994 return "offline";
995 case kCsBootloader:
996 return "bootloader";
997 case kCsDevice:
998 return "device";
999 case kCsHost:
1000 return "host";
1001 case kCsRecovery:
1002 return "recovery";
Tao Bao55d407e2019-04-07 23:24:03 -07001003 case kCsRescue:
1004 return "rescue";
Josh Gao1290fbf2016-11-22 14:32:34 -08001005 case kCsNoPerm:
1006 return UsbNoPermissionsShortHelpText();
1007 case kCsSideload:
1008 return "sideload";
1009 case kCsUnauthorized:
1010 return "unauthorized";
Josh Gao704494b2018-05-04 16:04:49 -07001011 case kCsAuthorizing:
1012 return "authorizing";
1013 case kCsConnecting:
1014 return "connecting";
Josh Gao1290fbf2016-11-22 14:32:34 -08001015 default:
1016 return "unknown";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001017 }
1018}
1019
Tamas Berghammer3d2904c2015-07-13 19:12:28 +01001020void atransport::update_version(int version, size_t payload) {
1021 protocol_version = std::min(version, A_VERSION);
1022 max_payload = std::min(payload, MAX_PAYLOAD);
1023}
1024
1025int atransport::get_protocol_version() const {
1026 return protocol_version;
1027}
1028
1029size_t atransport::get_max_payload() const {
1030 return max_payload;
1031}
1032
Dan Albert1792c232015-05-18 13:06:53 -07001033const FeatureSet& supported_features() {
David Pursell4e2fd362015-09-22 10:43:08 -07001034 // Local static allocation to avoid global non-POD variables.
1035 static const FeatureSet* features = new FeatureSet{
Josh Gao7b1cb662019-02-20 13:01:40 -08001036 kFeatureShell2,
1037 kFeatureCmd,
1038 kFeatureStat2,
Josh Gao34a478f2019-08-07 14:23:17 -07001039 kFeatureLs2,
Josh Gao7b1cb662019-02-20 13:01:40 -08001040 kFeatureFixedPushMkdir,
1041 kFeatureApex,
1042 kFeatureAbb,
1043 kFeatureFixedPushSymlinkTimestamp,
Alex Buynytskyy05626c12019-02-21 14:22:51 -08001044 kFeatureAbbExec,
Josh Gao8c2198c2019-07-11 14:15:32 -07001045 kFeatureRemountShell,
Josh Gao919b70c2018-11-08 22:39:43 -08001046 // Increment ADB_SERVER_VERSION when adding a feature that adbd needs
1047 // to know about. Otherwise, the client can be stuck running an old
1048 // version of the server even after upgrading their copy of adb.
1049 // (http://b/24370690)
David Pursell4e2fd362015-09-22 10:43:08 -07001050 };
1051
1052 return *features;
1053}
1054
1055std::string FeatureSetToString(const FeatureSet& features) {
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001056 return android::base::Join(features, ',');
David Pursell4e2fd362015-09-22 10:43:08 -07001057}
1058
1059FeatureSet StringToFeatureSet(const std::string& features_string) {
David Purselld2b588e2015-09-25 13:04:21 -07001060 if (features_string.empty()) {
1061 return FeatureSet();
1062 }
1063
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001064 auto names = android::base::Split(features_string, ",");
David Pursell4e2fd362015-09-22 10:43:08 -07001065 return FeatureSet(names.begin(), names.end());
Dan Albert1792c232015-05-18 13:06:53 -07001066}
1067
David Pursell70ef7b42015-09-30 13:35:42 -07001068bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001069 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell70ef7b42015-09-30 13:35:42 -07001070}
1071
Dan Albert1792c232015-05-18 13:06:53 -07001072bool atransport::has_feature(const std::string& feature) const {
1073 return features_.count(feature) > 0;
1074}
1075
David Pursell4e2fd362015-09-22 10:43:08 -07001076void atransport::SetFeatures(const std::string& features_string) {
1077 features_ = StringToFeatureSet(features_string);
Dan Albert1792c232015-05-18 13:06:53 -07001078}
1079
Yabin Cuib3298242015-08-28 15:09:44 -07001080void atransport::AddDisconnect(adisconnect* disconnect) {
1081 disconnects_.push_back(disconnect);
1082}
1083
1084void atransport::RemoveDisconnect(adisconnect* disconnect) {
1085 disconnects_.remove(disconnect);
1086}
1087
1088void atransport::RunDisconnects() {
Elliott Hughes65fe2512015-10-07 15:59:35 -07001089 for (const auto& disconnect : disconnects_) {
Yabin Cuib3298242015-08-28 15:09:44 -07001090 disconnect->func(disconnect->opaque, this);
1091 }
1092 disconnects_.clear();
1093}
1094
David Pursell3f902aa2016-03-01 08:58:26 -08001095bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001096 if (!serial.empty()) {
David Pursell3f902aa2016-03-01 08:58:26 -08001097 if (target == serial) {
1098 return true;
1099 } else if (type == kTransportLocal) {
1100 // Local transports can match [tcp:|udp:]<hostname>[:port].
1101 const char* local_target_ptr = target.c_str();
1102
1103 // For fastboot compatibility, ignore protocol prefixes.
1104 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao1290fbf2016-11-22 14:32:34 -08001105 android::base::StartsWith(target, "udp:")) {
David Pursell3f902aa2016-03-01 08:58:26 -08001106 local_target_ptr += 4;
1107 }
1108
1109 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1110 std::string serial_host, error;
1111 int serial_port = -1;
Josh Gao1290fbf2016-11-22 14:32:34 -08001112 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursell3f902aa2016-03-01 08:58:26 -08001113 // |target| may omit the port to default to ours.
1114 std::string target_host;
1115 int target_port = serial_port;
1116 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1117 nullptr, &error) &&
Josh Gao1290fbf2016-11-22 14:32:34 -08001118 serial_host == target_host && serial_port == target_port) {
David Pursell3f902aa2016-03-01 08:58:26 -08001119 return true;
1120 }
1121 }
1122 }
1123 }
1124
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001125 return (target == devpath) || qual_match(target, "product:", product, false) ||
1126 qual_match(target, "model:", model, true) ||
1127 qual_match(target, "device:", device, false);
David Pursell3f902aa2016-03-01 08:58:26 -08001128}
1129
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001130void atransport::SetConnectionEstablished(bool success) {
1131 connection_waitable_->SetConnectionEstablished(success);
1132}
1133
Josh Gaofc2e56f2018-08-30 11:37:00 -07001134ReconnectResult atransport::Reconnect() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001135 return reconnect_(this);
1136}
1137
Elliott Hughese67f1f82015-04-30 17:32:03 -07001138#if ADB_HOST
1139
Josh Gaob122b172017-08-16 16:57:01 -07001140// We use newline as our delimiter, make sure to never output it.
1141static std::string sanitize(std::string str, bool alphanumeric) {
1142 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1143 : [](const char c) { return c == '\n'; };
1144 std::replace_if(str.begin(), str.end(), pred, '_');
1145 return str;
1146}
1147
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001148static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob122b172017-08-16 16:57:01 -07001149 bool alphanumeric) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001150 if (value.empty()) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001151 return;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001152 }
1153
Elliott Hughese67f1f82015-04-30 17:32:03 -07001154 *result += ' ';
1155 *result += key;
Josh Gaob122b172017-08-16 16:57:01 -07001156 *result += sanitize(value, alphanumeric);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001157}
1158
Josh Gao1290fbf2016-11-22 14:32:34 -08001159static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001160 std::string serial = t->serial;
1161 if (serial.empty()) {
Dan Albertd99d9022015-05-06 16:48:52 -07001162 serial = "(no serial number)";
Elliott Hughese67f1f82015-04-30 17:32:03 -07001163 }
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001164
1165 if (!long_listing) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001166 *result += serial;
1167 *result += '\t';
1168 *result += t->connection_state_name();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001169 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001170 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1171 t->connection_state_name().c_str());
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001172
Elliott Hughese67f1f82015-04-30 17:32:03 -07001173 append_transport_info(result, "", t->devpath, false);
1174 append_transport_info(result, "product:", t->product, false);
1175 append_transport_info(result, "model:", t->model, true);
1176 append_transport_info(result, "device:", t->device, false);
Josh Gaob122b172017-08-16 16:57:01 -07001177
1178 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1179 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1180 *result += " transport_id:";
1181 *result += std::to_string(t->id);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001182 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001183 *result += '\n';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001184}
1185
Elliott Hughese67f1f82015-04-30 17:32:03 -07001186std::string list_transports(bool long_listing) {
Josh Gao1db71af2017-08-17 13:50:51 -07001187 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov04398a92017-12-17 10:56:07 +00001188
1189 auto sorted_transport_list = transport_list;
1190 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1191 if (x->type != y->type) {
1192 return x->type < y->type;
1193 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001194 return x->serial < y->serial;
Artem Iglikov04398a92017-12-17 10:56:07 +00001195 });
1196
1197 std::string result;
1198 for (const auto& t : sorted_transport_list) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001199 append_transport(t, &result, long_listing);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001200 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001201 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001202}
1203
Josh Gao3705b342019-03-28 15:47:44 -07001204void close_usb_devices(std::function<bool(const atransport*)> predicate, bool reset) {
Josh Gao1db71af2017-08-17 13:50:51 -07001205 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao22d2b3e2016-10-27 14:01:08 -07001206 for (auto& t : transport_list) {
1207 if (predicate(t)) {
Josh Gao3705b342019-03-28 15:47:44 -07001208 if (reset) {
1209 t->Reset();
1210 } else {
1211 t->Kick();
1212 }
Josh Gao22d2b3e2016-10-27 14:01:08 -07001213 }
1214 }
1215}
1216
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001217/* hack for osx */
Josh Gao3705b342019-03-28 15:47:44 -07001218void close_usb_devices(bool reset) {
1219 close_usb_devices([](const atransport*) { return true; }, reset);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001220}
Josh Gao1290fbf2016-11-22 14:32:34 -08001221#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001222
Josh Gao362e6962018-08-08 16:20:14 -07001223bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
1224 atransport::ReconnectCallback reconnect, int* error) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001225 atransport* t = new atransport(std::move(reconnect), kCsOffline);
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +01001226
Josh Gao3b4de3c2018-08-02 13:58:24 -07001227 D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
Josh Gao56300c92018-07-25 17:21:49 -07001228 if (init_socket_transport(t, std::move(s), port, local) < 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001229 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001230 if (error) *error = errno;
1231 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001232 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001233
Josh Gao1db71af2017-08-17 13:50:51 -07001234 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes65fe2512015-10-07 15:59:35 -07001235 for (const auto& transport : pending_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001236 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001237 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001238 << " is already in pending_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001239 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001240 if (error) *error = EALREADY;
1241 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001242 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001243 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001244
Elliott Hughes65fe2512015-10-07 15:59:35 -07001245 for (const auto& transport : transport_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001246 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001247 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001248 << " is already in transport_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001249 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001250 if (error) *error = EALREADY;
1251 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001252 }
1253 }
1254
Josh Gao3b4de3c2018-08-02 13:58:24 -07001255 t->serial = std::move(serial);
Dan Albertc7915a32015-05-18 16:46:31 -07001256 pending_list.push_front(t);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001257
1258 lock.unlock();
Benoit Goby1c45ee92013-03-29 18:22:36 -07001259
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001260 auto waitable = t->connection_waitable();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001261 register_transport(t);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001262
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001263 if (local == 1) {
1264 // Do not wait for emulator transports.
Josh Gao362e6962018-08-08 16:20:14 -07001265 return true;
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001266 }
1267
Josh Gao362e6962018-08-08 16:20:14 -07001268 if (!waitable->WaitForConnection(std::chrono::seconds(10))) {
1269 if (error) *error = ETIMEDOUT;
1270 return false;
1271 }
1272
1273 if (t->GetConnectionState() == kCsUnauthorized) {
1274 if (error) *error = EPERM;
1275 return false;
1276 }
1277
1278 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001279}
1280
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001281#if ADB_HOST
Josh Gao1290fbf2016-11-22 14:32:34 -08001282atransport* find_transport(const char* serial) {
Dan Albertc7915a32015-05-18 16:46:31 -07001283 atransport* result = nullptr;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001284
Josh Gao1db71af2017-08-17 13:50:51 -07001285 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001286 for (auto& t : transport_list) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001287 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001288 result = t;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001289 break;
1290 }
Dan Albertc7915a32015-05-18 16:46:31 -07001291 }
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001292
Dan Albertc7915a32015-05-18 16:46:31 -07001293 return result;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001294}
1295
Yabin Cuif4b99282015-08-27 12:03:11 -07001296void kick_all_tcp_devices() {
Josh Gao1db71af2017-08-17 13:50:51 -07001297 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001298 for (auto& t : transport_list) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001299 if (t->IsTcpDevice()) {
Yabin Cuid6ab3c22015-08-31 11:50:24 -07001300 // Kicking breaks the read_transport thread of this transport out of any read, then
1301 // the read_transport thread will notify the main thread to make this transport
1302 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cuif4b99282015-08-27 12:03:11 -07001303 // Finally, this transport will be closed and freed in the main thread.
Yabin Cui7f274902016-04-18 11:22:34 -07001304 t->Kick();
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001305 }
Dan Albertc7915a32015-05-18 16:46:31 -07001306 }
Josh Gao902dace2018-08-10 14:44:54 -07001307#if ADB_HOST
1308 reconnect_handler.CheckForKicked();
1309#endif
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001310}
1311
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001312#endif
1313
Josh Gao1290fbf2016-11-22 14:32:34 -08001314void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1315 unsigned writeable) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001316 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertc7915a32015-05-18 16:46:31 -07001317
Josh Gao1290fbf2016-11-22 14:32:34 -08001318 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cuib5e11412017-03-10 16:01:01 -08001319 init_usb_transport(t, usb);
Josh Gao1290fbf2016-11-22 14:32:34 -08001320 if (serial) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001321 t->serial = serial;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001322 }
Dan Albertc7915a32015-05-18 16:46:31 -07001323
1324 if (devpath) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001325 t->devpath = devpath;
Scott Andersone109d262012-04-20 11:21:14 -07001326 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001327
Josh Gao0cd3ae12016-09-21 12:37:10 -07001328 {
Josh Gao1db71af2017-08-17 13:50:51 -07001329 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001330 pending_list.push_front(t);
1331 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001332
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001333 register_transport(t);
1334}
1335
Josh Gaoc51726c2018-10-11 16:33:05 -07001336#if ADB_HOST
Dan Albertdcd78a12015-05-18 16:43:57 -07001337// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao1290fbf2016-11-22 14:32:34 -08001338void unregister_usb_transport(usb_handle* usb) {
Josh Gao1db71af2017-08-17 13:50:51 -07001339 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaob800d882018-01-28 20:32:46 -08001340 transport_list.remove_if([usb](atransport* t) {
Josh Gaoce5ce872018-12-11 13:11:52 -08001341 return t->GetUsbHandle() == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gaob800d882018-01-28 20:32:46 -08001342 });
Mike Lockwood0927bf92009-08-08 12:37:44 -04001343}
Josh Gaoc51726c2018-10-11 16:33:05 -07001344#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001345
Josh Gao36dadca2017-05-16 15:02:45 -07001346bool check_header(apacket* p, atransport* t) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001347 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cuib5e11412017-03-10 16:01:01 -08001348 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1349 << ", magic = " << p->msg.magic;
Josh Gao36dadca2017-05-16 15:02:45 -07001350 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001351 }
1352
Josh Gao1290fbf2016-11-22 14:32:34 -08001353 if (p->msg.data_length > t->get_max_payload()) {
1354 VLOG(RWX) << "check_header(): " << p->msg.data_length
1355 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao36dadca2017-05-16 15:02:45 -07001356 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001357 }
1358
Josh Gao36dadca2017-05-16 15:02:45 -07001359 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001360}
1361
Josh Gao3bd28792016-10-05 19:02:29 -07001362#if ADB_HOST
Josh Gao2e671202016-08-18 22:00:12 -07001363std::shared_ptr<RSA> atransport::NextKey() {
Josh Gao4414e4c2018-12-04 01:07:50 -08001364 if (keys_.empty()) {
1365 LOG(INFO) << "fetching keys for transport " << this->serial_name();
1366 keys_ = adb_auth_get_private_keys();
1367
1368 // We should have gotten at least one key: the one that's automatically generated.
1369 CHECK(!keys_.empty());
1370 }
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001371
Josh Gao2e671202016-08-18 22:00:12 -07001372 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001373 keys_.pop_front();
1374 return result;
1375}
Josh Gao4414e4c2018-12-04 01:07:50 -08001376
1377void atransport::ResetKeys() {
1378 keys_.clear();
1379}
Josh Gao3bd28792016-10-05 19:02:29 -07001380#endif