blob: 92c52e23c79eb80995dc1c89d735569063c88c0a [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yabin Cuiaed3c612015-09-22 15:52:57 -070017#define TRACE_TAG TRANSPORT
Dan Albert76649012015-02-24 15:51:19 -080018
Dan Albert33134262015-03-19 15:21:08 -070019#include "sysdeps.h"
Josh Gao31b5be62018-03-07 16:51:08 -080020#include "sysdeps/memory.h"
21
Dan Albert76649012015-02-24 15:51:19 -080022#include "transport.h"
23
Dan Albert055f1aa2015-02-20 17:24:58 -080024#include <ctype.h>
Dan Albert76649012015-02-24 15:51:19 -080025#include <errno.h>
Josh Gaob122b172017-08-16 16:57:01 -070026#include <inttypes.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080027#include <stdio.h>
28#include <stdlib.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080029#include <string.h>
Dan Albert76649012015-02-24 15:51:19 -080030#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080031
Spencer Low363af562015-11-07 18:51:54 -080032#include <algorithm>
Josh Gao0bbf69c2018-02-16 13:24:58 -080033#include <deque>
Dan Albertc7915a32015-05-18 16:46:31 -070034#include <list>
Josh Gao0cd3ae12016-09-21 12:37:10 -070035#include <mutex>
Josh Gaoe1dacfc2017-04-12 17:00:49 -070036#include <thread>
Dan Albertc7915a32015-05-18 16:46:31 -070037
Elliott Hughes4f713192015-12-04 22:00:26 -080038#include <android-base/logging.h>
David Pursell3f902aa2016-03-01 08:58:26 -080039#include <android-base/parsenetaddress.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080040#include <android-base/stringprintf.h>
41#include <android-base/strings.h>
Josh Gaob122b172017-08-16 16:57:01 -070042#include <android-base/thread_annotations.h>
Elliott Hughese67f1f82015-04-30 17:32:03 -070043
Josh Gao27768452018-01-02 12:01:43 -080044#include <diagnose_usb.h>
45
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080046#include "adb.h"
Elliott Hughes0aeb5052016-06-29 17:42:01 -070047#include "adb_auth.h"
Josh Gaob800d882018-01-28 20:32:46 -080048#include "adb_io.h"
Josh Gaocfe72e22016-11-29 09:40:29 -080049#include "adb_trace.h"
Elliott Hughese67f1f82015-04-30 17:32:03 -070050#include "adb_utils.h"
Yabin Cuib5e11412017-03-10 16:01:01 -080051#include "fdevent.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080052
53static void transport_unref(atransport *t);
54
Josh Gaob122b172017-08-16 16:57:01 -070055// TODO: unordered_map<TransportId, atransport*>
Josh Gaob7b1edf2015-11-11 17:56:12 -080056static auto& transport_list = *new std::list<atransport*>();
57static auto& pending_list = *new std::list<atransport*>();
Benoit Goby1c45ee92013-03-29 18:22:36 -070058
Josh Gao1db71af2017-08-17 13:50:51 -070059static auto& transport_lock = *new std::recursive_mutex();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080060
Todd Kennedy51c05ec2015-11-10 00:03:25 +000061const char* const kFeatureShell2 = "shell_v2";
62const char* const kFeatureCmd = "cmd";
Josh Gao5a1e3fd2016-12-05 17:11:34 -080063const char* const kFeatureStat2 = "stat_v2";
Josh Gao5d1756c2017-02-22 17:07:01 -080064const char* const kFeatureLibusb = "libusb";
Dan Albert5176df82017-05-23 14:30:00 -070065const char* const kFeaturePushSync = "push_sync";
Todd Kennedy51c05ec2015-11-10 00:03:25 +000066
Josh Gaob122b172017-08-16 16:57:01 -070067TransportId NextTransportId() {
68 static std::atomic<TransportId> next(1);
69 return next++;
70}
71
Josh Gao0bbf69c2018-02-16 13:24:58 -080072BlockingConnectionAdapter::BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection)
73 : underlying_(std::move(connection)) {}
74
75BlockingConnectionAdapter::~BlockingConnectionAdapter() {
76 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): destructing";
77 Stop();
78}
79
Josh Gaoc251ec52018-04-03 12:55:18 -070080static void AssumeLocked(std::mutex& mutex) ASSERT_CAPABILITY(mutex) {}
81
Josh Gao0bbf69c2018-02-16 13:24:58 -080082void BlockingConnectionAdapter::Start() {
Josh Gaoc251ec52018-04-03 12:55:18 -070083 std::lock_guard<std::mutex> lock(mutex_);
84 if (started_) {
85 LOG(FATAL) << "BlockingConnectionAdapter(" << this->transport_name_
86 << "): started multiple times";
87 }
88
Josh Gao0bbf69c2018-02-16 13:24:58 -080089 read_thread_ = std::thread([this]() {
90 LOG(INFO) << this->transport_name_ << ": read thread spawning";
91 while (true) {
Josh Gao31b5be62018-03-07 16:51:08 -080092 auto packet = std::make_unique<apacket>();
Josh Gao0bbf69c2018-02-16 13:24:58 -080093 if (!underlying_->Read(packet.get())) {
94 PLOG(INFO) << this->transport_name_ << ": read failed";
95 break;
96 }
97 read_callback_(this, std::move(packet));
98 }
99 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "read failed"); });
100 });
101
102 write_thread_ = std::thread([this]() {
103 LOG(INFO) << this->transport_name_ << ": write thread spawning";
104 while (true) {
105 std::unique_lock<std::mutex> lock(mutex_);
Josh Gaoc251ec52018-04-03 12:55:18 -0700106 cv_.wait(lock, [this]() REQUIRES(mutex_) {
107 return this->stopped_ || !this->write_queue_.empty();
108 });
109
110 AssumeLocked(mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800111
112 if (this->stopped_) {
113 return;
114 }
115
116 std::unique_ptr<apacket> packet = std::move(this->write_queue_.front());
117 this->write_queue_.pop_front();
118 lock.unlock();
119
120 if (!this->underlying_->Write(packet.get())) {
121 break;
122 }
123 }
124 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "write failed"); });
125 });
Josh Gaoc251ec52018-04-03 12:55:18 -0700126
127 started_ = true;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800128}
129
130void BlockingConnectionAdapter::Stop() {
Josh Gaoc251ec52018-04-03 12:55:18 -0700131 {
132 std::lock_guard<std::mutex> lock(mutex_);
133 if (!started_) {
134 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): not started";
135 return;
136 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800137
Josh Gaoc251ec52018-04-03 12:55:18 -0700138 if (stopped_) {
139 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_
140 << "): already stopped";
141 return;
142 }
143
144 stopped_ = true;
145 }
Josh Gao0bbf69c2018-02-16 13:24:58 -0800146
147 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopping";
148
149 this->underlying_->Close();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800150 this->cv_.notify_one();
Josh Gaoc251ec52018-04-03 12:55:18 -0700151
152 // Move the threads out into locals with the lock taken, and then unlock to let them exit.
153 std::thread read_thread;
154 std::thread write_thread;
155
156 {
157 std::lock_guard<std::mutex> lock(mutex_);
158 read_thread = std::move(read_thread_);
159 write_thread = std::move(write_thread_);
160 }
161
162 read_thread.join();
163 write_thread.join();
Josh Gao0bbf69c2018-02-16 13:24:58 -0800164
165 LOG(INFO) << "BlockingConnectionAdapter(" << this->transport_name_ << "): stopped";
166 std::call_once(this->error_flag_, [this]() { this->error_callback_(this, "requested stop"); });
167}
168
169bool BlockingConnectionAdapter::Write(std::unique_ptr<apacket> packet) {
170 {
Josh Gaoc251ec52018-04-03 12:55:18 -0700171 std::lock_guard<std::mutex> lock(this->mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800172 write_queue_.emplace_back(std::move(packet));
173 }
174
175 cv_.notify_one();
176 return true;
177}
178
Josh Gaob800d882018-01-28 20:32:46 -0800179bool FdConnection::Read(apacket* packet) {
180 if (!ReadFdExactly(fd_.get(), &packet->msg, sizeof(amessage))) {
181 D("remote local: read terminated (message)");
182 return false;
183 }
184
Josh Gaof571fcb2018-02-05 18:49:10 -0800185 if (packet->msg.data_length > MAX_PAYLOAD) {
Josh Gao5caaebd2018-02-02 14:38:04 -0800186 D("remote local: read overflow (data length = %" PRIu32 ")", packet->msg.data_length);
187 return false;
188 }
189
Josh Gaof571fcb2018-02-05 18:49:10 -0800190 packet->payload.resize(packet->msg.data_length);
191
192 if (!ReadFdExactly(fd_.get(), &packet->payload[0], packet->payload.size())) {
Josh Gaob800d882018-01-28 20:32:46 -0800193 D("remote local: terminated (data)");
194 return false;
195 }
196
197 return true;
198}
199
200bool FdConnection::Write(apacket* packet) {
Josh Gaof571fcb2018-02-05 18:49:10 -0800201 if (!WriteFdExactly(fd_.get(), &packet->msg, sizeof(packet->msg))) {
Josh Gaob800d882018-01-28 20:32:46 -0800202 D("remote local: write terminated");
203 return false;
204 }
205
Josh Gaof571fcb2018-02-05 18:49:10 -0800206 if (packet->msg.data_length) {
207 if (!WriteFdExactly(fd_.get(), &packet->payload[0], packet->msg.data_length)) {
208 D("remote local: write terminated");
209 return false;
210 }
211 }
212
Josh Gaob800d882018-01-28 20:32:46 -0800213 return true;
214}
215
216void FdConnection::Close() {
217 adb_shutdown(fd_.get());
218 fd_.reset();
219}
220
Yabin Cuiaed3c612015-09-22 15:52:57 -0700221static std::string dump_packet(const char* name, const char* func, apacket* p) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800222 unsigned command = p->msg.command;
223 int len = p->msg.data_length;
224 char cmd[9];
225 char arg0[12], arg1[12];
226 int n;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100227
228 for (n = 0; n < 4; n++) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800229 int b = (command >> (n * 8)) & 255;
230 if (b < 32 || b >= 127) break;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100231 cmd[n] = (char)b;
232 }
233 if (n == 4) {
234 cmd[4] = 0;
235 } else {
236 /* There is some non-ASCII name in the command, so dump
237 * the hexadecimal value instead */
238 snprintf(cmd, sizeof cmd, "%08x", command);
239 }
240
241 if (p->msg.arg0 < 256U)
242 snprintf(arg0, sizeof arg0, "%d", p->msg.arg0);
243 else
244 snprintf(arg0, sizeof arg0, "0x%x", p->msg.arg0);
245
246 if (p->msg.arg1 < 256U)
247 snprintf(arg1, sizeof arg1, "%d", p->msg.arg1);
248 else
249 snprintf(arg1, sizeof arg1, "0x%x", p->msg.arg1);
250
Josh Gao1290fbf2016-11-22 14:32:34 -0800251 std::string result = android::base::StringPrintf("%s: %s: [%s] arg0=%s arg1=%s (len=%d) ", name,
252 func, cmd, arg0, arg1, len);
Josh Gaof571fcb2018-02-05 18:49:10 -0800253 result += dump_hex(p->payload.data(), p->payload.size());
Yabin Cuiaed3c612015-09-22 15:52:57 -0700254 return result;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100255}
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100256
Josh Gao06d61d42016-10-06 13:31:44 -0700257void send_packet(apacket* p, atransport* t) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800258 p->msg.magic = p->msg.command ^ 0xffffffff;
Tim Murrayde471942017-12-07 11:40:00 -0800259 // compute a checksum for connection/auth packets for compatibility reasons
260 if (t->get_protocol_version() >= A_VERSION_SKIP_CHECKSUM) {
261 p->msg.data_check = 0;
262 } else {
263 p->msg.data_check = calculate_apacket_checksum(p);
264 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800265
Josh Gao0bbf69c2018-02-16 13:24:58 -0800266 VLOG(TRANSPORT) << dump_packet(t->serial, "to remote", p);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800267
268 if (t == NULL) {
Josh Gao06d61d42016-10-06 13:31:44 -0700269 fatal("Transport is null");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800270 }
271
Josh Gao0bbf69c2018-02-16 13:24:58 -0800272 if (t->Write(p) != 0) {
273 D("%s: failed to enqueue packet, closing transport", t->serial);
274 t->Kick();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800275 }
276}
277
Yabin Cuif4b99282015-08-27 12:03:11 -0700278void kick_transport(atransport* t) {
Josh Gao1db71af2017-08-17 13:50:51 -0700279 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cui1f4ec192016-04-05 13:50:44 -0700280 // As kick_transport() can be called from threads without guarantee that t is valid,
281 // check if the transport is in transport_list first.
Josh Gaob122b172017-08-16 16:57:01 -0700282 //
283 // TODO(jmgao): WTF? Is this actually true?
Yabin Cui1f4ec192016-04-05 13:50:44 -0700284 if (std::find(transport_list.begin(), transport_list.end(), t) != transport_list.end()) {
Yabin Cui7f274902016-04-18 11:22:34 -0700285 t->Kick();
Yabin Cui1f4ec192016-04-05 13:50:44 -0700286 }
Yabin Cuif4b99282015-08-27 12:03:11 -0700287}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800288
289static int transport_registration_send = -1;
290static int transport_registration_recv = -1;
291static fdevent transport_registration_fde;
292
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800293#if ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800294
295/* this adds support required by the 'track-devices' service.
296 * this is used to send the content of "list_transport" to any
297 * number of client connections that want it through a single
298 * live TCP connection
299 */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800300struct device_tracker {
Josh Gao1290fbf2016-11-22 14:32:34 -0800301 asocket socket;
Josh Gaoe0361d12018-02-12 17:24:00 -0800302 bool update_needed = false;
303 bool long_output = false;
304 device_tracker* next = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800305};
306
307/* linked list of all device trackers */
Josh Gao1290fbf2016-11-22 14:32:34 -0800308static device_tracker* device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800309
Josh Gao1290fbf2016-11-22 14:32:34 -0800310static void device_tracker_remove(device_tracker* tracker) {
311 device_tracker** pnode = &device_tracker_list;
312 device_tracker* node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800313
Josh Gao1db71af2017-08-17 13:50:51 -0700314 std::lock_guard<std::recursive_mutex> lock(transport_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800315 while (node) {
316 if (node == tracker) {
317 *pnode = node->next;
318 break;
319 }
320 pnode = &node->next;
Josh Gao1290fbf2016-11-22 14:32:34 -0800321 node = *pnode;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800322 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800323}
324
Josh Gao1290fbf2016-11-22 14:32:34 -0800325static void device_tracker_close(asocket* socket) {
326 device_tracker* tracker = (device_tracker*)socket;
327 asocket* peer = socket->peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800328
Josh Gao1290fbf2016-11-22 14:32:34 -0800329 D("device tracker %p removed", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800330 if (peer) {
331 peer->peer = NULL;
332 peer->close(peer);
333 }
334 device_tracker_remove(tracker);
Josh Gaoe0361d12018-02-12 17:24:00 -0800335 delete tracker;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800336}
337
Josh Gao1ce99572018-03-07 16:52:28 -0800338static int device_tracker_enqueue(asocket* socket, apacket::payload_type) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800339 /* you can't read from a device tracker, close immediately */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800340 device_tracker_close(socket);
341 return -1;
342}
343
Elliott Hughese67f1f82015-04-30 17:32:03 -0700344static int device_tracker_send(device_tracker* tracker, const std::string& string) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700345 asocket* peer = tracker->socket.peer;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800346
Josh Gao1ce99572018-03-07 16:52:28 -0800347 apacket::payload_type data;
Josh Gao27cb7dc2018-02-01 13:17:50 -0800348 data.resize(4 + string.size());
349 char buf[5];
350 snprintf(buf, sizeof(buf), "%04x", static_cast<int>(string.size()));
351 memcpy(&data[0], buf, 4);
352 memcpy(&data[4], string.data(), string.size());
353 return peer->enqueue(peer, std::move(data));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800354}
355
Elliott Hughese67f1f82015-04-30 17:32:03 -0700356static void device_tracker_ready(asocket* socket) {
357 device_tracker* tracker = reinterpret_cast<device_tracker*>(socket);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800358
Elliott Hughese67f1f82015-04-30 17:32:03 -0700359 // We want to send the device list when the tracker connects
360 // for the first time, even if no update occurred.
Josh Gaob0c18022017-08-14 18:57:54 -0700361 if (tracker->update_needed) {
362 tracker->update_needed = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800363
Josh Gaob0c18022017-08-14 18:57:54 -0700364 std::string transports = list_transports(tracker->long_output);
Elliott Hughese67f1f82015-04-30 17:32:03 -0700365 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800366 }
367}
368
Josh Gaob0c18022017-08-14 18:57:54 -0700369asocket* create_device_tracker(bool long_output) {
Josh Gaoe0361d12018-02-12 17:24:00 -0800370 device_tracker* tracker = new device_tracker();
Elliott Hughesdc3b4592015-04-21 19:39:52 -0700371 if (tracker == nullptr) fatal("cannot allocate device tracker");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800372
Josh Gao1290fbf2016-11-22 14:32:34 -0800373 D("device tracker %p created", tracker);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800374
375 tracker->socket.enqueue = device_tracker_enqueue;
Josh Gao1290fbf2016-11-22 14:32:34 -0800376 tracker->socket.ready = device_tracker_ready;
377 tracker->socket.close = device_tracker_close;
Josh Gaob0c18022017-08-14 18:57:54 -0700378 tracker->update_needed = true;
379 tracker->long_output = long_output;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800380
Josh Gao1290fbf2016-11-22 14:32:34 -0800381 tracker->next = device_tracker_list;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800382 device_tracker_list = tracker;
383
384 return &tracker->socket;
385}
386
Josh Gaofd713e52017-05-03 22:37:10 -0700387// Check if all of the USB transports are connected.
388bool iterate_transports(std::function<bool(const atransport*)> fn) {
Josh Gao1db71af2017-08-17 13:50:51 -0700389 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaofd713e52017-05-03 22:37:10 -0700390 for (const auto& t : transport_list) {
391 if (!fn(t)) {
392 return false;
393 }
394 }
395 for (const auto& t : pending_list) {
396 if (!fn(t)) {
397 return false;
398 }
399 }
400 return true;
401}
402
Elliott Hughese67f1f82015-04-30 17:32:03 -0700403// Call this function each time the transport list has changed.
404void update_transports() {
Josh Gaofd713e52017-05-03 22:37:10 -0700405 update_transport_status();
406
407 // Notify `adb track-devices` clients.
Elliott Hughese67f1f82015-04-30 17:32:03 -0700408 std::string transports = list_transports(false);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800409
Elliott Hughese67f1f82015-04-30 17:32:03 -0700410 device_tracker* tracker = device_tracker_list;
411 while (tracker != nullptr) {
412 device_tracker* next = tracker->next;
413 // This may destroy the tracker if the connection is closed.
414 device_tracker_send(tracker, transports);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800415 tracker = next;
416 }
417}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700418
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800419#else
Elliott Hughese67f1f82015-04-30 17:32:03 -0700420
421void update_transports() {
422 // Nothing to do on the device side.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800423}
Elliott Hughese67f1f82015-04-30 17:32:03 -0700424
Josh Gao1290fbf2016-11-22 14:32:34 -0800425#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800426
Josh Gao1290fbf2016-11-22 14:32:34 -0800427struct tmsg {
428 atransport* transport;
429 int action;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800430};
431
Josh Gao1290fbf2016-11-22 14:32:34 -0800432static int transport_read_action(int fd, struct tmsg* m) {
433 char* p = (char*)m;
434 int len = sizeof(*m);
435 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800436
Josh Gao1290fbf2016-11-22 14:32:34 -0800437 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800438 r = adb_read(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800439 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800440 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800441 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800442 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700443 D("transport_read_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800444 return -1;
445 }
446 }
447 return 0;
448}
449
Josh Gao1290fbf2016-11-22 14:32:34 -0800450static int transport_write_action(int fd, struct tmsg* m) {
451 char* p = (char*)m;
452 int len = sizeof(*m);
453 int r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800454
Josh Gao1290fbf2016-11-22 14:32:34 -0800455 while (len > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800456 r = adb_write(fd, p, len);
Josh Gao1290fbf2016-11-22 14:32:34 -0800457 if (r > 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800458 len -= r;
Josh Gao1290fbf2016-11-22 14:32:34 -0800459 p += r;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800460 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700461 D("transport_write_action: on fd %d: %s", fd, strerror(errno));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800462 return -1;
463 }
464 }
465 return 0;
466}
467
Josh Gao0bbf69c2018-02-16 13:24:58 -0800468static void remove_transport(atransport*);
469
470static void transport_registration_func(int _fd, unsigned ev, void*) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800471 tmsg m;
Josh Gao1290fbf2016-11-22 14:32:34 -0800472 atransport* t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800473
Josh Gao1290fbf2016-11-22 14:32:34 -0800474 if (!(ev & FDE_READ)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800475 return;
476 }
477
Josh Gao1290fbf2016-11-22 14:32:34 -0800478 if (transport_read_action(_fd, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800479 fatal_errno("cannot read transport registration socket");
480 }
481
482 t = m.transport;
483
Dan Albert1792c232015-05-18 13:06:53 -0700484 if (m.action == 0) {
Josh Gao0bbf69c2018-02-16 13:24:58 -0800485 D("transport: %s deleting", t->serial);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800486
Josh Gao0cd3ae12016-09-21 12:37:10 -0700487 {
Josh Gao1db71af2017-08-17 13:50:51 -0700488 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700489 transport_list.remove(t);
490 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800491
Josh Gao1290fbf2016-11-22 14:32:34 -0800492 if (t->product) free(t->product);
493 if (t->serial) free(t->serial);
494 if (t->model) free(t->model);
495 if (t->device) free(t->device);
496 if (t->devpath) free(t->devpath);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800497
Dan Albertc7915a32015-05-18 16:46:31 -0700498 delete t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800499
500 update_transports();
501 return;
502 }
503
Mike Lockwood0927bf92009-08-08 12:37:44 -0400504 /* don't create transport threads for inaccessible devices */
Yabin Cuib5e11412017-03-10 16:01:01 -0800505 if (t->GetConnectionState() != kCsNoPerm) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800506 /* initial references are the two threads */
Josh Gao0bbf69c2018-02-16 13:24:58 -0800507 t->ref_count = 1;
508 t->connection->SetTransportName(t->serial_name());
509 t->connection->SetReadCallback([t](Connection*, std::unique_ptr<apacket> p) {
510 if (!check_header(p.get(), t)) {
511 D("%s: remote read: bad header", t->serial);
512 return false;
513 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800514
Josh Gao0bbf69c2018-02-16 13:24:58 -0800515 VLOG(TRANSPORT) << dump_packet(t->serial, "from remote", p.get());
516 apacket* packet = p.release();
Mike Lockwood0927bf92009-08-08 12:37:44 -0400517
Josh Gao0bbf69c2018-02-16 13:24:58 -0800518 // TODO: Does this need to run on the main thread?
519 fdevent_run_on_main_thread([packet, t]() { handle_packet(packet, t); });
520 return true;
521 });
522 t->connection->SetErrorCallback([t](Connection*, const std::string& error) {
523 D("%s: connection terminated: %s", t->serial, error.c_str());
524 fdevent_run_on_main_thread([t]() {
525 handle_offline(t);
526 transport_unref(t);
527 });
528 });
Mike Lockwood0927bf92009-08-08 12:37:44 -0400529
Josh Gao0bbf69c2018-02-16 13:24:58 -0800530 t->connection->Start();
531#if ADB_HOST
532 send_connect(t);
533#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800534 }
535
Josh Gao0cd3ae12016-09-21 12:37:10 -0700536 {
Josh Gao1db71af2017-08-17 13:50:51 -0700537 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700538 pending_list.remove(t);
539 transport_list.push_front(t);
540 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800541
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800542 update_transports();
543}
544
Josh Gao1290fbf2016-11-22 14:32:34 -0800545void init_transport_registration(void) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800546 int s[2];
547
Josh Gao1290fbf2016-11-22 14:32:34 -0800548 if (adb_socketpair(s)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800549 fatal_errno("cannot open transport registration socketpair");
550 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700551 D("socketpair: (%d,%d)", s[0], s[1]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800552
553 transport_registration_send = s[0];
554 transport_registration_recv = s[1];
555
Josh Gao1290fbf2016-11-22 14:32:34 -0800556 fdevent_install(&transport_registration_fde, transport_registration_recv,
557 transport_registration_func, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800558
559 fdevent_set(&transport_registration_fde, FDE_READ);
Josh Gao01b7bc42017-05-09 13:43:35 -0700560}
561
562void kick_all_transports() {
563 // To avoid only writing part of a packet to a transport after exit, kick all transports.
Josh Gao1db71af2017-08-17 13:50:51 -0700564 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao01b7bc42017-05-09 13:43:35 -0700565 for (auto t : transport_list) {
566 t->Kick();
567 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800568}
569
570/* the fdevent select pump is single threaded */
Josh Gao1290fbf2016-11-22 14:32:34 -0800571static void register_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800572 tmsg m;
573 m.transport = transport;
574 m.action = 1;
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700575 D("transport: %s registered", transport->serial);
Josh Gao1290fbf2016-11-22 14:32:34 -0800576 if (transport_write_action(transport_registration_send, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800577 fatal_errno("cannot write transport registration socket\n");
578 }
579}
580
Josh Gao1290fbf2016-11-22 14:32:34 -0800581static void remove_transport(atransport* transport) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800582 tmsg m;
583 m.transport = transport;
584 m.action = 0;
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700585 D("transport: %s removed", transport->serial);
Josh Gao1290fbf2016-11-22 14:32:34 -0800586 if (transport_write_action(transport_registration_send, &m)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800587 fatal_errno("cannot write transport registration socket\n");
588 }
589}
590
Yabin Cuif4b99282015-08-27 12:03:11 -0700591static void transport_unref(atransport* t) {
592 CHECK(t != nullptr);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700593
Josh Gaoe48ecce2017-09-13 13:40:57 -0700594 std::lock_guard<std::recursive_mutex> lock(transport_lock);
595 CHECK_GT(t->ref_count, 0u);
596 t->ref_count--;
597 if (t->ref_count == 0) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700598 D("transport: %s unref (kicking and closing)", t->serial);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800599 t->connection->Stop();
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -0400600 remove_transport(t);
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100601 } else {
Josh Gaoe48ecce2017-09-13 13:40:57 -0700602 D("transport: %s unref (count=%zu)", t->serial, t->ref_count);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -0400603 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800604}
605
Josh Gao1290fbf2016-11-22 14:32:34 -0800606static int qual_match(const char* to_test, const char* prefix, const char* qual,
607 bool sanitize_qual) {
608 if (!to_test || !*to_test) /* Return true if both the qual and to_test are null strings. */
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700609 return !qual || !*qual;
610
Josh Gao1290fbf2016-11-22 14:32:34 -0800611 if (!qual) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700612
613 if (prefix) {
614 while (*prefix) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800615 if (*prefix++ != *to_test++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700616 }
617 }
618
619 while (*qual) {
620 char ch = *qual++;
Josh Gao1290fbf2016-11-22 14:32:34 -0800621 if (sanitize_qual && !isalnum(ch)) ch = '_';
622 if (ch != *to_test++) return 0;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700623 }
624
625 /* Everything matched so far. Return true if *to_test is a NUL. */
626 return !*to_test;
627}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800628
Josh Gaob122b172017-08-16 16:57:01 -0700629atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
630 bool* is_ambiguous, std::string* error_out,
631 bool accept_any_state) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700632 atransport* result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800633
Josh Gaob122b172017-08-16 16:57:01 -0700634 if (transport_id != 0) {
635 *error_out =
636 android::base::StringPrintf("no device with transport id '%" PRIu64 "'", transport_id);
637 } else if (serial) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700638 *error_out = android::base::StringPrintf("device '%s' not found", serial);
639 } else if (type == kTransportLocal) {
640 *error_out = "no emulators found";
641 } else if (type == kTransportAny) {
642 *error_out = "no devices/emulators found";
643 } else {
644 *error_out = "no devices found";
645 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800646
Josh Gao1db71af2017-08-17 13:50:51 -0700647 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes8d28e192015-10-07 14:55:10 -0700648 for (const auto& t : transport_list) {
Yabin Cuib5e11412017-03-10 16:01:01 -0800649 if (t->GetConnectionState() == kCsNoPerm) {
David Purselld2acbd12015-12-02 15:14:31 -0800650 *error_out = UsbNoPermissionsLongHelpText();
Mike Lockwood37d31112009-08-08 13:53:16 -0400651 continue;
652 }
Mike Lockwood0927bf92009-08-08 12:37:44 -0400653
Josh Gaob122b172017-08-16 16:57:01 -0700654 if (transport_id) {
655 if (t->id == transport_id) {
656 result = t;
657 break;
658 }
659 } else if (serial) {
David Pursell3f902aa2016-03-01 08:58:26 -0800660 if (t->MatchesTarget(serial)) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700661 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700662 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700663 if (is_ambiguous) *is_ambiguous = true;
664 result = nullptr;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700665 break;
666 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800667 result = t;
Scott Andersone109d262012-04-20 11:21:14 -0700668 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800669 } else {
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700670 if (type == kTransportUsb && t->type == kTransportUsb) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800671 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700672 *error_out = "more than one device";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700673 if (is_ambiguous) *is_ambiguous = true;
674 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800675 break;
676 }
677 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700678 } else if (type == kTransportLocal && t->type == kTransportLocal) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800679 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700680 *error_out = "more than one emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700681 if (is_ambiguous) *is_ambiguous = true;
682 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800683 break;
684 }
685 result = t;
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700686 } else if (type == kTransportAny) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800687 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700688 *error_out = "more than one device/emulator";
Elliott Hughes8d28e192015-10-07 14:55:10 -0700689 if (is_ambiguous) *is_ambiguous = true;
690 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800691 break;
692 }
693 result = t;
694 }
695 }
696 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700697 lock.unlock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800698
Elliott Hughes8d28e192015-10-07 14:55:10 -0700699 // Don't return unauthorized devices; the caller can't do anything with them.
Yabin Cuib5e11412017-03-10 16:01:01 -0800700 if (result && result->GetConnectionState() == kCsUnauthorized && !accept_any_state) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700701 *error_out = "device unauthorized.\n";
702 char* ADB_VENDOR_KEYS = getenv("ADB_VENDOR_KEYS");
703 *error_out += "This adb server's $ADB_VENDOR_KEYS is ";
704 *error_out += ADB_VENDOR_KEYS ? ADB_VENDOR_KEYS : "not set";
705 *error_out += "\n";
706 *error_out += "Try 'adb kill-server' if that seems wrong.\n";
707 *error_out += "Otherwise check for a confirmation dialog on your device.";
708 result = nullptr;
709 }
Benoit Goby77e8e582013-01-15 12:36:47 -0800710
Elliott Hughes8d28e192015-10-07 14:55:10 -0700711 // Don't return offline devices; the caller can't do anything with them.
Yabin Cuib5e11412017-03-10 16:01:01 -0800712 if (result && result->GetConnectionState() == kCsOffline && !accept_any_state) {
Elliott Hughes8d28e192015-10-07 14:55:10 -0700713 *error_out = "device offline";
714 result = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800715 }
716
717 if (result) {
Elliott Hughese2d36772015-06-23 13:00:32 -0700718 *error_out = "success";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800719 }
720
721 return result;
722}
723
Yabin Cuib5e11412017-03-10 16:01:01 -0800724int atransport::Write(apacket* p) {
Josh Gao0bbf69c2018-02-16 13:24:58 -0800725 return this->connection->Write(std::unique_ptr<apacket>(p)) ? 0 : -1;
Yabin Cuib5e11412017-03-10 16:01:01 -0800726}
727
Yabin Cui7f274902016-04-18 11:22:34 -0700728void atransport::Kick() {
729 if (!kicked_) {
Josh Gaob800d882018-01-28 20:32:46 -0800730 D("kicking transport %s", this->serial);
Yabin Cui7f274902016-04-18 11:22:34 -0700731 kicked_ = true;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800732 this->connection->Stop();
Yabin Cui7f274902016-04-18 11:22:34 -0700733 }
734}
735
Yabin Cuib5e11412017-03-10 16:01:01 -0800736ConnectionState atransport::GetConnectionState() const {
737 return connection_state_;
738}
739
740void atransport::SetConnectionState(ConnectionState state) {
741 check_main_thread();
742 connection_state_ = state;
743}
744
Josh Gaoffbd3362018-02-28 14:44:23 -0800745std::string atransport::connection_state_name() const {
Yabin Cuib5e11412017-03-10 16:01:01 -0800746 ConnectionState state = GetConnectionState();
747 switch (state) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800748 case kCsOffline:
749 return "offline";
750 case kCsBootloader:
751 return "bootloader";
752 case kCsDevice:
753 return "device";
754 case kCsHost:
755 return "host";
756 case kCsRecovery:
757 return "recovery";
758 case kCsNoPerm:
759 return UsbNoPermissionsShortHelpText();
760 case kCsSideload:
761 return "sideload";
762 case kCsUnauthorized:
763 return "unauthorized";
764 default:
765 return "unknown";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800766 }
767}
768
Tamas Berghammer3d2904c2015-07-13 19:12:28 +0100769void atransport::update_version(int version, size_t payload) {
770 protocol_version = std::min(version, A_VERSION);
771 max_payload = std::min(payload, MAX_PAYLOAD);
772}
773
774int atransport::get_protocol_version() const {
775 return protocol_version;
776}
777
778size_t atransport::get_max_payload() const {
779 return max_payload;
780}
781
David Pursell4e2fd362015-09-22 10:43:08 -0700782namespace {
David Pursell0955c662015-08-31 10:42:13 -0700783
David Pursell4e2fd362015-09-22 10:43:08 -0700784constexpr char kFeatureStringDelimiter = ',';
785
786} // namespace
Dan Albert1792c232015-05-18 13:06:53 -0700787
788const FeatureSet& supported_features() {
David Pursell4e2fd362015-09-22 10:43:08 -0700789 // Local static allocation to avoid global non-POD variables.
790 static const FeatureSet* features = new FeatureSet{
Josh Gao1290fbf2016-11-22 14:32:34 -0800791 kFeatureShell2, kFeatureCmd, kFeatureStat2,
David Pursellbbe3d212015-09-25 08:37:13 -0700792 // Increment ADB_SERVER_VERSION whenever the feature list changes to
793 // make sure that the adb client and server features stay in sync
794 // (http://b/24370690).
David Pursell4e2fd362015-09-22 10:43:08 -0700795 };
796
797 return *features;
798}
799
800std::string FeatureSetToString(const FeatureSet& features) {
801 return android::base::Join(features, kFeatureStringDelimiter);
802}
803
804FeatureSet StringToFeatureSet(const std::string& features_string) {
David Purselld2b588e2015-09-25 13:04:21 -0700805 if (features_string.empty()) {
806 return FeatureSet();
807 }
808
Josh Gao1290fbf2016-11-22 14:32:34 -0800809 auto names = android::base::Split(features_string, {kFeatureStringDelimiter});
David Pursell4e2fd362015-09-22 10:43:08 -0700810 return FeatureSet(names.begin(), names.end());
Dan Albert1792c232015-05-18 13:06:53 -0700811}
812
David Pursell70ef7b42015-09-30 13:35:42 -0700813bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature) {
Josh Gao1290fbf2016-11-22 14:32:34 -0800814 return feature_set.count(feature) > 0 && supported_features().count(feature) > 0;
David Pursell70ef7b42015-09-30 13:35:42 -0700815}
816
Dan Albert1792c232015-05-18 13:06:53 -0700817bool atransport::has_feature(const std::string& feature) const {
818 return features_.count(feature) > 0;
819}
820
David Pursell4e2fd362015-09-22 10:43:08 -0700821void atransport::SetFeatures(const std::string& features_string) {
822 features_ = StringToFeatureSet(features_string);
Dan Albert1792c232015-05-18 13:06:53 -0700823}
824
Yabin Cuib3298242015-08-28 15:09:44 -0700825void atransport::AddDisconnect(adisconnect* disconnect) {
826 disconnects_.push_back(disconnect);
827}
828
829void atransport::RemoveDisconnect(adisconnect* disconnect) {
830 disconnects_.remove(disconnect);
831}
832
833void atransport::RunDisconnects() {
Elliott Hughes65fe2512015-10-07 15:59:35 -0700834 for (const auto& disconnect : disconnects_) {
Yabin Cuib3298242015-08-28 15:09:44 -0700835 disconnect->func(disconnect->opaque, this);
836 }
837 disconnects_.clear();
838}
839
David Pursell3f902aa2016-03-01 08:58:26 -0800840bool atransport::MatchesTarget(const std::string& target) const {
841 if (serial) {
842 if (target == serial) {
843 return true;
844 } else if (type == kTransportLocal) {
845 // Local transports can match [tcp:|udp:]<hostname>[:port].
846 const char* local_target_ptr = target.c_str();
847
848 // For fastboot compatibility, ignore protocol prefixes.
849 if (android::base::StartsWith(target, "tcp:") ||
Josh Gao1290fbf2016-11-22 14:32:34 -0800850 android::base::StartsWith(target, "udp:")) {
David Pursell3f902aa2016-03-01 08:58:26 -0800851 local_target_ptr += 4;
852 }
853
854 // Parse our |serial| and the given |target| to check if the hostnames and ports match.
855 std::string serial_host, error;
856 int serial_port = -1;
Josh Gao1290fbf2016-11-22 14:32:34 -0800857 if (android::base::ParseNetAddress(serial, &serial_host, &serial_port, nullptr, &error)) {
David Pursell3f902aa2016-03-01 08:58:26 -0800858 // |target| may omit the port to default to ours.
859 std::string target_host;
860 int target_port = serial_port;
861 if (android::base::ParseNetAddress(local_target_ptr, &target_host, &target_port,
862 nullptr, &error) &&
Josh Gao1290fbf2016-11-22 14:32:34 -0800863 serial_host == target_host && serial_port == target_port) {
David Pursell3f902aa2016-03-01 08:58:26 -0800864 return true;
865 }
866 }
867 }
868 }
869
870 return (devpath && target == devpath) ||
871 qual_match(target.c_str(), "product:", product, false) ||
872 qual_match(target.c_str(), "model:", model, true) ||
873 qual_match(target.c_str(), "device:", device, false);
874}
875
Elliott Hughese67f1f82015-04-30 17:32:03 -0700876#if ADB_HOST
877
Josh Gaob122b172017-08-16 16:57:01 -0700878// We use newline as our delimiter, make sure to never output it.
879static std::string sanitize(std::string str, bool alphanumeric) {
880 auto pred = alphanumeric ? [](const char c) { return !isalnum(c); }
881 : [](const char c) { return c == '\n'; };
882 std::replace_if(str.begin(), str.end(), pred, '_');
883 return str;
884}
885
Josh Gao1290fbf2016-11-22 14:32:34 -0800886static void append_transport_info(std::string* result, const char* key, const char* value,
Josh Gaob122b172017-08-16 16:57:01 -0700887 bool alphanumeric) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700888 if (value == nullptr || *value == '\0') {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700889 return;
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700890 }
891
Elliott Hughese67f1f82015-04-30 17:32:03 -0700892 *result += ' ';
893 *result += key;
Josh Gaob122b172017-08-16 16:57:01 -0700894 *result += sanitize(value, alphanumeric);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700895}
896
Josh Gao1290fbf2016-11-22 14:32:34 -0800897static void append_transport(const atransport* t, std::string* result, bool long_listing) {
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700898 const char* serial = t->serial;
Elliott Hughese67f1f82015-04-30 17:32:03 -0700899 if (!serial || !serial[0]) {
Dan Albertd99d9022015-05-06 16:48:52 -0700900 serial = "(no serial number)";
Elliott Hughese67f1f82015-04-30 17:32:03 -0700901 }
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700902
903 if (!long_listing) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700904 *result += serial;
905 *result += '\t';
906 *result += t->connection_state_name();
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700907 } else {
Josh Gao1290fbf2016-11-22 14:32:34 -0800908 android::base::StringAppendF(result, "%-22s %s", serial, t->connection_state_name().c_str());
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700909
Elliott Hughese67f1f82015-04-30 17:32:03 -0700910 append_transport_info(result, "", t->devpath, false);
911 append_transport_info(result, "product:", t->product, false);
912 append_transport_info(result, "model:", t->model, true);
913 append_transport_info(result, "device:", t->device, false);
Josh Gaob122b172017-08-16 16:57:01 -0700914
915 // Put id at the end, so that anyone parsing the output here can always find it by scanning
916 // backwards from newlines, even with hypothetical devices named 'transport_id:1'.
917 *result += " transport_id:";
918 *result += std::to_string(t->id);
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700919 }
Elliott Hughese67f1f82015-04-30 17:32:03 -0700920 *result += '\n';
Scott Anderson2ca3e6b2012-05-30 18:11:27 -0700921}
922
Elliott Hughese67f1f82015-04-30 17:32:03 -0700923std::string list_transports(bool long_listing) {
Josh Gao1db71af2017-08-17 13:50:51 -0700924 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Artem Iglikov04398a92017-12-17 10:56:07 +0000925
926 auto sorted_transport_list = transport_list;
927 sorted_transport_list.sort([](atransport*& x, atransport*& y) {
928 if (x->type != y->type) {
929 return x->type < y->type;
930 }
931 return strcmp(x->serial, y->serial) < 0;
932 });
933
934 std::string result;
935 for (const auto& t : sorted_transport_list) {
Elliott Hughese67f1f82015-04-30 17:32:03 -0700936 append_transport(t, &result, long_listing);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800937 }
Elliott Hughese67f1f82015-04-30 17:32:03 -0700938 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800939}
940
Josh Gao22d2b3e2016-10-27 14:01:08 -0700941void close_usb_devices(std::function<bool(const atransport*)> predicate) {
Josh Gao1db71af2017-08-17 13:50:51 -0700942 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao22d2b3e2016-10-27 14:01:08 -0700943 for (auto& t : transport_list) {
944 if (predicate(t)) {
945 t->Kick();
946 }
947 }
948}
949
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800950/* hack for osx */
Dan Albertc7915a32015-05-18 16:46:31 -0700951void close_usb_devices() {
Josh Gao22d2b3e2016-10-27 14:01:08 -0700952 close_usb_devices([](const atransport*) { return true; });
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800953}
Josh Gao1290fbf2016-11-22 14:32:34 -0800954#endif // ADB_HOST
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800955
Josh Gao1290fbf2016-11-22 14:32:34 -0800956int register_socket_transport(int s, const char* serial, int port, int local) {
Dan Albertc7915a32015-05-18 16:46:31 -0700957 atransport* t = new atransport();
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100958
959 if (!serial) {
Dan Albertc7915a32015-05-18 16:46:31 -0700960 char buf[32];
961 snprintf(buf, sizeof(buf), "T-%p", t);
962 serial = buf;
David 'Digit' Turner730ff3b2011-01-06 14:11:07 +0100963 }
Dan Albertc7915a32015-05-18 16:46:31 -0700964
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700965 D("transport: %s init'ing for socket %d, on port %d", serial, s, port);
Benoit Goby1c45ee92013-03-29 18:22:36 -0700966 if (init_socket_transport(t, s, port, local) < 0) {
Dan Albertc7915a32015-05-18 16:46:31 -0700967 delete t;
Benoit Goby1c45ee92013-03-29 18:22:36 -0700968 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800969 }
Benoit Goby1c45ee92013-03-29 18:22:36 -0700970
Josh Gao1db71af2017-08-17 13:50:51 -0700971 std::unique_lock<std::recursive_mutex> lock(transport_lock);
Elliott Hughes65fe2512015-10-07 15:59:35 -0700972 for (const auto& transport : pending_list) {
Dan Albertc7915a32015-05-18 16:46:31 -0700973 if (transport->serial && strcmp(serial, transport->serial) == 0) {
Yabin Cuib74c6492016-04-29 16:53:52 -0700974 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -0800975 << " is already in pending_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -0700976 delete t;
Benoit Goby1c45ee92013-03-29 18:22:36 -0700977 return -1;
978 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800979 }
Benoit Goby1c45ee92013-03-29 18:22:36 -0700980
Elliott Hughes65fe2512015-10-07 15:59:35 -0700981 for (const auto& transport : transport_list) {
Dan Albertc7915a32015-05-18 16:46:31 -0700982 if (transport->serial && strcmp(serial, transport->serial) == 0) {
Yabin Cuib74c6492016-04-29 16:53:52 -0700983 VLOG(TRANSPORT) << "socket transport " << transport->serial
Josh Gao1290fbf2016-11-22 14:32:34 -0800984 << " is already in transport_list and fails to register";
Dan Albertc7915a32015-05-18 16:46:31 -0700985 delete t;
Benoit Goby1c45ee92013-03-29 18:22:36 -0700986 return -1;
987 }
988 }
989
Dan Albertc7915a32015-05-18 16:46:31 -0700990 pending_list.push_front(t);
Benoit Goby1c45ee92013-03-29 18:22:36 -0700991 t->serial = strdup(serial);
Josh Gao0cd3ae12016-09-21 12:37:10 -0700992
993 lock.unlock();
Benoit Goby1c45ee92013-03-29 18:22:36 -0700994
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800995 register_transport(t);
Benoit Goby1c45ee92013-03-29 18:22:36 -0700996 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800997}
998
Mike Lockwood8cf0d592009-10-11 23:04:18 -0400999#if ADB_HOST
Josh Gao1290fbf2016-11-22 14:32:34 -08001000atransport* find_transport(const char* serial) {
Dan Albertc7915a32015-05-18 16:46:31 -07001001 atransport* result = nullptr;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001002
Josh Gao1db71af2017-08-17 13:50:51 -07001003 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001004 for (auto& t : transport_list) {
Dan Albertc7915a32015-05-18 16:46:31 -07001005 if (t->serial && strcmp(serial, t->serial) == 0) {
1006 result = t;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001007 break;
1008 }
Dan Albertc7915a32015-05-18 16:46:31 -07001009 }
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001010
Dan Albertc7915a32015-05-18 16:46:31 -07001011 return result;
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001012}
1013
Yabin Cuif4b99282015-08-27 12:03:11 -07001014void kick_all_tcp_devices() {
Josh Gao1db71af2017-08-17 13:50:51 -07001015 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Yabin Cuif4b99282015-08-27 12:03:11 -07001016 for (auto& t : transport_list) {
Yabin Cuib74c6492016-04-29 16:53:52 -07001017 if (t->IsTcpDevice()) {
Yabin Cuid6ab3c22015-08-31 11:50:24 -07001018 // Kicking breaks the read_transport thread of this transport out of any read, then
1019 // the read_transport thread will notify the main thread to make this transport
1020 // offline. Then the main thread will notify the write_transport thread to exit.
Yabin Cuif4b99282015-08-27 12:03:11 -07001021 // Finally, this transport will be closed and freed in the main thread.
Yabin Cui7f274902016-04-18 11:22:34 -07001022 t->Kick();
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001023 }
Dan Albertc7915a32015-05-18 16:46:31 -07001024 }
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001025}
1026
Mike Lockwood8cf0d592009-10-11 23:04:18 -04001027#endif
1028
Josh Gao1290fbf2016-11-22 14:32:34 -08001029void register_usb_transport(usb_handle* usb, const char* serial, const char* devpath,
1030 unsigned writeable) {
Yabin Cuib5e11412017-03-10 16:01:01 -08001031 atransport* t = new atransport((writeable ? kCsOffline : kCsNoPerm));
Dan Albertc7915a32015-05-18 16:46:31 -07001032
Josh Gao1290fbf2016-11-22 14:32:34 -08001033 D("transport: %p init'ing for usb_handle %p (sn='%s')", t, usb, serial ? serial : "");
Yabin Cuib5e11412017-03-10 16:01:01 -08001034 init_usb_transport(t, usb);
Josh Gao1290fbf2016-11-22 14:32:34 -08001035 if (serial) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001036 t->serial = strdup(serial);
1037 }
Dan Albertc7915a32015-05-18 16:46:31 -07001038
1039 if (devpath) {
Scott Andersone109d262012-04-20 11:21:14 -07001040 t->devpath = strdup(devpath);
1041 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001042
Josh Gao0cd3ae12016-09-21 12:37:10 -07001043 {
Josh Gao1db71af2017-08-17 13:50:51 -07001044 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gao0cd3ae12016-09-21 12:37:10 -07001045 pending_list.push_front(t);
1046 }
Benoit Goby1c45ee92013-03-29 18:22:36 -07001047
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001048 register_transport(t);
1049}
1050
Dan Albertdcd78a12015-05-18 16:43:57 -07001051// This should only be used for transports with connection_state == kCsNoPerm.
Josh Gao1290fbf2016-11-22 14:32:34 -08001052void unregister_usb_transport(usb_handle* usb) {
Josh Gao1db71af2017-08-17 13:50:51 -07001053 std::lock_guard<std::recursive_mutex> lock(transport_lock);
Josh Gaob800d882018-01-28 20:32:46 -08001054 transport_list.remove_if([usb](atransport* t) {
1055 if (auto connection = dynamic_cast<UsbConnection*>(t->connection.get())) {
1056 return connection->handle_ == usb && t->GetConnectionState() == kCsNoPerm;
1057 }
1058 return false;
1059 });
Mike Lockwood0927bf92009-08-08 12:37:44 -04001060}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001061
Josh Gao36dadca2017-05-16 15:02:45 -07001062bool check_header(apacket* p, atransport* t) {
Josh Gao1290fbf2016-11-22 14:32:34 -08001063 if (p->msg.magic != (p->msg.command ^ 0xffffffff)) {
Yabin Cuib5e11412017-03-10 16:01:01 -08001064 VLOG(RWX) << "check_header(): invalid magic command = " << std::hex << p->msg.command
1065 << ", magic = " << p->msg.magic;
Josh Gao36dadca2017-05-16 15:02:45 -07001066 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001067 }
1068
Josh Gao1290fbf2016-11-22 14:32:34 -08001069 if (p->msg.data_length > t->get_max_payload()) {
1070 VLOG(RWX) << "check_header(): " << p->msg.data_length
1071 << " atransport::max_payload = " << t->get_max_payload();
Josh Gao36dadca2017-05-16 15:02:45 -07001072 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001073 }
1074
Josh Gao36dadca2017-05-16 15:02:45 -07001075 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001076}
1077
Josh Gao3bd28792016-10-05 19:02:29 -07001078#if ADB_HOST
Josh Gao2e671202016-08-18 22:00:12 -07001079std::shared_ptr<RSA> atransport::NextKey() {
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001080 if (keys_.empty()) keys_ = adb_auth_get_private_keys();
1081
Josh Gao2e671202016-08-18 22:00:12 -07001082 std::shared_ptr<RSA> result = keys_[0];
Elliott Hughes0aeb5052016-06-29 17:42:01 -07001083 keys_.pop_front();
1084 return result;
1085}
Josh Gao3bd28792016-10-05 19:02:29 -07001086#endif