blob: 0ab428e0d506ec3fe45b7ed97dac5cbd78f2127c [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;
520 t->connection->SetTransportName(t->serial_name());
521 t->connection->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
522 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 });
534 t->connection->SetErrorCallback([t](Connection*, const std::string& error) {
535 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
Josh Gao715fe602018-02-16 13:24:58 -0800542 t->connection->Start();
543#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);
Josh Gao715fe602018-02-16 13:24:58 -0800611 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
Elliott Hughes67943d12015-10-07 14:55:10 -0700711 // Don't return unauthorized devices; the caller can't do anything with them.
Yabin Cui3cf1b362017-03-10 16:01:01 -0800712 if (result && result->GetConnectionState() == kCsUnauthorized && !accept_any_state) {
Elliott Hughes67943d12015-10-07 14:55:10 -0700713 *error_out = "device unauthorized.\n";
714 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
715 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
716 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
717 *error_out += "\n";
718 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
719 *error_out += "Otherwise check for a confirmation dialog on your device.";
720 result = nullptr;
721 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -0700722
Elliott Hughes67943d12015-10-07 14:55:10 -0700723 // Don't return offline devices; the caller can't do anything with them.
Yabin Cui3cf1b362017-03-10 16:01:01 -0800724 if (result && result->GetConnectionState() == kCsOffline && !accept_any_state) {
Elliott Hughes67943d12015-10-07 14:55:10 -0700725 *error_out = "device offline";
726 result = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800727 }
728
729 if (result) {
Elliott Hughes24f52762015-06-23 13:00:32 -0700730 *error_out = "success";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800731 }
732
733 return result;
734}
735
Luis Hector Chavezda74b902018-04-17 14:25:04 -0700736bool ConnectionWaitable::WaitForConnection(std::chrono::milliseconds timeout) {
737 std::unique_lock<std::mutex> lock(mutex_);
738 ScopedAssumeLocked assume_locked(mutex_);
739 return cv_.wait_for(lock, timeout, [&]() REQUIRES(mutex_) {
740 return connection_established_ready_;
741 }) && connection_established_;
742}
743
744void ConnectionWaitable::SetConnectionEstablished(bool success) {
745 {
746 std::lock_guard<std::mutex> lock(mutex_);
747 if (connection_established_ready_) return;
748 connection_established_ready_ = true;
749 connection_established_ = success;
750 D("connection established with %d", success);
751 }
752 cv_.notify_one();
753}
754
755atransport::~atransport() {
756 // If the connection callback had not been run before, run it now.
757 SetConnectionEstablished(false);
758}
759
Yabin Cui3cf1b362017-03-10 16:01:01 -0800760int atransport::Write(apacket* p) {
Josh Gao715fe602018-02-16 13:24:58 -0800761 return this->connection->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cui3cf1b362017-03-10 16:01:01 -0800762}
763
Yabin Cuif2a9f9b2016-04-18 11:22:34 -0700764void atransport::Kick() {
765 if (!kicked_) {
Josh Gao395b86a2018-01-28 20:32:46 -0800766 D("kicking transport %s", this->serial);
Yabin Cuif2a9f9b2016-04-18 11:22:34 -0700767 kicked_ = true;
Josh Gao715fe602018-02-16 13:24:58 -0800768 this->connection->Stop();
Yabin Cuif2a9f9b2016-04-18 11:22:34 -0700769 }
770}
771
Yabin Cui3cf1b362017-03-10 16:01:01 -0800772ConnectionState atransport::GetConnectionState() const {
773 return connection_state_;
774}
775
776void atransport::SetConnectionState(ConnectionState state) {
777 check_main_thread();
778 connection_state_ = state;
779}
780
Josh Gao3cd03be2018-02-28 14:44:23 -0800781std::string atransport::connection_state_name() const {
Yabin Cui3cf1b362017-03-10 16:01:01 -0800782 ConnectionState state = GetConnectionState();
783 switch (state) {
Josh Gao0d6aa992016-11-22 14:32:34 -0800784 case kCsOffline:
785 return "offline";
786 case kCsBootloader:
787 return "bootloader";
788 case kCsDevice:
789 return "device";
790 case kCsHost:
791 return "host";
792 case kCsRecovery:
793 return "recovery";
794 case kCsNoPerm:
795 return UsbNoPermissionsShortHelpText();
796 case kCsSideload:
797 return "sideload";
798 case kCsUnauthorized:
799 return "unauthorized";
800 default:
801 return "unknown";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800802 }
803}
804
Tamas Berghammera1c60c02015-07-13 19:12:28 +0100805void atransport::update_version(int version, size_t payload) {
806 protocol_version = std::min(version, A_VERSION);
807 max_payload = std::min(payload, MAX_PAYLOAD);
808}
809
810int atransport::get_protocol_version() const {
811 return protocol_version;
812}
813
814size_t atransport::get_max_payload() const {
815 return max_payload;
816}
817
David Pursella07dbad2015-09-22 10:43:08 -0700818namespace {
David Pursell8da19a42015-08-31 10:42:13 -0700819
David Pursella07dbad2015-09-22 10:43:08 -0700820constexpr char kFeatureStringDelimiter = ',';
821
822} // namespace
Dan Albertbe8e54b2015-05-18 13:06:53 -0700823
824const FeatureSet& supported_features() {
David Pursella07dbad2015-09-22 10:43:08 -0700825 // Local static allocation to avoid global non-POD variables.
826 static const FeatureSet* features = new FeatureSet{
Josh Gao0d6aa992016-11-22 14:32:34 -0800827 kFeatureShell2, kFeatureCmd, kFeatureStat2,
David Pursell6d5fad32015-09-25 08:37:13 -0700828 // Increment ADB_SERVER_VERSION whenever the feature list changes to
829 // make sure that the adb client and server features stay in sync
830 // (http://b/24370690).
David Pursella07dbad2015-09-22 10:43:08 -0700831 };
832
833 return *features;
834}
835
836std::string FeatureSetToString(const FeatureSet& features) {
837 return android::base::Join(features, kFeatureStringDelimiter);
838}
839
840FeatureSet StringToFeatureSet(const std::string& features_string) {
David Pursell3d9072b2015-09-25 13:04:21 -0700841 if (features_string.empty()) {
842 return FeatureSet();
843 }
844
Josh Gao0d6aa992016-11-22 14:32:34 -0800845 auto names = android::base::Split(features_string, {kFeatureStringDelimiter});
David Pursella07dbad2015-09-22 10:43:08 -0700846 return FeatureSet(names.begin(), names.end());
Dan Albertbe8e54b2015-05-18 13:06:53 -0700847}
848
David Pursell22fc5e92015-09-30 13:35:42 -0700849bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao0d6aa992016-11-22 14:32:34 -0800850 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell22fc5e92015-09-30 13:35:42 -0700851}
852
Dan Albertbe8e54b2015-05-18 13:06:53 -0700853bool atransport::has_feature(const std::string& feature) const {
854 return features_.count(feature) > 0;
855}
856
David Pursella07dbad2015-09-22 10:43:08 -0700857void atransport::SetFeatures(const std::string& features_string) {
858 features_ = StringToFeatureSet(features_string);
Dan Albertbe8e54b2015-05-18 13:06:53 -0700859}
860
Yabin Cui2d4c1982015-08-28 15:09:44 -0700861void atransport::AddDisconnect(adisconnect* disconnect) {
862 disconnects_.push_back(disconnect);
863}
864
865void atransport::RemoveDisconnect(adisconnect* disconnect) {
866 disconnects_.remove(disconnect);
867}
868
869void atransport::RunDisconnects() {
Elliott Hughes85952832015-10-07 15:59:35 -0700870 for (const auto& disconnect : disconnects_) {
Yabin Cui2d4c1982015-08-28 15:09:44 -0700871 disconnect->func(disconnect->opaque, this);
872 }
873 disconnects_.clear();
874}
875
David Pursellc929c6f2016-03-01 08:58:26 -0800876bool atransport::MatchesTarget(const std::string& target) const {
877 if (serial) {
878 if (target == serial) {
879 return true;
880 } else if (type == kTransportLocal) {
881 // Local transports can match [tcp:|udp:]<hostname>[:port].
882 const char* local_target_ptr = target.c_str();
883
884 // For fastboot compatibility, ignore protocol prefixes.
885 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao0d6aa992016-11-22 14:32:34 -0800886 android::base::StartsWith(target, "udp:")) {
David Pursellc929c6f2016-03-01 08:58:26 -0800887 local_target_ptr += 4;
888 }
889
890 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
891 std::string serial_host, error;
892 int serial_port = -1;
Josh Gao0d6aa992016-11-22 14:32:34 -0800893 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursellc929c6f2016-03-01 08:58:26 -0800894 // |target| may omit the port to default to ours.
895 std::string target_host;
896 int target_port = serial_port;
897 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
898 nullptr, &error) &&
Josh Gao0d6aa992016-11-22 14:32:34 -0800899 serial_host == target_host && serial_port == target_port) {
David Pursellc929c6f2016-03-01 08:58:26 -0800900 return true;
901 }
902 }
903 }
904 }
905
906 return (devpath && target == devpath) ||
907 qual_match(target.c_str(), "product:", product, false) ||
908 qual_match(target.c_str(), "model:", model, true) ||
909 qual_match(target.c_str(), "device:", device, false);
910}
911
Luis Hector Chavezda74b902018-04-17 14:25:04 -0700912void atransport::SetConnectionEstablished(bool success) {
913 connection_waitable_->SetConnectionEstablished(success);
914}
915
Elliott Hughes88b4c852015-04-30 17:32:03 -0700916#if ADB_HOST
917
Josh Gaob39e4152017-08-16 16:57:01 -0700918// We use newline as our delimiter, make sure to never output it.
919static std::string sanitize(std::string str, bool alphanumeric) {
920 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
921 : [](const char c) { return c == '\n'; };
922 std::replace_if(str.begin(), str.end(), pred, '_');
923 return str;
924}
925
Josh Gao0d6aa992016-11-22 14:32:34 -0800926static void append_transport_info(std::string* result, const char* key, const char* value,
Josh Gaob39e4152017-08-16 16:57:01 -0700927 bool alphanumeric) {
Elliott Hughes88b4c852015-04-30 17:32:03 -0700928 if (value == nullptr || *value == '\0') {
Scott Anderson27042382012-05-30 18:11:27 -0700929 return;
Scott Anderson27042382012-05-30 18:11:27 -0700930 }
931
Elliott Hughes88b4c852015-04-30 17:32:03 -0700932 *result += ' ';
933 *result += key;
Josh Gaob39e4152017-08-16 16:57:01 -0700934 *result += sanitize(value, alphanumeric);
Scott Anderson27042382012-05-30 18:11:27 -0700935}
936
Josh Gao0d6aa992016-11-22 14:32:34 -0800937static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Scott Anderson27042382012-05-30 18:11:27 -0700938 const char* serial = t->serial;
Elliott Hughes88b4c852015-04-30 17:32:03 -0700939 if (!serial || !serial[0]) {
Dan Alberta8c34142015-05-06 16:48:52 -0700940 serial = "(no serial number)";
Elliott Hughes88b4c852015-04-30 17:32:03 -0700941 }
Scott Anderson27042382012-05-30 18:11:27 -0700942
943 if (!long_listing) {
Elliott Hughes88b4c852015-04-30 17:32:03 -0700944 *result += serial;
945 *result += '\t';
946 *result += t->connection_state_name();
Scott Anderson27042382012-05-30 18:11:27 -0700947 } else {
Josh Gao0d6aa992016-11-22 14:32:34 -0800948 android::base::StringAppendF(result, "%-22s %s", serial, t->connection_state_name().c_str());
Scott Anderson27042382012-05-30 18:11:27 -0700949
Elliott Hughes88b4c852015-04-30 17:32:03 -0700950 append_transport_info(result, "", t->devpath, false);
951 append_transport_info(result, "product:", t->product, false);
952 append_transport_info(result, "model:", t->model, true);
953 append_transport_info(result, "device:", t->device, false);
Josh Gaob39e4152017-08-16 16:57:01 -0700954
955 // Put id at the end, so that anyone parsing the output here can always find it by scanning
956 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
957 *result += " transport_id:";
958 *result += std::to_string(t->id);
Scott Anderson27042382012-05-30 18:11:27 -0700959 }
Elliott Hughes88b4c852015-04-30 17:32:03 -0700960 *result += '\n';
Scott Anderson27042382012-05-30 18:11:27 -0700961}
962
Elliott Hughes88b4c852015-04-30 17:32:03 -0700963std::string list_transports(bool long_listing) {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700964 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov4dd35012017-12-17 10:56:07 +0000965
966 auto sorted_transport_list = transport_list;
967 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
968 if (x->type != y->type) {
969 return x->type < y->type;
970 }
971 return strcmp(x->serial, y->serial) < 0;
972 });
973
974 std::string result;
975 for (const auto& t : sorted_transport_list) {
Elliott Hughes88b4c852015-04-30 17:32:03 -0700976 append_transport(t, &result, long_listing);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800977 }
Elliott Hughes88b4c852015-04-30 17:32:03 -0700978 return result;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800979}
980
Josh Gao4e562502016-10-27 14:01:08 -0700981void close_usb_devices(std::function<bool(const atransport*)> predicate) {
Josh Gaoaaa82f72017-08-17 13:50:51 -0700982 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao4e562502016-10-27 14:01:08 -0700983 for (auto& t : transport_list) {
984 if (predicate(t)) {
985 t->Kick();
986 }
987 }
988}
989
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800990/* hack for osx */
Dan Albertecce5032015-05-18 16:46:31 -0700991void close_usb_devices() {
Josh Gao4e562502016-10-27 14:01:08 -0700992 close_usb_devices([](const atransport*) { return true; });
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800993}
Josh Gao0d6aa992016-11-22 14:32:34 -0800994#endif // ADB_HOST
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800995
Josh Gao0d6aa992016-11-22 14:32:34 -0800996int register_socket_transport(int s, const char* serial, int port, int local) {
Dan Albertecce5032015-05-18 16:46:31 -0700997 atransport* t = new atransport();
David 'Digit' Turner58f59682011-01-06 14:11:07 +0100998
999 if (!serial) {
Dan Albertecce5032015-05-18 16:46:31 -07001000 char buf[32];
1001 snprintf(buf, sizeof(buf), "T-%p", t);
1002 serial = buf;
David 'Digit' Turner58f59682011-01-06 14:11:07 +01001003 }
Dan Albertecce5032015-05-18 16:46:31 -07001004
Yabin Cui815ad882015-09-02 17:44:28 -07001005 D("transport: %s init'ing for socket %d, on port %d", serial, s, port);
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001006 if (init_socket_transport(t, s, port, local) < 0) {
Dan Albertecce5032015-05-18 16:46:31 -07001007 delete t;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001008 return -1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001009 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001010
Josh Gaoaaa82f72017-08-17 13:50:51 -07001011 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes85952832015-10-07 15:59:35 -07001012 for (const auto& transport : pending_list) {
Dan Albertecce5032015-05-18 16:46:31 -07001013 if (transport->serial && strcmp(serial, transport->serial) == 0) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001014 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao0d6aa992016-11-22 14:32:34 -08001015 << " is already in pending_list and fails to register";
Dan Albertecce5032015-05-18 16:46:31 -07001016 delete t;
Luis Hector Chavez77719202018-04-17 14:09:21 -07001017 return -EALREADY;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001018 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001019 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001020
Elliott Hughes85952832015-10-07 15:59:35 -07001021 for (const auto& transport : transport_list) {
Dan Albertecce5032015-05-18 16:46:31 -07001022 if (transport->serial && strcmp(serial, transport->serial) == 0) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001023 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao0d6aa992016-11-22 14:32:34 -08001024 << " is already in transport_list and fails to register";
Dan Albertecce5032015-05-18 16:46:31 -07001025 delete t;
Luis Hector Chavez77719202018-04-17 14:09:21 -07001026 return -EALREADY;
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001027 }
1028 }
1029
Dan Albertecce5032015-05-18 16:46:31 -07001030 pending_list.push_front(t);
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001031 t->serial = strdup(serial);
Josh Gaoe7daf572016-09-21 12:37:10 -07001032
1033 lock.unlock();
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001034
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001035 auto waitable = t->connection_waitable();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001036 register_transport(t);
Luis Hector Chavezda74b902018-04-17 14:25:04 -07001037
1038 return waitable->WaitForConnection(std::chrono::seconds(10)) ? 0 : -1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001039}
1040
Mike Lockwood81ffe172009-10-11 23:04:18 -04001041#if ADB_HOST
Josh Gao0d6aa992016-11-22 14:32:34 -08001042atransport* find_transport(const char* serial) {
Dan Albertecce5032015-05-18 16:46:31 -07001043 atransport* result = nullptr;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001044
Josh Gaoaaa82f72017-08-17 13:50:51 -07001045 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui4d64fd82015-08-27 12:03:11 -07001046 for (auto& t : transport_list) {
Dan Albertecce5032015-05-18 16:46:31 -07001047 if (t->serial && strcmp(serial, t->serial) == 0) {
1048 result = t;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001049 break;
1050 }
Dan Albertecce5032015-05-18 16:46:31 -07001051 }
Mike Lockwood81ffe172009-10-11 23:04:18 -04001052
Dan Albertecce5032015-05-18 16:46:31 -07001053 return result;
Mike Lockwood81ffe172009-10-11 23:04:18 -04001054}
1055
Yabin Cui4d64fd82015-08-27 12:03:11 -07001056void kick_all_tcp_devices() {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001057 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui4d64fd82015-08-27 12:03:11 -07001058 for (auto& t : transport_list) {
Yabin Cuif401ead2016-04-29 16:53:52 -07001059 if (t->IsTcpDevice()) {
Yabin Cui4e222292015-08-31 11:50:24 -07001060 // Kicking breaks the read_transport thread of this transport out of any read, then
1061 // the read_transport thread will notify the main thread to make this transport
1062 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cui4d64fd82015-08-27 12:03:11 -07001063 // Finally, this transport will be closed and freed in the main thread.
Yabin Cuif2a9f9b2016-04-18 11:22:34 -07001064 t->Kick();
Mike Lockwood01c2c302010-05-24 10:44:35 -04001065 }
Dan Albertecce5032015-05-18 16:46:31 -07001066 }
Mike Lockwood01c2c302010-05-24 10:44:35 -04001067}
1068
Mike Lockwood81ffe172009-10-11 23:04:18 -04001069#endif
1070
Josh Gao0d6aa992016-11-22 14:32:34 -08001071void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1072 unsigned writeable) {
Yabin Cui3cf1b362017-03-10 16:01:01 -08001073 atransport* t = new atransport((writeable ? kCsOffline : kCsNoPerm));
Dan Albertecce5032015-05-18 16:46:31 -07001074
Josh Gao0d6aa992016-11-22 14:32:34 -08001075 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cui3cf1b362017-03-10 16:01:01 -08001076 init_usb_transport(t, usb);
Josh Gao0d6aa992016-11-22 14:32:34 -08001077 if (serial) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001078 t->serial = strdup(serial);
1079 }
Dan Albertecce5032015-05-18 16:46:31 -07001080
1081 if (devpath) {
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001082 t->devpath = strdup(devpath);
1083 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001084
Josh Gaoe7daf572016-09-21 12:37:10 -07001085 {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001086 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaoe7daf572016-09-21 12:37:10 -07001087 pending_list.push_front(t);
1088 }
Benoit Goby3f9f9ce2013-03-29 18:22:36 -07001089
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001090 register_transport(t);
1091}
1092
Dan Albert9a50f4c2015-05-18 16:43:57 -07001093// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao0d6aa992016-11-22 14:32:34 -08001094void unregister_usb_transport(usb_handle* usb) {
Josh Gaoaaa82f72017-08-17 13:50:51 -07001095 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao395b86a2018-01-28 20:32:46 -08001096 transport_list.remove_if([usb](atransport* t) {
1097 if (auto connection = dynamic_cast<UsbConnection*>(t->connection.get())) {
1098 return connection->handle_ == usb && t->GetConnectionState() == kCsNoPerm;
1099 }
1100 return false;
1101 });
Mike Lockwoode45583f2009-08-08 12:37:44 -04001102}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001103
Josh Gao67b683a2017-05-16 15:02:45 -07001104bool check_header(apacket* p, atransport* t) {
Josh Gao0d6aa992016-11-22 14:32:34 -08001105 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cui3cf1b362017-03-10 16:01:01 -08001106 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1107 << ", magic = " << p->msg.magic;
Josh Gao67b683a2017-05-16 15:02:45 -07001108 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001109 }
1110
Josh Gao0d6aa992016-11-22 14:32:34 -08001111 if (p->msg.data_length > t->get_max_payload()) {
1112 VLOG(RWX) << "check_header(): " << p->msg.data_length
1113 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao67b683a2017-05-16 15:02:45 -07001114 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001115 }
1116
Josh Gao67b683a2017-05-16 15:02:45 -07001117 return true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001118}
1119
Josh Gaoeac20582016-10-05 19:02:29 -07001120#if ADB_HOST
Josh Gao22cb70b2016-08-18 22:00:12 -07001121std::shared_ptr<RSA> atransport::NextKey() {
Elliott Hughes801066a2016-06-29 17:42:01 -07001122 if (keys_.empty()) keys_ = adb_auth_get_private_keys();
1123
Josh Gao22cb70b2016-08-18 22:00:12 -07001124 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes801066a2016-06-29 17:42:01 -07001125 keys_.pop_front();
1126 return result;
1127}
Josh Gaoeac20582016-10-05 19:02:29 -07001128#endif