blob: be7f8fe7f66e2dfc57490faacdd6b948dde722eb [file] [log] [blame]
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yabin Cui19bec5b2015-09-22 15:52:57 -070017#define TRACE_TAG TRANSPORT
Dan Albertb302d122015-02-24 15:51:19 -080018
Dan Albertdb6fe642015-03-19 15:21:08 -070019#include "sysdeps.h"
Josh Gaof2a988c2018-03-07 16:51:08 -080020#include "sysdeps/memory.h"
21
Dan Albertb302d122015-02-24 15:51:19 -080022#include "transport.h"
23
Dan Albert4895c522015-02-20 17:24:58 -080024#include <ctype.h>
Dan Albertb302d122015-02-24 15:51:19 -080025#include <errno.h>
Josh Gaob39e4152017-08-16 16:57:01 -070026#include <inttypes.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080027#include <stdio.h>
28#include <stdlib.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080029#include <string.h>
Dan Albertb302d122015-02-24 15:51:19 -080030#include <unistd.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080031
Spencer Low28bc2cb2015-11-07 18:51:54 -080032#include <algorithm>
Josh Gao715fe602018-02-16 13:24:58 -080033#include <deque>
Dan Albertecce5032015-05-18 16:46:31 -070034#include <list>
Josh Gaoe7daf572016-09-21 12:37:10 -070035#include <mutex>
Josh Gao0f3312a2017-04-12 17:00:49 -070036#include <thread>
Dan Albertecce5032015-05-18 16:46:31 -070037
Elliott Hughesf55ead92015-12-04 22:00:26 -080038#include <android-base/logging.h>
David Pursellc929c6f2016-03-01 08:58:26 -080039#include <android-base/parsenetaddress.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080040#include <android-base/stringprintf.h>
41#include <android-base/strings.h>
Josh Gaob39e4152017-08-16 16:57:01 -070042#include <android-base/thread_annotations.h>
Elliott Hughes88b4c852015-04-30 17:32:03 -070043
Josh Gao361148b2018-01-02 12:01:43 -080044#include <diagnose_usb.h>
45
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080046#include "adb.h"
Elliott Hughes801066a2016-06-29 17:42:01 -070047#include "adb_auth.h"
Josh Gao395b86a2018-01-28 20:32:46 -080048#include "adb_io.h"
Josh Gao9e09a972016-11-29 09:40:29 -080049#include "adb_trace.h"
Elliott Hughes88b4c852015-04-30 17:32:03 -070050#include "adb_utils.h"
Yabin Cui3cf1b362017-03-10 16:01:01 -080051#include "fdevent.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080052
53static void transport_unref(atransport *t);
54
Josh Gaob39e4152017-08-16 16:57:01 -070055// TODO: unordered_map<TransportId, atransport*>
Josh Gaoe3a87d02015-11-11 17:56:12 -080056static auto& transport_list = *new std::list<atransport*>();
57static auto& pending_list = *new std::list<atransport*>();
Benoit Goby3f9f9ce2013-03-29 18:22:36 -070058
Josh Gaoaaa82f72017-08-17 13:50:51 -070059static auto& transport_lock = *new std::recursive_mutex();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080060
Todd Kennedyaff9c672015-11-10 00:03:25 +000061const char* const kFeatureShell2 = "shell_v2";
62const char* const kFeatureCmd = "cmd";
Josh Gaoa2cf3752016-12-05 17:11:34 -080063const char* const kFeatureStat2 = "stat_v2";
Josh Gao210b63f2017-02-22 17:07:01 -080064const char* const kFeatureLibusb = "libusb";
Dan Albert27983bc2017-05-23 14:30:00 -070065const char* const kFeaturePushSync = "push_sync";
Todd Kennedyaff9c672015-11-10 00:03:25 +000066
Luis Hector Chavezda74b902018-04-17 14:25:04 -070067namespace {
68
69// A class that helps the Clang Thread Safety Analysis deal with
70// std::unique_lock. Given that std::unique_lock is movable, and the analysis
71// can not currently perform alias analysis, it is not annotated. In order to
72// assert that the mutex is held, a ScopedAssumeLocked can be created just after
73// the std::unique_lock.
74class SCOPED_CAPABILITY ScopedAssumeLocked {
75 public:
76 ScopedAssumeLocked(std::mutex& mutex) ACQUIRE(mutex) {}
77 ~ScopedAssumeLocked() RELEASE() {}
78};
79
80} // namespace
81
Josh Gaob39e4152017-08-16 16:57:01 -070082TransportId NextTransportId() {
83 static std::atomic<TransportId> next(1);
84 return next++;
85}
86
Josh Gao715fe602018-02-16 13:24:58 -080087BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
88 : underlying_(std::move(connection)) {}
89
90BlockingConnectionAdapter::~BlockingConnectionAdapter() {
91 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
92 Stop();
93}
94
95void BlockingConnectionAdapter::Start() {
Josh Gao13781e82018-04-03 12:55:18 -070096 std::lock_guard<std::mutex> lock(mutex_);
97 if (started_) {
98 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
99 << "): started multiple times";
100 }
101
Josh Gao715fe602018-02-16 13:24:58 -0800102 read_thread_ = std::thread([this]() {
103 LOG(INFO) << this->transport_name_ << ": read thread spawning";
104 while (true) {
Josh Gaof2a988c2018-03-07 16:51:08 -0800105 auto packet = std::make_unique<apacket>();
Josh Gao715fe602018-02-16 13:24:58 -0800106 if (!underlying_->Read(packet.get())) {
107 PLOG(INFO) << this->transport_name_ << ": read failed";
108 break;
109 }
110 read_callback_(this, std::move(packet));
111 }
112 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
113 });
114
115 write_thread_ = std::thread([this]() {
116 LOG(INFO) << this->transport_name_ << ": write thread spawning";
117 while (true) {
118 std::unique_lock<std::mutex> lock(mutex_);
Luis Hector Chavezda74b902018-04-17 14:25:04 -0700119 ScopedAssumeLocked assume_locked(mutex_);
Josh Gao13781e82018-04-03 12:55:18 -0700120 cv_.wait(lock, [this]() REQUIRES(mutex_) {
121 return this->stopped_ || !this->write_queue_.empty();
122 });
123
Josh Gao715fe602018-02-16 13:24:58 -0800124 if (this->stopped_) {
125 return;
126 }
127
128 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
129 this->write_queue_.pop_front();
130 lock.unlock();
131
132 if (!this->underlying_->Write(packet.get())) {
133 break;
134 }
135 }
136 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
137 });
Josh Gao13781e82018-04-03 12:55:18 -0700138
139 started_ = true;
Josh Gao715fe602018-02-16 13:24:58 -0800140}
141
142void BlockingConnectionAdapter::Stop() {
Josh Gao13781e82018-04-03 12:55:18 -0700143 {
144 std::lock_guard<std::mutex> lock(mutex_);
145 if (!started_) {
146 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
147 return;
148 }
Josh Gao715fe602018-02-16 13:24:58 -0800149
Josh Gao13781e82018-04-03 12:55:18 -0700150 if (stopped_) {
151 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
152 << "): already stopped";
153 return;
154 }
155
156 stopped_ = true;
157 }
Josh Gao715fe602018-02-16 13:24:58 -0800158
159 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
160
161 this->underlying_->Close();
Josh Gao715fe602018-02-16 13:24:58 -0800162 this->cv_.notify_one();
Josh Gao13781e82018-04-03 12:55:18 -0700163
164 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
165 std::thread read_thread;
166 std::thread write_thread;
167
168 {
169 std::lock_guard<std::mutex> lock(mutex_);
170 read_thread = std::move(read_thread_);
171 write_thread = std::move(write_thread_);
172 }
173
174 read_thread.join();
175 write_thread.join();
Josh Gao715fe602018-02-16 13:24:58 -0800176
177 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
178 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
179}
180
181bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
182 {
Josh Gao13781e82018-04-03 12:55:18 -0700183 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao715fe602018-02-16 13:24:58 -0800184 write_queue_.emplace_back(std::move(packet));
185 }
186
187 cv_.notify_one();
188 return true;
189}
190
Josh Gao395b86a2018-01-28 20:32:46 -0800191bool FdConnection::Read(apacket* packet) {
192 if (!ReadFdExactly(fd_.get(), &packet->msg, sizeof(amessage))) {
193 D("remote local: read terminated (message)");
194 return false;
195 }
196
Josh Gao839b9322018-02-05 18:49:10 -0800197 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gaob14756a2018-02-02 14:38:04 -0800198 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
199 return false;
200 }
201
Josh Gao839b9322018-02-05 18:49:10 -0800202 packet->payload.resize(packet->msg.data_length);
203
204 if (!ReadFdExactly(fd_.get(), &packet->payload[0], packet->payload.size())) {
Josh Gao395b86a2018-01-28 20:32:46 -0800205 D("remote local: terminated (data)");
206 return false;
207 }
208
209 return true;
210}
211
212bool FdConnection::Write(apacket* packet) {
Josh Gao839b9322018-02-05 18:49:10 -0800213 if (!WriteFdExactly(fd_.get(), &packet->msg, sizeof(packet->msg))) {
Josh Gao395b86a2018-01-28 20:32:46 -0800214 D("remote local: write terminated");
215 return false;
216 }
217
Josh Gao839b9322018-02-05 18:49:10 -0800218 if (packet->msg.data_length) {
219 if (!WriteFdExactly(fd_.get(), &packet->payload[0], packet->msg.data_length)) {
220 D("remote local: write terminated");
221 return false;
222 }
223 }
224
Josh Gao395b86a2018-01-28 20:32:46 -0800225 return true;
226}
227
228void FdConnection::Close() {
229 adb_shutdown(fd_.get());
230 fd_.reset();
231}
232
Yabin Cui19bec5b2015-09-22 15:52:57 -0700233static std::string dump_packet(const char* name, const char* func, apacket* p) {
Josh Gao0d6aa992016-11-22 14:32:34 -0800234 unsigned command = p->msg.command;
235 int len = p->msg.data_length;
236 char cmd[9];
237 char arg0[12], arg1[12];
238 int n;
David 'Digit' Turner58f59682011-01-06 14:11:07 +0100239
240 for (n = 0; n < 4; n++) {
Josh Gao0d6aa992016-11-22 14:32:34 -0800241 int b = (command >> (n * 8)) & 255;
242 if (b < 32 || b >= 127) break;
David 'Digit' Turner58f59682011-01-06 14:11:07 +0100243 cmd[n] = (char)b;
244 }
245 if (n == 4) {
246 cmd[4] = 0;
247 } else {
248 /* There is some non-ASCII name in the command, so dump
249 * the hexadecimal value instead */
250 snprintf(cmd, sizeof cmd, "%08x", command);
251 }
252
253 if (p->msg.arg0 < 256U)
254 snprintf(arg0, sizeof arg0, "%d", p->msg.arg0);
255 else
256 snprintf(arg0, sizeof arg0, "0x%x", p->msg.arg0);
257
258 if (p->msg.arg1 < 256U)
259 snprintf(arg1, sizeof arg1, "%d", p->msg.arg1);
260 else
261 snprintf(arg1, sizeof arg1, "0x%x", p->msg.arg1);
262
Josh Gao0d6aa992016-11-22 14:32:34 -0800263 std::string result = android::base::StringPrintf("%s: %s: [%s] arg0=%s arg1=%s (len=%d) ", name,
264 func, cmd, arg0, arg1, len);
Josh Gao839b9322018-02-05 18:49:10 -0800265 result += dump_hex(p->payload.data(), p->payload.size());
Yabin Cui19bec5b2015-09-22 15:52:57 -0700266 return result;
David 'Digit' Turner58f59682011-01-06 14:11:07 +0100267}
David 'Digit' Turner58f59682011-01-06 14:11:07 +0100268
Josh Gao67ac3792016-10-06 13:31:44 -0700269void send_packet(apacket* p, atransport* t) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800270 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayee7b44d2017-12-07 11:40:00 -0800271 // compute a checksum for connection/auth packets for compatibility reasons
272 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
273 p->msg.data_check = 0;
274 } else {
275 p->msg.data_check = calculate_apacket_checksum(p);
276 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800277
Josh Gao715fe602018-02-16 13:24:58 -0800278 VLOG(TRANSPORT) << dump_packet(t->serial, "to remote", p);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800279
280 if (t == NULL) {
Josh Gao67ac3792016-10-06 13:31:44 -0700281 fatal("Transport is null");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800282 }
283
Josh Gao715fe602018-02-16 13:24:58 -0800284 if (t->Write(p) != 0) {
285 D("%s: failed to enqueue packet, closing transport", t->serial);
286 t->Kick();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800287 }
288}
289
Yabin Cui4d64fd82015-08-27 12:03:11 -0700290void kick_transport(atransport* t) {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700291 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuid78ed222016-04-05 13:50:44 -0700292 // As kick_transport() can be called from threads without guarantee that t is valid,
293 // check if the transport is in transport_list first.
Josh Gaob39e4152017-08-16 16:57:01 -0700294 //
295 // TODO(jmgao): WTF? Is this actually true?
Yabin Cuid78ed222016-04-05 13:50:44 -0700296 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Yabin Cuif2a9f9b2016-04-18 11:22:34 -0700297 t->Kick();
Yabin Cuid78ed222016-04-05 13:50:44 -0700298 }
Yabin Cui4d64fd82015-08-27 12:03:11 -0700299}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800300
301static int transport_registration_send = -1;
302static int transport_registration_recv = -1;
303static fdevent transport_registration_fde;
304
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800305#if ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800306
307/* this adds support required by the 'track-devices' service.
308 * this is used to send the content of "list_transport" to any
309 * number of client connections that want it through a single
310 * live TCP connection
311 */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800312struct device_tracker {
Josh Gao0d6aa992016-11-22 14:32:34 -0800313 asocket socket;
Josh Gao5cb76ce2018-02-12 17:24:00 -0800314 bool update_needed = false;
315 bool long_output = false;
316 device_tracker* next = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800317};
318
319/* linked list of all device trackers */
Josh Gao0d6aa992016-11-22 14:32:34 -0800320static device_tracker* device_tracker_list;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800321
Josh Gao0d6aa992016-11-22 14:32:34 -0800322static void device_tracker_remove(device_tracker* tracker) {
323 device_tracker** pnode = &device_tracker_list;
324 device_tracker* node = *pnode;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800325
Josh Gaoaaa82f72017-08-17 13:50:51 -0700326 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800327 while (node) {
328 if (node == tracker) {
329 *pnode = node->next;
330 break;
331 }
332 pnode = &node->next;
Josh Gao0d6aa992016-11-22 14:32:34 -0800333 node = *pnode;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800334 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800335}
336
Josh Gao0d6aa992016-11-22 14:32:34 -0800337static void device_tracker_close(asocket* socket) {
338 device_tracker* tracker = (device_tracker*)socket;
339 asocket* peer = socket->peer;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800340
Josh Gao0d6aa992016-11-22 14:32:34 -0800341 D("device tracker %p removed", tracker);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800342 if (peer) {
343 peer->peer = NULL;
344 peer->close(peer);
345 }
346 device_tracker_remove(tracker);
Josh Gao5cb76ce2018-02-12 17:24:00 -0800347 delete tracker;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800348}
349
Josh Gaocd2a5292018-03-07 16:52:28 -0800350static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800351 /* you can't read from a device tracker, close immediately */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800352 device_tracker_close(socket);
353 return -1;
354}
355
Elliott Hughes88b4c852015-04-30 17:32:03 -0700356static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughes88b4c852015-04-30 17:32:03 -0700357 asocket* peer = tracker->socket.peer;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800358
Josh Gaocd2a5292018-03-07 16:52:28 -0800359 apacket::payload_type data;
Josh Gaoa7d9d712018-02-01 13:17:50 -0800360 data.resize(4 + string.size());
361 char buf[5];
362 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
363 memcpy(&data[0], buf, 4);
364 memcpy(&data[4], string.data(), string.size());
365 return peer->enqueue(peer, std::move(data));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800366}
367
Elliott Hughes88b4c852015-04-30 17:32:03 -0700368static void device_tracker_ready(asocket* socket) {
369 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800370
Elliott Hughes88b4c852015-04-30 17:32:03 -0700371 // We want to send the device list when the tracker connects
372 // for the first time, even if no update occurred.
Josh Gao32124632017-08-14 18:57:54 -0700373 if (tracker->update_needed) {
374 tracker->update_needed = false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800375
Josh Gao32124632017-08-14 18:57:54 -0700376 std::string transports = list_transports(tracker->long_output);
Elliott Hughes88b4c852015-04-30 17:32:03 -0700377 device_tracker_send(tracker, transports);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800378 }
379}
380
Josh Gao32124632017-08-14 18:57:54 -0700381asocket* create_device_tracker(bool long_output) {
Josh Gao5cb76ce2018-02-12 17:24:00 -0800382 device_tracker* tracker = new device_tracker();
Elliott Hughesd0269c92015-04-21 19:39:52 -0700383 if (tracker == nullptr) fatal("cannot allocate device tracker");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800384
Josh Gao0d6aa992016-11-22 14:32:34 -0800385 D("device tracker %p created", tracker);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800386
387 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao0d6aa992016-11-22 14:32:34 -0800388 tracker->socket.ready = device_tracker_ready;
389 tracker->socket.close = device_tracker_close;
Josh Gao32124632017-08-14 18:57:54 -0700390 tracker->update_needed = true;
391 tracker->long_output = long_output;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800392
Josh Gao0d6aa992016-11-22 14:32:34 -0800393 tracker->next = device_tracker_list;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800394 device_tracker_list = tracker;
395
396 return &tracker->socket;
397}
398
Josh Gao1e3bf732017-05-03 22:37:10 -0700399// Check if all of the USB transports are connected.
400bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700401 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao1e3bf732017-05-03 22:37:10 -0700402 for (const auto& t : transport_list) {
403 if (!fn(t)) {
404 return false;
405 }
406 }
407 for (const auto& t : pending_list) {
408 if (!fn(t)) {
409 return false;
410 }
411 }
412 return true;
413}
414
Elliott Hughes88b4c852015-04-30 17:32:03 -0700415// Call this function each time the transport list has changed.
416void update_transports() {
Josh Gao1e3bf732017-05-03 22:37:10 -0700417 update_transport_status();
418
419 // Notify `adb track-devices` clients.
Elliott Hughes88b4c852015-04-30 17:32:03 -0700420 std::string transports = list_transports(false);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800421
Elliott Hughes88b4c852015-04-30 17:32:03 -0700422 device_tracker* tracker = device_tracker_list;
423 while (tracker != nullptr) {
424 device_tracker* next = tracker->next;
425 // This may destroy the tracker if the connection is closed.
426 device_tracker_send(tracker, transports);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800427 tracker = next;
428 }
429}
Elliott Hughes88b4c852015-04-30 17:32:03 -0700430
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800431#else
Elliott Hughes88b4c852015-04-30 17:32:03 -0700432
433void update_transports() {
434 // Nothing to do on the device side.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800435}
Elliott Hughes88b4c852015-04-30 17:32:03 -0700436
Josh Gao0d6aa992016-11-22 14:32:34 -0800437#endif // ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800438
Josh Gao0d6aa992016-11-22 14:32:34 -0800439struct tmsg {
440 atransport* transport;
441 int action;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800442};
443
Josh Gao0d6aa992016-11-22 14:32:34 -0800444static int transport_read_action(int fd, struct tmsg* m) {
445 char* p = (char*)m;
446 int len = sizeof(*m);
447 int r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800448
Josh Gao0d6aa992016-11-22 14:32:34 -0800449 while (len > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800450 r = adb_read(fd, p, len);
Josh Gao0d6aa992016-11-22 14:32:34 -0800451 if (r > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800452 len -= r;
Josh Gao0d6aa992016-11-22 14:32:34 -0800453 p += r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800454 } else {
Yabin Cui815ad882015-09-02 17:44:28 -0700455 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800456 return -1;
457 }
458 }
459 return 0;
460}
461
Josh Gao0d6aa992016-11-22 14:32:34 -0800462static int transport_write_action(int fd, struct tmsg* m) {
463 char* p = (char*)m;
464 int len = sizeof(*m);
465 int r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800466
Josh Gao0d6aa992016-11-22 14:32:34 -0800467 while (len > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800468 r = adb_write(fd, p, len);
Josh Gao0d6aa992016-11-22 14:32:34 -0800469 if (r > 0) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800470 len -= r;
Josh Gao0d6aa992016-11-22 14:32:34 -0800471 p += r;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800472 } else {
Yabin Cui815ad882015-09-02 17:44:28 -0700473 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800474 return -1;
475 }
476 }
477 return 0;
478}
479
Josh Gao715fe602018-02-16 13:24:58 -0800480static void remove_transport(atransport*);
481
482static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800483 tmsg m;
Josh Gao0d6aa992016-11-22 14:32:34 -0800484 atransport* t;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800485
Josh Gao0d6aa992016-11-22 14:32:34 -0800486 if (!(ev & FDE_READ)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800487 return;
488 }
489
Josh Gao0d6aa992016-11-22 14:32:34 -0800490 if (transport_read_action(_fd, &m)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800491 fatal_errno("cannot read transport registration socket");
492 }
493
494 t = m.transport;
495
Dan Albertbe8e54b2015-05-18 13:06:53 -0700496 if (m.action == 0) {
Josh Gao715fe602018-02-16 13:24:58 -0800497 D("transport: %s deleting", t->serial);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800498
Josh Gaoe7daf572016-09-21 12:37:10 -0700499 {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700500 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaoe7daf572016-09-21 12:37:10 -0700501 transport_list.remove(t);
502 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800503
Josh Gao0d6aa992016-11-22 14:32:34 -0800504 if (t->product) free(t->product);
505 if (t->serial) free(t->serial);
506 if (t->model) free(t->model);
507 if (t->device) free(t->device);
508 if (t->devpath) free(t->devpath);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800509
Dan Albertecce5032015-05-18 16:46:31 -0700510 delete t;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800511
512 update_transports();
513 return;
514 }
515
Mike Lockwoode45583f2009-08-08 12:37:44 -0400516 /* don't create transport threads for inaccessible devices */
Yabin Cui3cf1b362017-03-10 16:01:01 -0800517 if (t->GetConnectionState() != kCsNoPerm) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800518 /* initial references are the two threads */
Josh Gao715fe602018-02-16 13:24:58 -0800519 t->ref_count = 1;
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700520 t->connection()->SetTransportName(t->serial_name());
521 t->connection()->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
Josh Gao715fe602018-02-16 13:24:58 -0800522 if (!check_header(p.get(), t)) {
523 D("%s: remote read: bad header", t->serial);
524 return false;
525 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800526
Josh Gao715fe602018-02-16 13:24:58 -0800527 VLOG(TRANSPORT) << dump_packet(t->serial, "from remote", p.get());
528 apacket* packet = p.release();
Mike Lockwoode45583f2009-08-08 12:37:44 -0400529
Josh Gao715fe602018-02-16 13:24:58 -0800530 // TODO: Does this need to run on the main thread?
531 fdevent_run_on_main_thread([packet, t]() { handle_packet(packet, t); });
532 return true;
533 });
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700534 t->connection()->SetErrorCallback([t](Connection*, const std::string& error) {
Josh Gao715fe602018-02-16 13:24:58 -0800535 D("%s: connection terminated: %s", t->serial, error.c_str());
536 fdevent_run_on_main_thread([t]() {
537 handle_offline(t);
538 transport_unref(t);
539 });
540 });
Mike Lockwoode45583f2009-08-08 12:37:44 -0400541
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700542 t->connection()->Start();
Josh Gao715fe602018-02-16 13:24:58 -0800543#if ADB_HOST
544 send_connect(t);
545#endif
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800546 }
547
Josh Gaoe7daf572016-09-21 12:37:10 -0700548 {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700549 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaoe7daf572016-09-21 12:37:10 -0700550 pending_list.remove(t);
551 transport_list.push_front(t);
552 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800553
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800554 update_transports();
555}
556
Josh Gao0d6aa992016-11-22 14:32:34 -0800557void init_transport_registration(void) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800558 int s[2];
559
Josh Gao0d6aa992016-11-22 14:32:34 -0800560 if (adb_socketpair(s)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800561 fatal_errno("cannot open transport registration socketpair");
562 }
Yabin Cui815ad882015-09-02 17:44:28 -0700563 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800564
565 transport_registration_send = s[0];
566 transport_registration_recv = s[1];
567
Josh Gao0d6aa992016-11-22 14:32:34 -0800568 fdevent_install(&transport_registration_fde, transport_registration_recv,
569 transport_registration_func, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800570
571 fdevent_set(&transport_registration_fde, FDE_READ);
Josh Gao165460f2017-05-09 13:43:35 -0700572}
573
574void kick_all_transports() {
575 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gaoaaa82f72017-08-17 13:50:51 -0700576 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao165460f2017-05-09 13:43:35 -0700577 for (auto t : transport_list) {
578 t->Kick();
579 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800580}
581
582/* the fdevent select pump is single threaded */
Josh Gao0d6aa992016-11-22 14:32:34 -0800583static void register_transport(atransport* transport) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800584 tmsg m;
585 m.transport = transport;
586 m.action = 1;
Yabin Cui815ad882015-09-02 17:44:28 -0700587 D("transport: %s registered", transport->serial);
Josh Gao0d6aa992016-11-22 14:32:34 -0800588 if (transport_write_action(transport_registration_send, &m)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800589 fatal_errno("cannot write transport registration socket\n");
590 }
591}
592
Josh Gao0d6aa992016-11-22 14:32:34 -0800593static void remove_transport(atransport* transport) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800594 tmsg m;
595 m.transport = transport;
596 m.action = 0;
Yabin Cui815ad882015-09-02 17:44:28 -0700597 D("transport: %s removed", transport->serial);
Josh Gao0d6aa992016-11-22 14:32:34 -0800598 if (transport_write_action(transport_registration_send, &m)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800599 fatal_errno("cannot write transport registration socket\n");
600 }
601}
602
Yabin Cui4d64fd82015-08-27 12:03:11 -0700603static void transport_unref(atransport* t) {
604 CHECK(t != nullptr);
Josh Gaoe7daf572016-09-21 12:37:10 -0700605
Josh Gao4d299742017-09-13 13:40:57 -0700606 std::lock_guard<std::recursive_mutex> lock(transport_lock);
607 CHECK_GT(t->ref_count, 0u);
608 t->ref_count--;
609 if (t->ref_count == 0) {
Yabin Cui815ad882015-09-02 17:44:28 -0700610 D("transport: %s unref (kicking and closing)", t->serial);
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700611 t->connection()->Stop();
Mike Lockwood01c2c302010-05-24 10:44:35 -0400612 remove_transport(t);
David 'Digit' Turner58f59682011-01-06 14:11:07 +0100613 } else {
Josh Gao4d299742017-09-13 13:40:57 -0700614 D("transport: %s unref (count=%zu)", t->serial, t->ref_count);
Mike Lockwood01c2c302010-05-24 10:44:35 -0400615 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800616}
617
Josh Gao0d6aa992016-11-22 14:32:34 -0800618static int qual_match(const char* to_test, const char* prefix, const char* qual,
619 bool sanitize_qual) {
620 if (!to_test || !*to_test) /* Return true if both the qual and to_test are null strings. */
Scott Anderson27042382012-05-30 18:11:27 -0700621 return !qual || !*qual;
622
Josh Gao0d6aa992016-11-22 14:32:34 -0800623 if (!qual) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700624
625 if (prefix) {
626 while (*prefix) {
Josh Gao0d6aa992016-11-22 14:32:34 -0800627 if (*prefix++ != *to_test++) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700628 }
629 }
630
631 while (*qual) {
632 char ch = *qual++;
Josh Gao0d6aa992016-11-22 14:32:34 -0800633 if (sanitize_qual && !isalnum(ch)) ch = '_';
634 if (ch != *to_test++) return 0;
Scott Anderson27042382012-05-30 18:11:27 -0700635 }
636
637 /* Everything matched so far. Return true if *to_test is a NUL. */
638 return !*to_test;
639}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800640
Josh Gaob39e4152017-08-16 16:57:01 -0700641atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
642 bool* is_ambiguous, std::string* error_out,
643 bool accept_any_state) {
Elliott Hughes67943d12015-10-07 14:55:10 -0700644 atransport* result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800645
Josh Gaob39e4152017-08-16 16:57:01 -0700646 if (transport_id != 0) {
647 *error_out =
648 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
649 } else if (serial) {
Elliott Hughes67943d12015-10-07 14:55:10 -0700650 *error_out = android::base::StringPrintf("device '%s' not found", serial);
651 } else if (type == kTransportLocal) {
652 *error_out = "no emulators found";
653 } else if (type == kTransportAny) {
654 *error_out = "no devices/emulators found";
655 } else {
656 *error_out = "no devices found";
657 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800658
Josh Gaoaaa82f72017-08-17 13:50:51 -0700659 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes67943d12015-10-07 14:55:10 -0700660 for (const auto& t : transport_list) {
Yabin Cui3cf1b362017-03-10 16:01:01 -0800661 if (t->GetConnectionState() == kCsNoPerm) {
David Pursell6e5c7eb2015-12-02 15:14:31 -0800662 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwoodadc16b32009-08-08 13:53:16 -0400663 continue;
664 }
Mike Lockwoode45583f2009-08-08 12:37:44 -0400665
Josh Gaob39e4152017-08-16 16:57:01 -0700666 if (transport_id) {
667 if (t->id == transport_id) {
668 result = t;
669 break;
670 }
671 } else if (serial) {
David Pursellc929c6f2016-03-01 08:58:26 -0800672 if (t->MatchesTarget(serial)) {
Scott Anderson27042382012-05-30 18:11:27 -0700673 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700674 *error_out = "more than one device";
Elliott Hughes67943d12015-10-07 14:55:10 -0700675 if (is_ambiguous) *is_ambiguous = true;
676 result = nullptr;
Scott Anderson27042382012-05-30 18:11:27 -0700677 break;
678 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800679 result = t;
Scott Anderson6dfaf4b2012-04-20 11:21:14 -0700680 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800681 } else {
Elliott Hughes3aec2ba2015-05-05 13:10:43 -0700682 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800683 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700684 *error_out = "more than one device";
Elliott Hughes67943d12015-10-07 14:55:10 -0700685 if (is_ambiguous) *is_ambiguous = true;
686 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800687 break;
688 }
689 result = t;
Elliott Hughes3aec2ba2015-05-05 13:10:43 -0700690 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800691 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700692 *error_out = "more than one emulator";
Elliott Hughes67943d12015-10-07 14:55:10 -0700693 if (is_ambiguous) *is_ambiguous = true;
694 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800695 break;
696 }
697 result = t;
Elliott Hughes3aec2ba2015-05-05 13:10:43 -0700698 } else if (type == kTransportAny) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800699 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700700 *error_out = "more than one device/emulator";
Elliott Hughes67943d12015-10-07 14:55:10 -0700701 if (is_ambiguous) *is_ambiguous = true;
702 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800703 break;
704 }
705 result = t;
706 }
707 }
708 }
Josh Gaoe7daf572016-09-21 12:37:10 -0700709 lock.unlock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800710
Josh Gao7a7c5cb2018-05-04 16:04:49 -0700711 if (result && !accept_any_state) {
712 // The caller requires an active transport.
713 // Make sure that we're actually connected.
714 ConnectionState state = result->GetConnectionState();
715 switch (state) {
716 case kCsConnecting:
717 *error_out = "device still connecting";
718 result = nullptr;
719 break;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -0700720
Josh Gao7a7c5cb2018-05-04 16:04:49 -0700721 case kCsAuthorizing:
722 *error_out = "device still authorizing";
723 result = nullptr;
724 break;
725
726 case kCsUnauthorized: {
727 *error_out = "device unauthorized.\n";
728 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
729 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
730 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
731 *error_out += "\n";
732 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
733 *error_out += "Otherwise check for a confirmation dialog on your device.";
734 result = nullptr;
735 break;
736 }
737
738 case kCsOffline:
739 *error_out = "device offline";
740 result = nullptr;
741 break;
742
743 default:
744 break;
745 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800746 }
747
748 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700749 *error_out = "success";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800750 }
751
752 return result;
753}
754
Luis Hector Chavezda74b902018-04-17 14:25:04 -0700755bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
756 std::unique_lock<std::mutex> lock(mutex_);
757 ScopedAssumeLocked assume_locked(mutex_);
758 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
759 return connection_established_ready_;
760 }) && connection_established_;
761}
762
763void ConnectionWaitable::SetConnectionEstablished(bool success) {
764 {
765 std::lock_guard<std::mutex> lock(mutex_);
766 if (connection_established_ready_) return;
767 connection_established_ready_ = true;
768 connection_established_ = success;
769 D("connection established with %d", success);
770 }
771 cv_.notify_one();
772}
773
774atransport::~atransport() {
775 // If the connection callback had not been run before, run it now.
776 SetConnectionEstablished(false);
777}
778
Yabin Cui3cf1b362017-03-10 16:01:01 -0800779int atransport::Write(apacket* p) {
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700780 return this->connection()->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cui3cf1b362017-03-10 16:01:01 -0800781}
782
Yabin Cuif2a9f9b2016-04-18 11:22:34 -0700783void atransport::Kick() {
784 if (!kicked_) {
Josh Gao395b86a2018-01-28 20:32:46 -0800785 D("kicking transport %s", this->serial);
Yabin Cuif2a9f9b2016-04-18 11:22:34 -0700786 kicked_ = true;
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700787 this->connection()->Stop();
Yabin Cuif2a9f9b2016-04-18 11:22:34 -0700788 }
789}
790
Yabin Cui3cf1b362017-03-10 16:01:01 -0800791ConnectionState atransport::GetConnectionState() const {
792 return connection_state_;
793}
794
795void atransport::SetConnectionState(ConnectionState state) {
796 check_main_thread();
797 connection_state_ = state;
798}
799
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -0700800void atransport::SetConnection(std::unique_ptr<Connection> connection) {
801 std::lock_guard<std::mutex> lock(mutex_);
802 connection_ = std::shared_ptr<Connection>(std::move(connection));
803}
804
Josh Gao3cd03be2018-02-28 14:44:23 -0800805std::string atransport::connection_state_name() const {
Yabin Cui3cf1b362017-03-10 16:01:01 -0800806 ConnectionState state = GetConnectionState();
807 switch (state) {
Josh Gao0d6aa992016-11-22 14:32:34 -0800808 case kCsOffline:
809 return "offline";
810 case kCsBootloader:
811 return "bootloader";
812 case kCsDevice:
813 return "device";
814 case kCsHost:
815 return "host";
816 case kCsRecovery:
817 return "recovery";
818 case kCsNoPerm:
819 return UsbNoPermissionsShortHelpText();
820 case kCsSideload:
821 return "sideload";
822 case kCsUnauthorized:
823 return "unauthorized";
Josh Gao7a7c5cb2018-05-04 16:04:49 -0700824 case kCsAuthorizing:
825 return "authorizing";
826 case kCsConnecting:
827 return "connecting";
Josh Gao0d6aa992016-11-22 14:32:34 -0800828 default:
829 return "unknown";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800830 }
831}
832
Tamas Berghammera1c60c02015-07-13 19:12:28 +0100833void atransport::update_version(int version, size_t payload) {
834 protocol_version = std::min(version, A_VERSION);
835 max_payload = std::min(payload, MAX_PAYLOAD);
836}
837
838int atransport::get_protocol_version() const {
839 return protocol_version;
840}
841
842size_t atransport::get_max_payload() const {
843 return max_payload;
844}
845
David Pursella07dbad2015-09-22 10:43:08 -0700846namespace {
David Pursell8da19a42015-08-31 10:42:13 -0700847
David Pursella07dbad2015-09-22 10:43:08 -0700848constexpr char kFeatureStringDelimiter = ',';
849
850} // namespace
Dan Albertbe8e54b2015-05-18 13:06:53 -0700851
852const FeatureSet& supported_features() {
David Pursella07dbad2015-09-22 10:43:08 -0700853 // Local static allocation to avoid global non-POD variables.
854 static const FeatureSet* features = new FeatureSet{
Josh Gao0d6aa992016-11-22 14:32:34 -0800855 kFeatureShell2, kFeatureCmd, kFeatureStat2,
David Pursell6d5fad32015-09-25 08:37:13 -0700856 // Increment ADB_SERVER_VERSION whenever the feature list changes to
857 // make sure that the adb client and server features stay in sync
858 // (http://b/24370690).
David Pursella07dbad2015-09-22 10:43:08 -0700859 };
860
861 return *features;
862}
863
864std::string FeatureSetToString(const FeatureSet& features) {
865 return android::base::Join(features, kFeatureStringDelimiter);
866}
867
868FeatureSet StringToFeatureSet(const std::string& features_string) {
David Pursell3d9072b2015-09-25 13:04:21 -0700869 if (features_string.empty()) {
870 return FeatureSet();
871 }
872
Josh Gao0d6aa992016-11-22 14:32:34 -0800873 auto names = android::base::Split(features_string, {kFeatureStringDelimiter});
David Pursella07dbad2015-09-22 10:43:08 -0700874 return FeatureSet(names.begin(), names.end());
Dan Albertbe8e54b2015-05-18 13:06:53 -0700875}
876
David Pursell22fc5e92015-09-30 13:35:42 -0700877bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao0d6aa992016-11-22 14:32:34 -0800878 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell22fc5e92015-09-30 13:35:42 -0700879}
880
Dan Albertbe8e54b2015-05-18 13:06:53 -0700881bool atransport::has_feature(const std::string& feature) const {
882 return features_.count(feature) > 0;
883}
884
David Pursella07dbad2015-09-22 10:43:08 -0700885void atransport::SetFeatures(const std::string& features_string) {
886 features_ = StringToFeatureSet(features_string);
Dan Albertbe8e54b2015-05-18 13:06:53 -0700887}
888
Yabin Cui2d4c1982015-08-28 15:09:44 -0700889void atransport::AddDisconnect(adisconnect* disconnect) {
890 disconnects_.push_back(disconnect);
891}
892
893void atransport::RemoveDisconnect(adisconnect* disconnect) {
894 disconnects_.remove(disconnect);
895}
896
897void atransport::RunDisconnects() {
Elliott Hughes85952832015-10-07 15:59:35 -0700898 for (const auto& disconnect : disconnects_) {
Yabin Cui2d4c1982015-08-28 15:09:44 -0700899 disconnect->func(disconnect->opaque, this);
900 }
901 disconnects_.clear();
902}
903
David Pursellc929c6f2016-03-01 08:58:26 -0800904bool atransport::MatchesTarget(const std::string& target) const {
905 if (serial) {
906 if (target == serial) {
907 return true;
908 } else if (type == kTransportLocal) {
909 // Local transports can match [tcp:|udp:]<hostname>[:port].
910 const char* local_target_ptr = target.c_str();
911
912 // For fastboot compatibility, ignore protocol prefixes.
913 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao0d6aa992016-11-22 14:32:34 -0800914 android::base::StartsWith(target, "udp:")) {
David Pursellc929c6f2016-03-01 08:58:26 -0800915 local_target_ptr += 4;
916 }
917
918 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
919 std::string serial_host, error;
920 int serial_port = -1;
Josh Gao0d6aa992016-11-22 14:32:34 -0800921 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursellc929c6f2016-03-01 08:58:26 -0800922 // |target| may omit the port to default to ours.
923 std::string target_host;
924 int target_port = serial_port;
925 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
926 nullptr, &error) &&
Josh Gao0d6aa992016-11-22 14:32:34 -0800927 serial_host == target_host && serial_port == target_port) {
David Pursellc929c6f2016-03-01 08:58:26 -0800928 return true;
929 }
930 }
931 }
932 }
933
934 return (devpath && target == devpath) ||
935 qual_match(target.c_str(), "product:", product, false) ||
936 qual_match(target.c_str(), "model:", model, true) ||
937 qual_match(target.c_str(), "device:", device, false);
938}
939
Luis Hector Chavezda74b902018-04-17 14:25:04 -0700940void atransport::SetConnectionEstablished(bool success) {
941 connection_waitable_->SetConnectionEstablished(success);
942}
943
Elliott Hughes88b4c852015-04-30 17:32:03 -0700944#if ADB_HOST
945
Josh Gaob39e4152017-08-16 16:57:01 -0700946// We use newline as our delimiter, make sure to never output it.
947static std::string sanitize(std::string str, bool alphanumeric) {
948 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
949 : [](const char c) { return c == '\n'; };
950 std::replace_if(str.begin(), str.end(), pred, '_');
951 return str;
952}
953
Josh Gao0d6aa992016-11-22 14:32:34 -0800954static void append_transport_info(std::string* result, const char* key, const char* value,
Josh Gaob39e4152017-08-16 16:57:01 -0700955 bool alphanumeric) {
Elliott Hughes88b4c852015-04-30 17:32:03 -0700956 if (value == nullptr || *value == '\0') {
Scott Anderson27042382012-05-30 18:11:27 -0700957 return;
Scott Anderson27042382012-05-30 18:11:27 -0700958 }
959
Elliott Hughes88b4c852015-04-30 17:32:03 -0700960 *result += ' ';
961 *result += key;
Josh Gaob39e4152017-08-16 16:57:01 -0700962 *result += sanitize(value, alphanumeric);
Scott Anderson27042382012-05-30 18:11:27 -0700963}
964
Josh Gao0d6aa992016-11-22 14:32:34 -0800965static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Scott Anderson27042382012-05-30 18:11:27 -0700966 const char* serial = t->serial;
Elliott Hughes88b4c852015-04-30 17:32:03 -0700967 if (!serial || !serial[0]) {
Dan Alberta8c34142015-05-06 16:48:52 -0700968 serial = "(no serial number)";
Elliott Hughes88b4c852015-04-30 17:32:03 -0700969 }
Scott Anderson27042382012-05-30 18:11:27 -0700970
971 if (!long_listing) {
Elliott Hughes88b4c852015-04-30 17:32:03 -0700972 *result += serial;
973 *result += '\t';
974 *result += t->connection_state_name();
Scott Anderson27042382012-05-30 18:11:27 -0700975 } else {
Josh Gao0d6aa992016-11-22 14:32:34 -0800976 android::base::StringAppendF(result, "%-22s %s", serial, t->connection_state_name().c_str());
Scott Anderson27042382012-05-30 18:11:27 -0700977
Elliott Hughes88b4c852015-04-30 17:32:03 -0700978 append_transport_info(result, "", t->devpath, false);
979 append_transport_info(result, "product:", t->product, false);
980 append_transport_info(result, "model:", t->model, true);
981 append_transport_info(result, "device:", t->device, false);
Josh Gaob39e4152017-08-16 16:57:01 -0700982
983 // Put id at the end, so that anyone parsing the output here can always find it by scanning
984 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
985 *result += " transport_id:";
986 *result += std::to_string(t->id);
Scott Anderson27042382012-05-30 18:11:27 -0700987 }
Elliott Hughes88b4c852015-04-30 17:32:03 -0700988 *result += '\n';
Scott Anderson27042382012-05-30 18:11:27 -0700989}
990
Elliott Hughes88b4c852015-04-30 17:32:03 -0700991std::string list_transports(bool long_listing) {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700992 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov4dd35012017-12-17 10:56:07 +0000993
994 auto sorted_transport_list = transport_list;
995 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
996 if (x->type != y->type) {
997 return x->type < y->type;
998 }
999 return strcmp(x->serial, y->serial) < 0;
1000 });
1001
1002 std::string result;
1003 for (const auto& t : sorted_transport_list) {
Elliott Hughes88b4c852015-04-30 17:32:03 -07001004 append_transport(t, &result, long_listing);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001005 }
Elliott Hughes88b4c852015-04-30 17:32:03 -07001006 return result;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001007}
1008
Josh Gao4e562502016-10-27 14:01:08 -07001009void close_usb_devices(std::function<bool(const atransport*)> predicate) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001010 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao4e562502016-10-27 14:01:08 -07001011 for (auto& t : transport_list) {
1012 if (predicate(t)) {
1013 t->Kick();
1014 }
1015 }
1016}
1017
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001018/* hack for osx */
Dan Albertecce5032015-05-18 16:46:31 -07001019void close_usb_devices() {
Josh Gao4e562502016-10-27 14:01:08 -07001020 close_usb_devices([](const atransport*) { return true; });
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001021}
Josh Gao0d6aa992016-11-22 14:32:34 -08001022#endif // ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001023
Josh Gao0d6aa992016-11-22 14:32:34 -08001024int register_socket_transport(int s, const char* serial, int port, int local) {
Dan Albertecce5032015-05-18 16:46:31 -07001025 atransport* t = new atransport();
David 'Digit' Turner58f59682011-01-06 14:11:07 +01001026
1027 if (!serial) {
Dan Albertecce5032015-05-18 16:46:31 -07001028 char buf[32];
1029 snprintf(buf, sizeof(buf), "T-%p", t);
1030 serial = buf;
David 'Digit' Turner58f59682011-01-06 14:11:07 +01001031 }
Dan Albertecce5032015-05-18 16:46:31 -07001032
Yabin Cui815ad882015-09-02 17:44:28 -07001033 D("transport: %s init'ing for socket %d, on port %d", serial, s, port);
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001034 if (init_socket_transport(t, s, port, local) < 0) {
Dan Albertecce5032015-05-18 16:46:31 -07001035 delete t;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001036 return -1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001037 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001038
Josh Gaoaaa82f72017-08-17 13:50:51 -07001039 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes85952832015-10-07 15:59:35 -07001040 for (const auto& transport : pending_list) {
Dan Albertecce5032015-05-18 16:46:31 -07001041 if (transport->serial && strcmp(serial, transport->serial) == 0) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001042 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao0d6aa992016-11-22 14:32:34 -08001043 << " is already in pending_list and fails to register";
Dan Albertecce5032015-05-18 16:46:31 -07001044 delete t;
Luis Hector Chavez77719202018-04-17 14:09:21 -07001045 return -EALREADY;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001046 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001047 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001048
Elliott Hughes85952832015-10-07 15:59:35 -07001049 for (const auto& transport : transport_list) {
Dan Albertecce5032015-05-18 16:46:31 -07001050 if (transport->serial && strcmp(serial, transport->serial) == 0) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001051 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao0d6aa992016-11-22 14:32:34 -08001052 << " is already in transport_list and fails to register";
Dan Albertecce5032015-05-18 16:46:31 -07001053 delete t;
Luis Hector Chavez77719202018-04-17 14:09:21 -07001054 return -EALREADY;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001055 }
1056 }
1057
Dan Albertecce5032015-05-18 16:46:31 -07001058 pending_list.push_front(t);
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001059 t->serial = strdup(serial);
Josh Gaoe7daf572016-09-21 12:37:10 -07001060
1061 lock.unlock();
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001062
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001063 auto waitable = t->connection_waitable();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001064 register_transport(t);
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001065
Luis Hector Chavez25bc41c2018-05-01 17:12:16 -07001066 if (local == 1) {
1067 // Do not wait for emulator transports.
1068 return 0;
1069 }
1070
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001071 return waitable->WaitForConnection(std::chrono::seconds(10)) ? 0 : -1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001072}
1073
Mike Lockwood81ffe172009-10-11 23:04:18 -04001074#if ADB_HOST
Josh Gao0d6aa992016-11-22 14:32:34 -08001075atransport* find_transport(const char* serial) {
Dan Albertecce5032015-05-18 16:46:31 -07001076 atransport* result = nullptr;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001077
Josh Gaoaaa82f72017-08-17 13:50:51 -07001078 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui4d64fd82015-08-27 12:03:11 -07001079 for (auto& t : transport_list) {
Dan Albertecce5032015-05-18 16:46:31 -07001080 if (t->serial && strcmp(serial, t->serial) == 0) {
1081 result = t;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001082 break;
1083 }
Dan Albertecce5032015-05-18 16:46:31 -07001084 }
Mike Lockwood81ffe172009-10-11 23:04:18 -04001085
Dan Albertecce5032015-05-18 16:46:31 -07001086 return result;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001087}
1088
Yabin Cui4d64fd82015-08-27 12:03:11 -07001089void kick_all_tcp_devices() {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001090 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui4d64fd82015-08-27 12:03:11 -07001091 for (auto& t : transport_list) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001092 if (t->IsTcpDevice()) {
Yabin Cui4e222292015-08-31 11:50:24 -07001093 // Kicking breaks the read_transport thread of this transport out of any read, then
1094 // the read_transport thread will notify the main thread to make this transport
1095 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cui4d64fd82015-08-27 12:03:11 -07001096 // Finally, this transport will be closed and freed in the main thread.
Yabin Cuif2a9f9b2016-04-18 11:22:34 -07001097 t->Kick();
Mike Lockwood01c2c302010-05-24 10:44:35 -04001098 }
Dan Albertecce5032015-05-18 16:46:31 -07001099 }
Mike Lockwood01c2c302010-05-24 10:44:35 -04001100}
1101
Mike Lockwood81ffe172009-10-11 23:04:18 -04001102#endif
1103
Josh Gao0d6aa992016-11-22 14:32:34 -08001104void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1105 unsigned writeable) {
Josh Gao7a7c5cb2018-05-04 16:04:49 -07001106 atransport* t = new atransport((writeable ? kCsConnecting : kCsNoPerm));
Dan Albertecce5032015-05-18 16:46:31 -07001107
Josh Gao0d6aa992016-11-22 14:32:34 -08001108 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cui3cf1b362017-03-10 16:01:01 -08001109 init_usb_transport(t, usb);
Josh Gao0d6aa992016-11-22 14:32:34 -08001110 if (serial) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001111 t->serial = strdup(serial);
1112 }
Dan Albertecce5032015-05-18 16:46:31 -07001113
1114 if (devpath) {
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001115 t->devpath = strdup(devpath);
1116 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001117
Josh Gaoe7daf572016-09-21 12:37:10 -07001118 {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001119 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaoe7daf572016-09-21 12:37:10 -07001120 pending_list.push_front(t);
1121 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001122
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001123 register_transport(t);
1124}
1125
Dan Albert9a50f4c2015-05-18 16:43:57 -07001126// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao0d6aa992016-11-22 14:32:34 -08001127void unregister_usb_transport(usb_handle* usb) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001128 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao395b86a2018-01-28 20:32:46 -08001129 transport_list.remove_if([usb](atransport* t) {
Luis Hector Chavez3c7881d2018-04-25 08:56:41 -07001130 auto connection = t->connection();
1131 if (auto usb_connection = dynamic_cast<UsbConnection*>(connection.get())) {
1132 return usb_connection->handle_ == usb && t->GetConnectionState() == kCsNoPerm;
Josh Gao395b86a2018-01-28 20:32:46 -08001133 }
1134 return false;
1135 });
Mike Lockwoode45583f2009-08-08 12:37:44 -04001136}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001137
Josh Gao67b683a2017-05-16 15:02:45 -07001138bool check_header(apacket* p, atransport* t) {
Josh Gao0d6aa992016-11-22 14:32:34 -08001139 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cui3cf1b362017-03-10 16:01:01 -08001140 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1141 << ", magic = " << p->msg.magic;
Josh Gao67b683a2017-05-16 15:02:45 -07001142 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001143 }
1144
Josh Gao0d6aa992016-11-22 14:32:34 -08001145 if (p->msg.data_length > t->get_max_payload()) {
1146 VLOG(RWX) << "check_header(): " << p->msg.data_length
1147 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao67b683a2017-05-16 15:02:45 -07001148 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001149 }
1150
Josh Gao67b683a2017-05-16 15:02:45 -07001151 return true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001152}
1153
Josh Gaoeac20582016-10-05 19:02:29 -07001154#if ADB_HOST
Josh Gao22cb70b2016-08-18 22:00:12 -07001155std::shared_ptr<RSA> atransport::NextKey() {
Elliott Hughes801066a2016-06-29 17:42:01 -07001156 if (keys_.empty()) keys_ = adb_auth_get_private_keys();
1157
Josh Gao22cb70b2016-08-18 22:00:12 -07001158 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes801066a2016-06-29 17:42:01 -07001159 keys_.pop_front();
1160 return result;
1161}
Josh Gaoeac20582016-10-05 19:02:29 -07001162#endif