blob: 0c7b0b69b0a31d064821b2313694df1760d77f67 [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yabin Cuiaed3c612015-09-22 15:52:57 -070017#define TRACE_TAG TRANSPORT
Dan Albert76649012015-02-24 15:51:19 -080018
Dan Albert33134262015-03-19 15:21:08 -070019#include "sysdeps.h"
Josh Gao31b5be62018-03-07 16:51:08 -080020
Dan Albert76649012015-02-24 15:51:19 -080021#include "transport.h"
22
Dan Albert055f1aa2015-02-20 17:24:58 -080023#include <ctype.h>
Dan Albert76649012015-02-24 15:51:19 -080024#include <errno.h>
Josh Gaob122b172017-08-16 16:57:01 -070025#include <inttypes.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080026#include <stdio.h>
27#include <stdlib.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080028#include <string.h>
Dan Albert76649012015-02-24 15:51:19 -080029#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080030
Spencer Low363af562015-11-07 18:51:54 -080031#include <algorithm>
Josh Gao0bbf69c2018-02-16 13:24:58 -080032#include <deque>
Dan Albertc7915a32015-05-18 16:46:31 -070033#include <list>
Pirama Arumuga Nainar29e3dd82018-08-08 10:33:24 -070034#include <memory>
Josh Gao0cd3ae12016-09-21 12:37:10 -070035#include <mutex>
Josh Gao8a40c8a2018-08-10 14:28:24 -070036#include <set>
Josh Gaoe1dacfc2017-04-12 17:00:49 -070037#include <thread>
Dan Albertc7915a32015-05-18 16:46:31 -070038
Elliott Hughes4f713192015-12-04 22:00:26 -080039#include <android-base/logging.h>
David Pursell3f902aa2016-03-01 08:58:26 -080040#include <android-base/parsenetaddress.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080041#include <android-base/stringprintf.h>
42#include <android-base/strings.h>
Josh Gaob122b172017-08-16 16:57:01 -070043#include <android-base/thread_annotations.h>
Elliott Hughese67f1f82015-04-30 17:32:03 -070044
Josh Gao27768452018-01-02 12:01:43 -080045#include <diagnose_usb.h>
46
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080047#include "adb.h"
Elliott Hughes0aeb5052016-06-29 17:42:01 -070048#include "adb_auth.h"
Josh Gaob800d882018-01-28 20:32:46 -080049#include "adb_io.h"
Josh Gaocfe72e22016-11-29 09:40:29 -080050#include "adb_trace.h"
Elliott Hughese67f1f82015-04-30 17:32:03 -070051#include "adb_utils.h"
Yabin Cuib5e11412017-03-10 16:01:01 -080052#include "fdevent.h"
Josh Gaoe445a6d2018-07-31 14:12:59 -070053#include "sysdeps/chrono.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080054
Josh Gao982f7bd2019-02-12 13:59:03 -080055using android::base::ScopedLockAssertion;
56
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070057static void remove_transport(atransport* transport);
58static void transport_unref(atransport* transport);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080059
Josh Gaob122b172017-08-16 16:57:01 -070060// TODO: unordered_map<TransportId, atransport*>
Josh Gaob7b1edf2015-11-11 17:56:12 -080061static auto& transport_list = *new std::list<atransport*>();
62static auto& pending_list = *new std::list<atransport*>();
Benoit Goby1c45ee92013-03-29 18:22:36 -070063
Josh Gao1db71af2017-08-17 13:50:51 -070064static auto& transport_lock = *new std::recursive_mutex();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080065
Todd Kennedy51c05ec2015-11-10 00:03:25 +000066const char* const kFeatureShell2 = "shell_v2";
67const char* const kFeatureCmd = "cmd";
Josh Gao5a1e3fd2016-12-05 17:11:34 -080068const char* const kFeatureStat2 = "stat_v2";
Josh Gao5d1756c2017-02-22 17:07:01 -080069const char* const kFeatureLibusb = "libusb";
Dan Albert5176df82017-05-23 14:30:00 -070070const char* const kFeaturePushSync = "push_sync";
Dario Freni29814de2018-10-04 16:26:40 +010071const char* const kFeatureApex = "apex";
Josh Gaofb085102018-10-22 13:00:05 -070072const char* const kFeatureFixedPushMkdir = "fixed_push_mkdir";
Alex Buynytskyy01a65ee2019-01-17 13:13:56 -080073const char* const kFeatureAbb = "abb";
Josh Gao7b1cb662019-02-20 13:01:40 -080074const char* const kFeatureFixedPushSymlinkTimestamp = "fixed_push_symlink_timestamp";
Todd Kennedy51c05ec2015-11-10 00:03:25 +000075
Luis Hector Chavez56fe7532018-04-17 14:25:04 -070076namespace {
77
Josh Gaodef91c02018-07-31 18:28:32 -070078#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070079// Tracks and handles atransport*s that are attempting reconnection.
80class ReconnectHandler {
81 public:
82 ReconnectHandler() = default;
83 ~ReconnectHandler() = default;
84
85 // Starts the ReconnectHandler thread.
86 void Start();
87
88 // Requests the ReconnectHandler thread to stop.
89 void Stop();
90
91 // Adds the atransport* to the queue of reconnect attempts.
92 void TrackTransport(atransport* transport);
93
Josh Gao902dace2018-08-10 14:44:54 -070094 // Wake up the ReconnectHandler thread to have it check for kicked transports.
95 void CheckForKicked();
96
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -070097 private:
98 // The main thread loop.
99 void Run();
100
101 // Tracks a reconnection attempt.
102 struct ReconnectAttempt {
103 atransport* transport;
Josh Gao95af6412018-07-30 18:51:55 -0700104 std::chrono::steady_clock::time_point reconnect_time;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700105 size_t attempts_left;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700106
107 bool operator<(const ReconnectAttempt& rhs) const {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700108 if (reconnect_time == rhs.reconnect_time) {
109 return reinterpret_cast<uintptr_t>(transport) <
110 reinterpret_cast<uintptr_t>(rhs.transport);
111 }
112 return reconnect_time < rhs.reconnect_time;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700113 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700114 };
115
116 // Only retry for up to one minute.
Josh Gaoe445a6d2018-07-31 14:12:59 -0700117 static constexpr const std::chrono::seconds kDefaultTimeout = 10s;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700118 static constexpr const size_t kMaxAttempts = 6;
119
120 // Protects all members.
121 std::mutex reconnect_mutex_;
122 bool running_ GUARDED_BY(reconnect_mutex_) = true;
123 std::thread handler_thread_;
124 std::condition_variable reconnect_cv_;
Josh Gao8a40c8a2018-08-10 14:28:24 -0700125 std::set<ReconnectAttempt> reconnect_queue_ GUARDED_BY(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700126
127 DISALLOW_COPY_AND_ASSIGN(ReconnectHandler);
128};
129
130void ReconnectHandler::Start() {
131 check_main_thread();
132 handler_thread_ = std::thread(&ReconnectHandler::Run, this);
133}
134
135void ReconnectHandler::Stop() {
136 check_main_thread();
137 {
138 std::lock_guard<std::mutex> lock(reconnect_mutex_);
139 running_ = false;
140 }
141 reconnect_cv_.notify_one();
142 handler_thread_.join();
143
144 // Drain the queue to free all resources.
145 std::lock_guard<std::mutex> lock(reconnect_mutex_);
146 while (!reconnect_queue_.empty()) {
Josh Gao8a40c8a2018-08-10 14:28:24 -0700147 ReconnectAttempt attempt = *reconnect_queue_.begin();
148 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700149 remove_transport(attempt.transport);
150 }
151}
152
153void ReconnectHandler::TrackTransport(atransport* transport) {
154 check_main_thread();
155 {
156 std::lock_guard<std::mutex> lock(reconnect_mutex_);
157 if (!running_) return;
Josh Gaoe445a6d2018-07-31 14:12:59 -0700158 // Arbitrary sleep to give adbd time to get ready, if we disconnected because it exited.
159 auto reconnect_time = std::chrono::steady_clock::now() + 250ms;
160 reconnect_queue_.emplace(
161 ReconnectAttempt{transport, reconnect_time, ReconnectHandler::kMaxAttempts});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700162 }
163 reconnect_cv_.notify_one();
164}
165
Josh Gao902dace2018-08-10 14:44:54 -0700166void ReconnectHandler::CheckForKicked() {
167 reconnect_cv_.notify_one();
168}
169
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700170void ReconnectHandler::Run() {
171 while (true) {
172 ReconnectAttempt attempt;
173 {
174 std::unique_lock<std::mutex> lock(reconnect_mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800175 ScopedLockAssertion assume_lock(reconnect_mutex_);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700176
Josh Gao95af6412018-07-30 18:51:55 -0700177 if (!reconnect_queue_.empty()) {
178 // FIXME: libstdc++ (used on Windows) implements condition_variable with
179 // system_clock as its clock, so we're probably hosed if the clock changes,
180 // even if we use steady_clock throughout. This problem goes away once we
181 // switch to libc++.
Josh Gao8a40c8a2018-08-10 14:28:24 -0700182 reconnect_cv_.wait_until(lock, reconnect_queue_.begin()->reconnect_time);
Josh Gao95af6412018-07-30 18:51:55 -0700183 } else {
184 reconnect_cv_.wait(lock);
185 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700186
187 if (!running_) return;
Josh Gao902dace2018-08-10 14:44:54 -0700188
189 // Scan the whole list for kicked transports, so that we immediately handle an explicit
190 // disconnect request.
191 bool kicked = false;
192 for (auto it = reconnect_queue_.begin(); it != reconnect_queue_.end();) {
193 if (it->transport->kicked()) {
194 D("transport %s was kicked. giving up on it.", it->transport->serial.c_str());
195 remove_transport(it->transport);
196 it = reconnect_queue_.erase(it);
197 } else {
198 ++it;
199 }
200 kicked = true;
201 }
202
Josh Gao95af6412018-07-30 18:51:55 -0700203 if (reconnect_queue_.empty()) continue;
204
Josh Gao902dace2018-08-10 14:44:54 -0700205 // Go back to sleep if we either woke up spuriously, or we were woken up to remove
206 // a kicked transport, and the first transport isn't ready for reconnection yet.
Josh Gao95af6412018-07-30 18:51:55 -0700207 auto now = std::chrono::steady_clock::now();
Josh Gao8a40c8a2018-08-10 14:28:24 -0700208 if (reconnect_queue_.begin()->reconnect_time > now) {
Josh Gao95af6412018-07-30 18:51:55 -0700209 continue;
210 }
211
Josh Gao8a40c8a2018-08-10 14:28:24 -0700212 attempt = *reconnect_queue_.begin();
213 reconnect_queue_.erase(reconnect_queue_.begin());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700214 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700215 D("attempting to reconnect %s", attempt.transport->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700216
Josh Gaofc2e56f2018-08-30 11:37:00 -0700217 switch (attempt.transport->Reconnect()) {
218 case ReconnectResult::Retry: {
219 D("attempting to reconnect %s failed.", attempt.transport->serial.c_str());
220 if (attempt.attempts_left == 0) {
221 D("transport %s exceeded the number of retry attempts. giving up on it.",
222 attempt.transport->serial.c_str());
223 remove_transport(attempt.transport);
224 continue;
225 }
226
227 std::lock_guard<std::mutex> lock(reconnect_mutex_);
228 reconnect_queue_.emplace(ReconnectAttempt{
229 attempt.transport,
230 std::chrono::steady_clock::now() + ReconnectHandler::kDefaultTimeout,
231 attempt.attempts_left - 1});
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700232 continue;
233 }
234
Josh Gaofc2e56f2018-08-30 11:37:00 -0700235 case ReconnectResult::Success:
236 D("reconnection to %s succeeded.", attempt.transport->serial.c_str());
237 register_transport(attempt.transport);
238 continue;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700239
Josh Gaofc2e56f2018-08-30 11:37:00 -0700240 case ReconnectResult::Abort:
241 D("cancelling reconnection attempt to %s.", attempt.transport->serial.c_str());
242 remove_transport(attempt.transport);
243 continue;
244 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700245 }
246}
247
248static auto& reconnect_handler = *new ReconnectHandler();
249
Josh Gaodef91c02018-07-31 18:28:32 -0700250#endif
251
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700252} // namespace
253
Josh Gaob122b172017-08-16 16:57:01 -0700254TransportId NextTransportId() {
255 static std::atomic<TransportId> next(1);
256 return next++;
257}
258
Josh Gao0bbf69c2018-02-16 13:24:58 -0800259BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
260 : underlying_(std::move(connection)) {}
261
262BlockingConnectionAdapter::~BlockingConnectionAdapter() {
263 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
264 Stop();
265}
266
267void BlockingConnectionAdapter::Start() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700268 std::lock_guard<std::mutex> lock(mutex_);
269 if (started_) {
270 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
271 << "): started multiple times";
272 }
273
Josh Gao0bbf69c2018-02-16 13:24:58 -0800274 read_thread_ = std::thread([this]() {
275 LOG(INFO) << this->transport_name_ << ": read thread spawning";
276 while (true) {
Josh Gao31b5be62018-03-07 16:51:08 -0800277 auto packet = std::make_unique<apacket>();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800278 if (!underlying_->Read(packet.get())) {
279 PLOG(INFO) << this->transport_name_ << ": read failed";
280 break;
281 }
282 read_callback_(this, std::move(packet));
283 }
284 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
285 });
286
287 write_thread_ = std::thread([this]() {
288 LOG(INFO) << this->transport_name_ << ": write thread spawning";
289 while (true) {
290 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800291 ScopedLockAssertion assume_locked(mutex_);
Josh Gaoc251ec52018-04-03 12:55:18 -0700292 cv_.wait(lock, [this]() REQUIRES(mutex_) {
293 return this->stopped_ || !this->write_queue_.empty();
294 });
295
Josh Gao0bbf69c2018-02-16 13:24:58 -0800296 if (this->stopped_) {
297 return;
298 }
299
300 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
301 this->write_queue_.pop_front();
302 lock.unlock();
303
304 if (!this->underlying_->Write(packet.get())) {
305 break;
306 }
307 }
308 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
309 });
Josh Gaoc251ec52018-04-03 12:55:18 -0700310
311 started_ = true;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800312}
313
314void BlockingConnectionAdapter::Stop() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700315 {
316 std::lock_guard<std::mutex> lock(mutex_);
317 if (!started_) {
318 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
319 return;
320 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800321
Josh Gaoc251ec52018-04-03 12:55:18 -0700322 if (stopped_) {
323 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
324 << "): already stopped";
325 return;
326 }
327
328 stopped_ = true;
329 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800330
331 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
332
333 this->underlying_->Close();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800334 this->cv_.notify_one();
Josh Gaoc251ec52018-04-03 12:55:18 -0700335
336 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
337 std::thread read_thread;
338 std::thread write_thread;
339
340 {
341 std::lock_guard<std::mutex> lock(mutex_);
342 read_thread = std::move(read_thread_);
343 write_thread = std::move(write_thread_);
344 }
345
346 read_thread.join();
347 write_thread.join();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800348
349 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
350 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
351}
352
353bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
354 {
Josh Gaoc251ec52018-04-03 12:55:18 -0700355 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800356 write_queue_.emplace_back(std::move(packet));
357 }
358
359 cv_.notify_one();
360 return true;
361}
362
Josh Gaob800d882018-01-28 20:32:46 -0800363bool FdConnection::Read(apacket* packet) {
364 if (!ReadFdExactly(fd_.get(), &packet->msg, sizeof(amessage))) {
365 D("remote local: read terminated (message)");
366 return false;
367 }
368
Josh Gaof571fcb2018-02-05 18:49:10 -0800369 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gao5caaebd2018-02-02 14:38:04 -0800370 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
371 return false;
372 }
373
Josh Gaof571fcb2018-02-05 18:49:10 -0800374 packet->payload.resize(packet->msg.data_length);
375
376 if (!ReadFdExactly(fd_.get(), &packet->payload[0], packet->payload.size())) {
Josh Gaob800d882018-01-28 20:32:46 -0800377 D("remote local: terminated (data)");
378 return false;
379 }
380
381 return true;
382}
383
384bool FdConnection::Write(apacket* packet) {
Josh Gaof571fcb2018-02-05 18:49:10 -0800385 if (!WriteFdExactly(fd_.get(), &packet->msg, sizeof(packet->msg))) {
Josh Gaob800d882018-01-28 20:32:46 -0800386 D("remote local: write terminated");
387 return false;
388 }
389
Josh Gaof571fcb2018-02-05 18:49:10 -0800390 if (packet->msg.data_length) {
391 if (!WriteFdExactly(fd_.get(), &packet->payload[0], packet->msg.data_length)) {
392 D("remote local: write terminated");
393 return false;
394 }
395 }
396
Josh Gaob800d882018-01-28 20:32:46 -0800397 return true;
398}
399
400void FdConnection::Close() {
401 adb_shutdown(fd_.get());
402 fd_.reset();
403}
404
Josh Gao06d61d42016-10-06 13:31:44 -0700405void send_packet(apacket* p, atransport* t) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800406 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayde471942017-12-07 11:40:00 -0800407 // compute a checksum for connection/auth packets for compatibility reasons
408 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
409 p->msg.data_check = 0;
410 } else {
411 p->msg.data_check = calculate_apacket_checksum(p);
412 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800413
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700414 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "to remote", p);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800415
Yi Kongaed415c2018-07-13 18:15:16 -0700416 if (t == nullptr) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700417 LOG(FATAL) << "Transport is null";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800418 }
419
Josh Gao0bbf69c2018-02-16 13:24:58 -0800420 if (t->Write(p) != 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700421 D("%s: failed to enqueue packet, closing transport", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800422 t->Kick();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800423 }
424}
425
Yabin Cuif4b99282015-08-27 12:03:11 -0700426void kick_transport(atransport* t) {
Josh Gao1db71af2017-08-17 13:50:51 -0700427 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui1f4ec192016-04-05 13:50:44 -0700428 // As kick_transport() can be called from threads without guarantee that t is valid,
429 // check if the transport is in transport_list first.
Josh Gaob122b172017-08-16 16:57:01 -0700430 //
431 // TODO(jmgao): WTF? Is this actually true?
Yabin Cui1f4ec192016-04-05 13:50:44 -0700432 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Yabin Cui7f274902016-04-18 11:22:34 -0700433 t->Kick();
Yabin Cui1f4ec192016-04-05 13:50:44 -0700434 }
Josh Gao902dace2018-08-10 14:44:54 -0700435
436#if ADB_HOST
437 reconnect_handler.CheckForKicked();
438#endif
Yabin Cuif4b99282015-08-27 12:03:11 -0700439}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800440
441static int transport_registration_send = -1;
442static int transport_registration_recv = -1;
Josh Gao71f775a2018-05-14 11:14:33 -0700443static fdevent* transport_registration_fde;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800444
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800445#if ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800446
447/* this adds support required by the 'track-devices' service.
448 * this is used to send the content of "list_transport" to any
449 * number of client connections that want it through a single
450 * live TCP connection
451 */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800452struct device_tracker {
Josh Gao1290fbf2016-11-22 14:32:34 -0800453 asocket socket;
Josh Gaoe0361d12018-02-12 17:24:00 -0800454 bool update_needed = false;
455 bool long_output = false;
456 device_tracker* next = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800457};
458
459/* linked list of all device trackers */
Josh Gao1290fbf2016-11-22 14:32:34 -0800460static device_tracker* device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800461
Josh Gao1290fbf2016-11-22 14:32:34 -0800462static void device_tracker_remove(device_tracker* tracker) {
463 device_tracker** pnode = &device_tracker_list;
464 device_tracker* node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800465
Josh Gao1db71af2017-08-17 13:50:51 -0700466 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800467 while (node) {
468 if (node == tracker) {
469 *pnode = node->next;
470 break;
471 }
472 pnode = &node->next;
Josh Gao1290fbf2016-11-22 14:32:34 -0800473 node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800474 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800475}
476
Josh Gao1290fbf2016-11-22 14:32:34 -0800477static void device_tracker_close(asocket* socket) {
478 device_tracker* tracker = (device_tracker*)socket;
479 asocket* peer = socket->peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800480
Josh Gao1290fbf2016-11-22 14:32:34 -0800481 D("device tracker %p removed", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800482 if (peer) {
Yi Kongaed415c2018-07-13 18:15:16 -0700483 peer->peer = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800484 peer->close(peer);
485 }
486 device_tracker_remove(tracker);
Josh Gaoe0361d12018-02-12 17:24:00 -0800487 delete tracker;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800488}
489
Josh Gao1ce99572018-03-07 16:52:28 -0800490static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800491 /* you can't read from a device tracker, close immediately */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800492 device_tracker_close(socket);
493 return -1;
494}
495
Elliott Hughese67f1f82015-04-30 17:32:03 -0700496static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700497 asocket* peer = tracker->socket.peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800498
Josh Gao1ce99572018-03-07 16:52:28 -0800499 apacket::payload_type data;
Josh Gao27cb7dc2018-02-01 13:17:50 -0800500 data.resize(4 + string.size());
501 char buf[5];
502 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
503 memcpy(&data[0], buf, 4);
504 memcpy(&data[4], string.data(), string.size());
505 return peer->enqueue(peer, std::move(data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800506}
507
Elliott Hughese67f1f82015-04-30 17:32:03 -0700508static void device_tracker_ready(asocket* socket) {
509 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800510
Elliott Hughese67f1f82015-04-30 17:32:03 -0700511 // We want to send the device list when the tracker connects
512 // for the first time, even if no update occurred.
Josh Gaob0c18022017-08-14 18:57:54 -0700513 if (tracker->update_needed) {
514 tracker->update_needed = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800515
Josh Gaob0c18022017-08-14 18:57:54 -0700516 std::string transports = list_transports(tracker->long_output);
Elliott Hughese67f1f82015-04-30 17:32:03 -0700517 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800518 }
519}
520
Josh Gaob0c18022017-08-14 18:57:54 -0700521asocket* create_device_tracker(bool long_output) {
Josh Gaoe0361d12018-02-12 17:24:00 -0800522 device_tracker* tracker = new device_tracker();
Elliott Hughes4679a392018-10-19 13:59:44 -0700523 if (tracker == nullptr) LOG(FATAL) << "cannot allocate device tracker";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800524
Josh Gao1290fbf2016-11-22 14:32:34 -0800525 D("device tracker %p created", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800526
527 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao1290fbf2016-11-22 14:32:34 -0800528 tracker->socket.ready = device_tracker_ready;
529 tracker->socket.close = device_tracker_close;
Josh Gaob0c18022017-08-14 18:57:54 -0700530 tracker->update_needed = true;
531 tracker->long_output = long_output;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800532
Josh Gao1290fbf2016-11-22 14:32:34 -0800533 tracker->next = device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800534 device_tracker_list = tracker;
535
536 return &tracker->socket;
537}
538
Josh Gaofd713e52017-05-03 22:37:10 -0700539// Check if all of the USB transports are connected.
540bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gao1db71af2017-08-17 13:50:51 -0700541 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaofd713e52017-05-03 22:37:10 -0700542 for (const auto& t : transport_list) {
543 if (!fn(t)) {
544 return false;
545 }
546 }
547 for (const auto& t : pending_list) {
548 if (!fn(t)) {
549 return false;
550 }
551 }
552 return true;
553}
554
Elliott Hughese67f1f82015-04-30 17:32:03 -0700555// Call this function each time the transport list has changed.
556void update_transports() {
Josh Gaofd713e52017-05-03 22:37:10 -0700557 update_transport_status();
558
559 // Notify `adb track-devices` clients.
Elliott Hughese67f1f82015-04-30 17:32:03 -0700560 std::string transports = list_transports(false);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800561
Elliott Hughese67f1f82015-04-30 17:32:03 -0700562 device_tracker* tracker = device_tracker_list;
563 while (tracker != nullptr) {
564 device_tracker* next = tracker->next;
565 // This may destroy the tracker if the connection is closed.
566 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800567 tracker = next;
568 }
569}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700570
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800571#else
Elliott Hughese67f1f82015-04-30 17:32:03 -0700572
573void update_transports() {
574 // Nothing to do on the device side.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800575}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700576
Josh Gao1290fbf2016-11-22 14:32:34 -0800577#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800578
Josh Gao1290fbf2016-11-22 14:32:34 -0800579struct tmsg {
580 atransport* transport;
581 int action;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800582};
583
Josh Gao1290fbf2016-11-22 14:32:34 -0800584static int transport_read_action(int fd, struct tmsg* m) {
585 char* p = (char*)m;
586 int len = sizeof(*m);
587 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800588
Josh Gao1290fbf2016-11-22 14:32:34 -0800589 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800590 r = adb_read(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800591 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800592 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800593 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800594 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700595 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800596 return -1;
597 }
598 }
599 return 0;
600}
601
Josh Gao1290fbf2016-11-22 14:32:34 -0800602static int transport_write_action(int fd, struct tmsg* m) {
603 char* p = (char*)m;
604 int len = sizeof(*m);
605 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800606
Josh Gao1290fbf2016-11-22 14:32:34 -0800607 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800608 r = adb_write(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800609 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800610 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800611 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800612 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700613 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800614 return -1;
615 }
616 }
617 return 0;
618}
619
Josh Gao0bbf69c2018-02-16 13:24:58 -0800620static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800621 tmsg m;
Josh Gao1290fbf2016-11-22 14:32:34 -0800622 atransport* t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800623
Josh Gao1290fbf2016-11-22 14:32:34 -0800624 if (!(ev & FDE_READ)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800625 return;
626 }
627
Josh Gao1290fbf2016-11-22 14:32:34 -0800628 if (transport_read_action(_fd, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700629 PLOG(FATAL) << "cannot read transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800630 }
631
632 t = m.transport;
633
Dan Albert1792c232015-05-18 13:06:53 -0700634 if (m.action == 0) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700635 D("transport: %s deleting", t->serial.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800636
Josh Gao0cd3ae12016-09-21 12:37:10 -0700637 {
Josh Gao1db71af2017-08-17 13:50:51 -0700638 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700639 transport_list.remove(t);
640 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800641
Dan Albertc7915a32015-05-18 16:46:31 -0700642 delete t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800643
644 update_transports();
645 return;
646 }
647
Mike Lockwood0927bf92009-08-08 12:37:44 -0400648 /* don't create transport threads for inaccessible devices */
Yabin Cuib5e11412017-03-10 16:01:01 -0800649 if (t->GetConnectionState() != kCsNoPerm) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700650 // The connection gets a reference to the atransport. It will release it
651 // upon a read/write error.
652 t->ref_count++;
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700653 t->connection()->SetTransportName(t->serial_name());
654 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao0bbf69c2018-02-16 13:24:58 -0800655 if (!check_header(p.get(), t)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700656 D("%s: remote read: bad header", t->serial.c_str());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800657 return false;
658 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800659
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700660 VLOG(TRANSPORT) << dump_packet(t->serial.c_str(), "from remote", p.get());
Josh Gao0bbf69c2018-02-16 13:24:58 -0800661 apacket* packet = p.release();
Mike Lockwood0927bf92009-08-08 12:37:44 -0400662
Josh Gao0bbf69c2018-02-16 13:24:58 -0800663 // TODO: Does this need to run on the main thread?
664 fdevent_run_on_main_thread([packet, t]() { handle_packet(packet, t); });
665 return true;
666 });
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700667 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700668 LOG(INFO) << t->serial_name() << ": connection terminated: " << error;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800669 fdevent_run_on_main_thread([t]() {
670 handle_offline(t);
671 transport_unref(t);
672 });
673 });
Mike Lockwood0927bf92009-08-08 12:37:44 -0400674
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700675 t->connection()->Start();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800676#if ADB_HOST
677 send_connect(t);
678#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800679 }
680
Josh Gao0cd3ae12016-09-21 12:37:10 -0700681 {
Josh Gao1db71af2017-08-17 13:50:51 -0700682 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700683 auto it = std::find(pending_list.begin(), pending_list.end(), t);
684 if (it != pending_list.end()) {
685 pending_list.remove(t);
686 transport_list.push_front(t);
687 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700688 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800689
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800690 update_transports();
691}
692
Josh Gaodef91c02018-07-31 18:28:32 -0700693#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700694void init_reconnect_handler(void) {
695 reconnect_handler.Start();
696}
Josh Gaodef91c02018-07-31 18:28:32 -0700697#endif
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700698
Josh Gao1290fbf2016-11-22 14:32:34 -0800699void init_transport_registration(void) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800700 int s[2];
701
Josh Gao1290fbf2016-11-22 14:32:34 -0800702 if (adb_socketpair(s)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700703 PLOG(FATAL) << "cannot open transport registration socketpair";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800704 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700705 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800706
707 transport_registration_send = s[0];
708 transport_registration_recv = s[1];
709
Josh Gao71f775a2018-05-14 11:14:33 -0700710 transport_registration_fde =
Yi Kongaed415c2018-07-13 18:15:16 -0700711 fdevent_create(transport_registration_recv, transport_registration_func, nullptr);
Josh Gao71f775a2018-05-14 11:14:33 -0700712 fdevent_set(transport_registration_fde, FDE_READ);
Josh Gao01b7bc42017-05-09 13:43:35 -0700713}
714
715void kick_all_transports() {
Josh Gaodef91c02018-07-31 18:28:32 -0700716#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700717 reconnect_handler.Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700718#endif
Josh Gao01b7bc42017-05-09 13:43:35 -0700719 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gao1db71af2017-08-17 13:50:51 -0700720 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao01b7bc42017-05-09 13:43:35 -0700721 for (auto t : transport_list) {
722 t->Kick();
723 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800724}
725
726/* the fdevent select pump is single threaded */
Josh Gaoc51726c2018-10-11 16:33:05 -0700727void register_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800728 tmsg m;
729 m.transport = transport;
730 m.action = 1;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700731 D("transport: %s registered", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800732 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700733 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800734 }
735}
736
Josh Gao1290fbf2016-11-22 14:32:34 -0800737static void remove_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800738 tmsg m;
739 m.transport = transport;
740 m.action = 0;
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700741 D("transport: %s removed", transport->serial.c_str());
Josh Gao1290fbf2016-11-22 14:32:34 -0800742 if (transport_write_action(transport_registration_send, &m)) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700743 PLOG(FATAL) << "cannot write transport registration socket";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800744 }
745}
746
Yabin Cuif4b99282015-08-27 12:03:11 -0700747static void transport_unref(atransport* t) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700748 check_main_thread();
Yabin Cuif4b99282015-08-27 12:03:11 -0700749 CHECK(t != nullptr);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700750
Josh Gaoe48ecce2017-09-13 13:40:57 -0700751 std::lock_guard<std::recursive_mutex> lock(transport_lock);
752 CHECK_GT(t->ref_count, 0u);
753 t->ref_count--;
754 if (t->ref_count == 0) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700755 LOG(INFO) << "destroying transport " << t->serial_name();
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700756 t->connection()->Stop();
Josh Gaodef91c02018-07-31 18:28:32 -0700757#if ADB_HOST
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700758 if (t->IsTcpDevice() && !t->kicked()) {
Josh Gaodef91c02018-07-31 18:28:32 -0700759 D("transport: %s unref (attempting reconnection)", t->serial.c_str());
Josh Gao4414e4c2018-12-04 01:07:50 -0800760
761 // We need to clear the transport's keys, so that on the next connection, it tries
762 // again from the beginning.
763 t->ResetKeys();
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700764 reconnect_handler.TrackTransport(t);
765 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700766 D("transport: %s unref (kicking and closing)", t->serial.c_str());
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700767 remove_transport(t);
768 }
Josh Gaodef91c02018-07-31 18:28:32 -0700769#else
770 D("transport: %s unref (kicking and closing)", t->serial.c_str());
771 remove_transport(t);
772#endif
773
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100774 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700775 D("transport: %s unref (count=%zu)", t->serial.c_str(), t->ref_count);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -0400776 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800777}
778
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700779static int qual_match(const std::string& to_test, const char* prefix, const std::string& qual,
Josh Gao1290fbf2016-11-22 14:32:34 -0800780 bool sanitize_qual) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700781 if (to_test.empty()) /* Return true if both the qual and to_test are empty strings. */
782 return qual.empty();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700783
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700784 if (qual.empty()) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700785
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700786 const char* ptr = to_test.c_str();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700787 if (prefix) {
788 while (*prefix) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700789 if (*prefix++ != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700790 }
791 }
792
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700793 for (char ch : qual) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800794 if (sanitize_qual && !isalnum(ch)) ch = '_';
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700795 if (ch != *ptr++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700796 }
797
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700798 /* Everything matched so far. Return true if *ptr is a NUL. */
799 return !*ptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700800}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800801
Josh Gaob122b172017-08-16 16:57:01 -0700802atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
803 bool* is_ambiguous, std::string* error_out,
804 bool accept_any_state) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700805 atransport* result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800806
Josh Gaob122b172017-08-16 16:57:01 -0700807 if (transport_id != 0) {
808 *error_out =
809 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
810 } else if (serial) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700811 *error_out = android::base::StringPrintf("device '%s' not found", serial);
812 } else if (type == kTransportLocal) {
813 *error_out = "no emulators found";
814 } else if (type == kTransportAny) {
815 *error_out = "no devices/emulators found";
816 } else {
817 *error_out = "no devices found";
818 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800819
Josh Gao1db71af2017-08-17 13:50:51 -0700820 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes8d28e192015-10-07 14:55:10 -0700821 for (const auto& t : transport_list) {
Yabin Cuib5e11412017-03-10 16:01:01 -0800822 if (t->GetConnectionState() == kCsNoPerm) {
David Purselld2acbd12015-12-02 15:14:31 -0800823 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwood37d31112009-08-08 13:53:16 -0400824 continue;
825 }
Mike Lockwood0927bf92009-08-08 12:37:44 -0400826
Josh Gaob122b172017-08-16 16:57:01 -0700827 if (transport_id) {
828 if (t->id == transport_id) {
829 result = t;
830 break;
831 }
832 } else if (serial) {
David Pursell3f902aa2016-03-01 08:58:26 -0800833 if (t->MatchesTarget(serial)) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700834 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700835 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700836 if (is_ambiguous) *is_ambiguous = true;
837 result = nullptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700838 break;
839 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800840 result = t;
Scott Andersone109d262012-04-20 11:21:14 -0700841 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800842 } else {
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700843 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800844 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700845 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700846 if (is_ambiguous) *is_ambiguous = true;
847 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800848 break;
849 }
850 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700851 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800852 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700853 *error_out = "more than one emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700854 if (is_ambiguous) *is_ambiguous = true;
855 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800856 break;
857 }
858 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700859 } else if (type == kTransportAny) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800860 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700861 *error_out = "more than one device/emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700862 if (is_ambiguous) *is_ambiguous = true;
863 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800864 break;
865 }
866 result = t;
867 }
868 }
869 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700870 lock.unlock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800871
Josh Gao704494b2018-05-04 16:04:49 -0700872 if (result && !accept_any_state) {
873 // The caller requires an active transport.
874 // Make sure that we're actually connected.
875 ConnectionState state = result->GetConnectionState();
876 switch (state) {
877 case kCsConnecting:
878 *error_out = "device still connecting";
879 result = nullptr;
880 break;
Benoit Goby77e8e582013-01-15 12:36:47 -0800881
Josh Gao704494b2018-05-04 16:04:49 -0700882 case kCsAuthorizing:
883 *error_out = "device still authorizing";
884 result = nullptr;
885 break;
886
887 case kCsUnauthorized: {
888 *error_out = "device unauthorized.\n";
889 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
890 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
891 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
892 *error_out += "\n";
893 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
894 *error_out += "Otherwise check for a confirmation dialog on your device.";
895 result = nullptr;
896 break;
897 }
898
899 case kCsOffline:
900 *error_out = "device offline";
901 result = nullptr;
902 break;
903
904 default:
905 break;
906 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800907 }
908
909 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700910 *error_out = "success";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800911 }
912
913 return result;
914}
915
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700916bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
917 std::unique_lock<std::mutex> lock(mutex_);
Josh Gao982f7bd2019-02-12 13:59:03 -0800918 ScopedLockAssertion assume_locked(mutex_);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700919 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
920 return connection_established_ready_;
921 }) && connection_established_;
922}
923
924void ConnectionWaitable::SetConnectionEstablished(bool success) {
925 {
926 std::lock_guard<std::mutex> lock(mutex_);
927 if (connection_established_ready_) return;
928 connection_established_ready_ = true;
929 connection_established_ = success;
930 D("connection established with %d", success);
931 }
932 cv_.notify_one();
933}
934
935atransport::~atransport() {
936 // If the connection callback had not been run before, run it now.
937 SetConnectionEstablished(false);
938}
939
Yabin Cuib5e11412017-03-10 16:01:01 -0800940int atransport::Write(apacket* p) {
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700941 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cuib5e11412017-03-10 16:01:01 -0800942}
943
Yabin Cui7f274902016-04-18 11:22:34 -0700944void atransport::Kick() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700945 if (!kicked_.exchange(true)) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700946 D("kicking transport %p %s", this, this->serial.c_str());
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700947 this->connection()->Stop();
Yabin Cui7f274902016-04-18 11:22:34 -0700948 }
949}
950
Yabin Cuib5e11412017-03-10 16:01:01 -0800951ConnectionState atransport::GetConnectionState() const {
952 return connection_state_;
953}
954
955void atransport::SetConnectionState(ConnectionState state) {
956 check_main_thread();
957 connection_state_ = state;
958}
959
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700960void atransport::SetConnection(std::unique_ptr<Connection> connection) {
961 std::lock_guard<std::mutex> lock(mutex_);
962 connection_ = std::shared_ptr<Connection>(std::move(connection));
963}
964
Josh Gaoffbd3362018-02-28 14:44:23 -0800965std::string atransport::connection_state_name() const {
Yabin Cuib5e11412017-03-10 16:01:01 -0800966 ConnectionState state = GetConnectionState();
967 switch (state) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800968 case kCsOffline:
969 return "offline";
970 case kCsBootloader:
971 return "bootloader";
972 case kCsDevice:
973 return "device";
974 case kCsHost:
975 return "host";
976 case kCsRecovery:
977 return "recovery";
978 case kCsNoPerm:
979 return UsbNoPermissionsShortHelpText();
980 case kCsSideload:
981 return "sideload";
982 case kCsUnauthorized:
983 return "unauthorized";
Josh Gao704494b2018-05-04 16:04:49 -0700984 case kCsAuthorizing:
985 return "authorizing";
986 case kCsConnecting:
987 return "connecting";
Josh Gao1290fbf2016-11-22 14:32:34 -0800988 default:
989 return "unknown";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800990 }
991}
992
Tamas Berghammer3d2904c2015-07-13 19:12:28 +0100993void atransport::update_version(int version, size_t payload) {
994 protocol_version = std::min(version, A_VERSION);
995 max_payload = std::min(payload, MAX_PAYLOAD);
996}
997
998int atransport::get_protocol_version() const {
999 return protocol_version;
1000}
1001
1002size_t atransport::get_max_payload() const {
1003 return max_payload;
1004}
1005
Dan Albert1792c232015-05-18 13:06:53 -07001006const FeatureSet& supported_features() {
David Pursell4e2fd362015-09-22 10:43:08 -07001007 // Local static allocation to avoid global non-POD variables.
1008 static const FeatureSet* features = new FeatureSet{
Josh Gao7b1cb662019-02-20 13:01:40 -08001009 kFeatureShell2,
1010 kFeatureCmd,
1011 kFeatureStat2,
1012 kFeatureFixedPushMkdir,
1013 kFeatureApex,
1014 kFeatureAbb,
1015 kFeatureFixedPushSymlinkTimestamp,
Josh Gao919b70c2018-11-08 22:39:43 -08001016 // Increment ADB_SERVER_VERSION when adding a feature that adbd needs
1017 // to know about. Otherwise, the client can be stuck running an old
1018 // version of the server even after upgrading their copy of adb.
1019 // (http://b/24370690)
David Pursell4e2fd362015-09-22 10:43:08 -07001020 };
1021
1022 return *features;
1023}
1024
1025std::string FeatureSetToString(const FeatureSet& features) {
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001026 return android::base::Join(features, ',');
David Pursell4e2fd362015-09-22 10:43:08 -07001027}
1028
1029FeatureSet StringToFeatureSet(const std::string& features_string) {
David Purselld2b588e2015-09-25 13:04:21 -07001030 if (features_string.empty()) {
1031 return FeatureSet();
1032 }
1033
Elliott Hughes86ab9ff2018-09-05 12:13:11 -07001034 auto names = android::base::Split(features_string, ",");
David Pursell4e2fd362015-09-22 10:43:08 -07001035 return FeatureSet(names.begin(), names.end());
Dan Albert1792c232015-05-18 13:06:53 -07001036}
1037
David Pursell70ef7b42015-09-30 13:35:42 -07001038bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001039 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell70ef7b42015-09-30 13:35:42 -07001040}
1041
Dan Albert1792c232015-05-18 13:06:53 -07001042bool atransport::has_feature(const std::string& feature) const {
1043 return features_.count(feature) > 0;
1044}
1045
David Pursell4e2fd362015-09-22 10:43:08 -07001046void atransport::SetFeatures(const std::string& features_string) {
1047 features_ = StringToFeatureSet(features_string);
Dan Albert1792c232015-05-18 13:06:53 -07001048}
1049
Yabin Cuib3298242015-08-28 15:09:44 -07001050void atransport::AddDisconnect(adisconnect* disconnect) {
1051 disconnects_.push_back(disconnect);
1052}
1053
1054void atransport::RemoveDisconnect(adisconnect* disconnect) {
1055 disconnects_.remove(disconnect);
1056}
1057
1058void atransport::RunDisconnects() {
Elliott Hughes65fe2512015-10-07 15:59:35 -07001059 for (const auto& disconnect : disconnects_) {
Yabin Cuib3298242015-08-28 15:09:44 -07001060 disconnect->func(disconnect->opaque, this);
1061 }
1062 disconnects_.clear();
1063}
1064
David Pursell3f902aa2016-03-01 08:58:26 -08001065bool atransport::MatchesTarget(const std::string& target) const {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001066 if (!serial.empty()) {
David Pursell3f902aa2016-03-01 08:58:26 -08001067 if (target == serial) {
1068 return true;
1069 } else if (type == kTransportLocal) {
1070 // Local transports can match [tcp:|udp:]<hostname>[:port].
1071 const char* local_target_ptr = target.c_str();
1072
1073 // For fastboot compatibility, ignore protocol prefixes.
1074 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao1290fbf2016-11-22 14:32:34 -08001075 android::base::StartsWith(target, "udp:")) {
David Pursell3f902aa2016-03-01 08:58:26 -08001076 local_target_ptr += 4;
1077 }
1078
1079 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
1080 std::string serial_host, error;
1081 int serial_port = -1;
Josh Gao1290fbf2016-11-22 14:32:34 -08001082 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursell3f902aa2016-03-01 08:58:26 -08001083 // |target| may omit the port to default to ours.
1084 std::string target_host;
1085 int target_port = serial_port;
1086 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
1087 nullptr, &error) &&
Josh Gao1290fbf2016-11-22 14:32:34 -08001088 serial_host == target_host && serial_port == target_port) {
David Pursell3f902aa2016-03-01 08:58:26 -08001089 return true;
1090 }
1091 }
1092 }
1093 }
1094
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001095 return (target == devpath) || qual_match(target, "product:", product, false) ||
1096 qual_match(target, "model:", model, true) ||
1097 qual_match(target, "device:", device, false);
David Pursell3f902aa2016-03-01 08:58:26 -08001098}
1099
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001100void atransport::SetConnectionEstablished(bool success) {
1101 connection_waitable_->SetConnectionEstablished(success);
1102}
1103
Josh Gaofc2e56f2018-08-30 11:37:00 -07001104ReconnectResult atransport::Reconnect() {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001105 return reconnect_(this);
1106}
1107
Elliott Hughese67f1f82015-04-30 17:32:03 -07001108#if ADB_HOST
1109
Josh Gaob122b172017-08-16 16:57:01 -07001110// We use newline as our delimiter, make sure to never output it.
1111static std::string sanitize(std::string str, bool alphanumeric) {
1112 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
1113 : [](const char c) { return c == '\n'; };
1114 std::replace_if(str.begin(), str.end(), pred, '_');
1115 return str;
1116}
1117
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001118static void append_transport_info(std::string* result, const char* key, const std::string& value,
Josh Gaob122b172017-08-16 16:57:01 -07001119 bool alphanumeric) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001120 if (value.empty()) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001121 return;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001122 }
1123
Elliott Hughese67f1f82015-04-30 17:32:03 -07001124 *result += ' ';
1125 *result += key;
Josh Gaob122b172017-08-16 16:57:01 -07001126 *result += sanitize(value, alphanumeric);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001127}
1128
Josh Gao1290fbf2016-11-22 14:32:34 -08001129static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001130 std::string serial = t->serial;
1131 if (serial.empty()) {
Dan Albertd99d9022015-05-06 16:48:52 -07001132 serial = "(no serial number)";
Elliott Hughese67f1f82015-04-30 17:32:03 -07001133 }
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001134
1135 if (!long_listing) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001136 *result += serial;
1137 *result += '\t';
1138 *result += t->connection_state_name();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001139 } else {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001140 android::base::StringAppendF(result, "%-22s %s", serial.c_str(),
1141 t->connection_state_name().c_str());
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001142
Elliott Hughese67f1f82015-04-30 17:32:03 -07001143 append_transport_info(result, "", t->devpath, false);
1144 append_transport_info(result, "product:", t->product, false);
1145 append_transport_info(result, "model:", t->model, true);
1146 append_transport_info(result, "device:", t->device, false);
Josh Gaob122b172017-08-16 16:57:01 -07001147
1148 // Put id at the end, so that anyone parsing the output here can always find it by scanning
1149 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
1150 *result += " transport_id:";
1151 *result += std::to_string(t->id);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001152 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001153 *result += '\n';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -07001154}
1155
Elliott Hughese67f1f82015-04-30 17:32:03 -07001156std::string list_transports(bool long_listing) {
Josh Gao1db71af2017-08-17 13:50:51 -07001157 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov04398a92017-12-17 10:56:07 +00001158
1159 auto sorted_transport_list = transport_list;
1160 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
1161 if (x->type != y->type) {
1162 return x->type < y->type;
1163 }
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001164 return x->serial < y->serial;
Artem Iglikov04398a92017-12-17 10:56:07 +00001165 });
1166
1167 std::string result;
1168 for (const auto& t : sorted_transport_list) {
Elliott Hughese67f1f82015-04-30 17:32:03 -07001169 append_transport(t, &result, long_listing);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001170 }
Elliott Hughese67f1f82015-04-30 17:32:03 -07001171 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001172}
1173
Josh Gao22d2b3e2016-10-27 14:01:08 -07001174void close_usb_devices(std::function<bool(const atransport*)> predicate) {
Josh Gao1db71af2017-08-17 13:50:51 -07001175 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao22d2b3e2016-10-27 14:01:08 -07001176 for (auto& t : transport_list) {
1177 if (predicate(t)) {
1178 t->Kick();
1179 }
1180 }
1181}
1182
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001183/* hack for osx */
Dan Albertc7915a32015-05-18 16:46:31 -07001184void close_usb_devices() {
Josh Gao22d2b3e2016-10-27 14:01:08 -07001185 close_usb_devices([](const atransport*) { return true; });
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001186}
Josh Gao1290fbf2016-11-22 14:32:34 -08001187#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001188
Josh Gao362e6962018-08-08 16:20:14 -07001189bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
1190 atransport::ReconnectCallback reconnect, int* error) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001191 atransport* t = new atransport(std::move(reconnect), kCsOffline);
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +01001192
Josh Gao3b4de3c2018-08-02 13:58:24 -07001193 D("transport: %s init'ing for socket %d, on port %d", serial.c_str(), s.get(), port);
Josh Gao56300c92018-07-25 17:21:49 -07001194 if (init_socket_transport(t, std::move(s), port, local) < 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001195 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001196 if (error) *error = errno;
1197 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001198 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001199
Josh Gao1db71af2017-08-17 13:50:51 -07001200 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes65fe2512015-10-07 15:59:35 -07001201 for (const auto& transport : pending_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001202 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001203 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001204 << " is already in pending_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001205 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001206 if (error) *error = EALREADY;
1207 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001208 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001209 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001210
Elliott Hughes65fe2512015-10-07 15:59:35 -07001211 for (const auto& transport : transport_list) {
Josh Gao3b4de3c2018-08-02 13:58:24 -07001212 if (serial == transport->serial) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001213 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -08001214 << " is already in transport_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -07001215 delete t;
Josh Gao362e6962018-08-08 16:20:14 -07001216 if (error) *error = EALREADY;
1217 return false;
Benoit Goby1c45ee92013-03-29 18:22:36 -07001218 }
1219 }
1220
Josh Gao3b4de3c2018-08-02 13:58:24 -07001221 t->serial = std::move(serial);
Dan Albertc7915a32015-05-18 16:46:31 -07001222 pending_list.push_front(t);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001223
1224 lock.unlock();
Benoit Goby1c45ee92013-03-29 18:22:36 -07001225
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001226 auto waitable = t->connection_waitable();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001227 register_transport(t);
Luis Hector Chavez56fe7532018-04-17 14:25:04 -07001228
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001229 if (local == 1) {
1230 // Do not wait for emulator transports.
Josh Gao362e6962018-08-08 16:20:14 -07001231 return true;
Luis Hector Chavezc587f022018-05-01 17:12:16 -07001232 }
1233
Josh Gao362e6962018-08-08 16:20:14 -07001234 if (!waitable->WaitForConnection(std::chrono::seconds(10))) {
1235 if (error) *error = ETIMEDOUT;
1236 return false;
1237 }
1238
1239 if (t->GetConnectionState() == kCsUnauthorized) {
1240 if (error) *error = EPERM;
1241 return false;
1242 }
1243
1244 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001245}
1246
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001247#if ADB_HOST
Josh Gao1290fbf2016-11-22 14:32:34 -08001248atransport* find_transport(const char* serial) {
Dan Albertc7915a32015-05-18 16:46:31 -07001249 atransport* result = nullptr;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001250
Josh Gao1db71af2017-08-17 13:50:51 -07001251 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001252 for (auto& t : transport_list) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001253 if (strcmp(serial, t->serial.c_str()) == 0) {
Dan Albertc7915a32015-05-18 16:46:31 -07001254 result = t;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001255 break;
1256 }
Dan Albertc7915a32015-05-18 16:46:31 -07001257 }
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001258
Dan Albertc7915a32015-05-18 16:46:31 -07001259 return result;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001260}
1261
Yabin Cuif4b99282015-08-27 12:03:11 -07001262void kick_all_tcp_devices() {
Josh Gao1db71af2017-08-17 13:50:51 -07001263 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001264 for (auto& t : transport_list) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001265 if (t->IsTcpDevice()) {
Yabin Cuid6ab3c22015-08-31 11:50:24 -07001266 // Kicking breaks the read_transport thread of this transport out of any read, then
1267 // the read_transport thread will notify the main thread to make this transport
1268 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cuif4b99282015-08-27 12:03:11 -07001269 // Finally, this transport will be closed and freed in the main thread.
Yabin Cui7f274902016-04-18 11:22:34 -07001270 t->Kick();
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001271 }
Dan Albertc7915a32015-05-18 16:46:31 -07001272 }
Josh Gao902dace2018-08-10 14:44:54 -07001273#if ADB_HOST
1274 reconnect_handler.CheckForKicked();
1275#endif
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001276}
1277
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001278#endif
1279
Josh Gao1290fbf2016-11-22 14:32:34 -08001280void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1281 unsigned writeable) {
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -07001282 atransport* t = new atransport(writeable ? kCsOffline : kCsNoPerm);
Dan Albertc7915a32015-05-18 16:46:31 -07001283
Josh Gao1290fbf2016-11-22 14:32:34 -08001284 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cuib5e11412017-03-10 16:01:01 -08001285 init_usb_transport(t, usb);
Josh Gao1290fbf2016-11-22 14:32:34 -08001286 if (serial) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001287 t->serial = serial;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001288 }
Dan Albertc7915a32015-05-18 16:46:31 -07001289
1290 if (devpath) {
Luis Hector Chavez6150a372018-07-18 21:18:27 -07001291 t->devpath = devpath;
Scott Andersone109d262012-04-20 11:21:14 -07001292 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001293
Josh Gao0cd3ae12016-09-21 12:37:10 -07001294 {
Josh Gao1db71af2017-08-17 13:50:51 -07001295 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001296 pending_list.push_front(t);
1297 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001298
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001299 register_transport(t);
1300}
1301
Josh Gaoc51726c2018-10-11 16:33:05 -07001302#if ADB_HOST
Dan Albertdcd78a12015-05-18 16:43:57 -07001303// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao1290fbf2016-11-22 14:32:34 -08001304void unregister_usb_transport(usb_handle* usb) {
Josh Gao1db71af2017-08-17 13:50:51 -07001305 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaob800d882018-01-28 20:32:46 -08001306 transport_list.remove_if([usb](atransport* t) {
Josh Gaoce5ce872018-12-11 13:11:52 -08001307 return t->GetUsbHandle() == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gaob800d882018-01-28 20:32:46 -08001308 });
Mike Lockwood0927bf92009-08-08 12:37:44 -04001309}
Josh Gaoc51726c2018-10-11 16:33:05 -07001310#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001311
Josh Gao36dadca2017-05-16 15:02:45 -07001312bool check_header(apacket* p, atransport* t) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001313 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cuib5e11412017-03-10 16:01:01 -08001314 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1315 << ", magic = " << p->msg.magic;
Josh Gao36dadca2017-05-16 15:02:45 -07001316 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001317 }
1318
Josh Gao1290fbf2016-11-22 14:32:34 -08001319 if (p->msg.data_length > t->get_max_payload()) {
1320 VLOG(RWX) << "check_header(): " << p->msg.data_length
1321 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao36dadca2017-05-16 15:02:45 -07001322 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001323 }
1324
Josh Gao36dadca2017-05-16 15:02:45 -07001325 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001326}
1327
Josh Gao3bd28792016-10-05 19:02:29 -07001328#if ADB_HOST
Josh Gao2e671202016-08-18 22:00:12 -07001329std::shared_ptr<RSA> atransport::NextKey() {
Josh Gao4414e4c2018-12-04 01:07:50 -08001330 if (keys_.empty()) {
1331 LOG(INFO) << "fetching keys for transport " << this->serial_name();
1332 keys_ = adb_auth_get_private_keys();
1333
1334 // We should have gotten at least one key: the one that's automatically generated.
1335 CHECK(!keys_.empty());
1336 }
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001337
Josh Gao2e671202016-08-18 22:00:12 -07001338 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001339 keys_.pop_front();
1340 return result;
1341}
Josh Gao4414e4c2018-12-04 01:07:50 -08001342
1343void atransport::ResetKeys() {
1344 keys_.clear();
1345}
Josh Gao3bd28792016-10-05 19:02:29 -07001346#endif