1 /*
2 * Copyright (C) 2016 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
17 #include "sysdeps.h"
18
19 #include "client/usb.h"
20
21 #include <stdint.h>
22 #include <stdlib.h>
23
24 #if defined(__linux__)
25 #include <sys/inotify.h>
26 #include <unistd.h>
27 #endif
28
29 #include <atomic>
30 #include <chrono>
31 #include <condition_variable>
32 #include <memory>
33 #include <mutex>
34 #include <string>
35 #include <thread>
36 #include <unordered_map>
37 #include <vector>
38
39 #include <libusb/libusb.h>
40
41 #include <android-base/file.h>
42 #include <android-base/logging.h>
43 #include <android-base/stringprintf.h>
44 #include <android-base/strings.h>
45 #include <android-base/thread_annotations.h>
46
47 #include "adb.h"
48 #include "adb_utils.h"
49 #include "fdevent/fdevent.h"
50 #include "transfer_id.h"
51 #include "transport.h"
52
53 using namespace std::chrono_literals;
54
55 using android::base::ScopedLockAssertion;
56 using android::base::StringPrintf;
57
58 #define LOG_ERR(out, fmt, ...) \
59 do { \
60 std::string __err = android::base::StringPrintf(fmt, ##__VA_ARGS__); \
61 LOG(ERROR) << __err; \
62 *out = std::move(__err); \
63 } while (0)
64
65 // RAII wrappers for libusb.
66 struct ConfigDescriptorDeleter {
operator ()ConfigDescriptorDeleter67 void operator()(libusb_config_descriptor* desc) { libusb_free_config_descriptor(desc); }
68 };
69
70 using unique_config_descriptor = std::unique_ptr<libusb_config_descriptor, ConfigDescriptorDeleter>;
71
72 struct DeviceDeleter {
operator ()DeviceDeleter73 void operator()(libusb_device* d) { libusb_unref_device(d); }
74 };
75
76 using unique_device = std::unique_ptr<libusb_device, DeviceDeleter>;
77
78 struct DeviceHandleDeleter {
operator ()DeviceHandleDeleter79 void operator()(libusb_device_handle* h) { libusb_close(h); }
80 };
81
82 using unique_device_handle = std::unique_ptr<libusb_device_handle, DeviceHandleDeleter>;
83
84 static void process_device(libusb_device* device_raw);
85
get_device_address(libusb_device * device)86 static std::string get_device_address(libusb_device* device) {
87 uint8_t ports[7];
88 int port_count = libusb_get_port_numbers(device, ports, 7);
89 if (port_count < 0) return "";
90
91 std::string address = StringPrintf("%d-%d", libusb_get_bus_number(device), ports[0]);
92 for (int port = 1; port < port_count; ++port) {
93 address += StringPrintf(".%d", ports[port]);
94 }
95
96 return address;
97 }
98
99 #if defined(__linux__)
get_device_serial_path(libusb_device * device)100 static std::string get_device_serial_path(libusb_device* device) {
101 std::string address = get_device_address(device);
102 std::string path = StringPrintf("/sys/bus/usb/devices/%s/serial", address.c_str());
103 return path;
104 }
105 #endif
106
endpoint_is_output(uint8_t endpoint)107 static bool endpoint_is_output(uint8_t endpoint) {
108 return (endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT;
109 }
110
should_perform_zero_transfer(size_t write_length,uint16_t zero_mask)111 static bool should_perform_zero_transfer(size_t write_length, uint16_t zero_mask) {
112 return write_length != 0 && zero_mask != 0 && (write_length & zero_mask) == 0;
113 }
114
115 struct LibusbConnection : public Connection {
116 struct ReadBlock {
117 LibusbConnection* self = nullptr;
118 libusb_transfer* transfer = nullptr;
119 Block block;
120 bool active = false;
121 };
122
123 struct WriteBlock {
124 LibusbConnection* self;
125 libusb_transfer* transfer;
126 Block block;
127 TransferId id;
128 };
129
LibusbConnectionLibusbConnection130 explicit LibusbConnection(unique_device device)
131 : device_(std::move(device)), device_address_(get_device_address(device_.get())) {}
132
~LibusbConnectionLibusbConnection133 ~LibusbConnection() { Stop(); }
134
HandlePacketLibusbConnection135 void HandlePacket(amessage& msg, std::optional<Block> payload) {
136 auto packet = std::make_unique<apacket>();
137 packet->msg = msg;
138 if (payload) {
139 packet->payload = std::move(*payload);
140 }
141 transport_->HandleRead(std::move(packet));
142 }
143
CleanupLibusbConnection144 void Cleanup(ReadBlock* read_block) REQUIRES(read_mutex_) {
145 libusb_free_transfer(read_block->transfer);
146 read_block->active = false;
147 read_block->transfer = nullptr;
148 if (terminated_) {
149 destruction_cv_.notify_one();
150 }
151 }
152
MaybeCleanupLibusbConnection153 bool MaybeCleanup(ReadBlock* read_block) REQUIRES(read_mutex_) {
154 CHECK(read_block);
155 CHECK(read_block->transfer);
156
157 if (terminated_) {
158 Cleanup(read_block);
159 return true;
160 }
161
162 return false;
163 }
164
header_read_cbLibusbConnection165 static void LIBUSB_CALL header_read_cb(libusb_transfer* transfer) {
166 auto read_block = static_cast<ReadBlock*>(transfer->user_data);
167 auto self = read_block->self;
168
169 std::lock_guard<std::mutex> lock(self->read_mutex_);
170 CHECK_EQ(read_block, &self->header_read_);
171 if (self->MaybeCleanup(read_block)) {
172 return;
173 }
174
175 if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
176 std::string msg =
177 StringPrintf("usb read failed: '%s'", libusb_error_name(transfer->status));
178 LOG(ERROR) << msg;
179 if (!self->detached_) {
180 self->OnError(msg);
181 }
182 self->Cleanup(read_block);
183 return;
184 }
185
186 if (transfer->actual_length != sizeof(amessage)) {
187 std::string msg = StringPrintf("usb read: invalid length for header: %d",
188 transfer->actual_length);
189 LOG(ERROR) << msg;
190 self->OnError(msg);
191 self->Cleanup(read_block);
192 return;
193 }
194
195 CHECK(!self->incoming_header_);
196 amessage& amsg = self->incoming_header_.emplace();
197 memcpy(&amsg, transfer->buffer, sizeof(amsg));
198
199 if (amsg.data_length > MAX_PAYLOAD) {
200 std::string msg =
201 StringPrintf("usb read: payload length too long: %d", amsg.data_length);
202 LOG(ERROR) << msg;
203 self->OnError(msg);
204 self->Cleanup(&self->header_read_);
205 return;
206 } else if (amsg.data_length == 0) {
207 self->HandlePacket(amsg, std::nullopt);
208 self->incoming_header_.reset();
209 self->SubmitRead(read_block, sizeof(amessage));
210 } else {
211 read_block->active = false;
212 self->SubmitRead(&self->payload_read_, amsg.data_length);
213 }
214 }
215
payload_read_cbLibusbConnection216 static void LIBUSB_CALL payload_read_cb(libusb_transfer* transfer) {
217 auto read_block = static_cast<ReadBlock*>(transfer->user_data);
218 auto self = read_block->self;
219 std::lock_guard<std::mutex> lock(self->read_mutex_);
220
221 if (self->MaybeCleanup(&self->payload_read_)) {
222 return;
223 }
224
225 if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
226 std::string msg =
227 StringPrintf("usb read failed: '%s'", libusb_error_name(transfer->status));
228 LOG(ERROR) << msg;
229 if (!self->detached_) {
230 self->OnError(msg);
231 }
232 self->Cleanup(&self->payload_read_);
233 return;
234 }
235
236 if (transfer->actual_length != transfer->length) {
237 std::string msg =
238 StringPrintf("usb read: unexpected length for payload: wanted %d, got %d",
239 transfer->length, transfer->actual_length);
240 LOG(ERROR) << msg;
241 self->OnError(msg);
242 self->Cleanup(&self->payload_read_);
243 return;
244 }
245
246 CHECK(self->incoming_header_.has_value());
247 self->HandlePacket(*self->incoming_header_, std::move(read_block->block));
248 self->incoming_header_.reset();
249
250 read_block->active = false;
251 self->SubmitRead(&self->header_read_, sizeof(amessage));
252 }
253
write_cbLibusbConnection254 static void LIBUSB_CALL write_cb(libusb_transfer* transfer) {
255 auto write_block = static_cast<WriteBlock*>(transfer->user_data);
256 auto self = write_block->self;
257
258 bool succeeded = transfer->status == LIBUSB_TRANSFER_COMPLETED;
259
260 {
261 std::lock_guard<std::mutex> lock(self->write_mutex_);
262 libusb_free_transfer(transfer);
263 self->writes_.erase(write_block->id);
264
265 if (self->terminated_ && self->writes_.empty()) {
266 self->destruction_cv_.notify_one();
267 }
268 }
269
270 if (!succeeded && !self->detached_) {
271 self->OnError("libusb write failed");
272 }
273 }
274
DoTlsHandshakeLibusbConnection275 bool DoTlsHandshake(RSA*, std::string*) final {
276 LOG(FATAL) << "tls not supported";
277 return false;
278 }
279
CreateReadLibusbConnection280 void CreateRead(ReadBlock* read, bool header) {
281 read->self = this;
282 read->transfer = libusb_alloc_transfer(0);
283 if (!read->transfer) {
284 LOG(FATAL) << "failed to allocate libusb_transfer for read";
285 }
286 libusb_fill_bulk_transfer(read->transfer, device_handle_.get(), read_endpoint_, nullptr, 0,
287 header ? header_read_cb : payload_read_cb, read, 0);
288 }
289
SubmitReadLibusbConnection290 void SubmitRead(ReadBlock* read, size_t length) {
291 read->block.resize(length);
292 read->transfer->buffer = reinterpret_cast<unsigned char*>(read->block.data());
293 read->transfer->length = length;
294 read->active = true;
295 int rc = libusb_submit_transfer(read->transfer);
296 if (rc != 0) {
297 LOG(ERROR) << "libusb_submit_transfer failed: " << libusb_strerror(rc);
298 }
299 }
300
SubmitWriteLibusbConnection301 void SubmitWrite(Block&& block) REQUIRES(write_mutex_) {
302 // TODO: Reuse write blocks.
303 auto write = std::make_unique<WriteBlock>();
304
305 write->self = this;
306 write->id = TransferId::write(next_write_id_++);
307 write->block = std::move(block);
308 write->transfer = libusb_alloc_transfer(0);
309 if (!write->transfer) {
310 LOG(FATAL) << "failed to allocate libusb_transfer for write";
311 }
312
313 libusb_fill_bulk_transfer(write->transfer, device_handle_.get(), write_endpoint_,
314 reinterpret_cast<unsigned char*>(write->block.data()),
315 write->block.size(), &write_cb, write.get(), 0);
316 int rc = libusb_submit_transfer(write->transfer);
317 if (rc == 0) {
318 writes_[write->id] = std::move(write);
319 } else {
320 LOG(ERROR) << "libusb_submit_transfer failed: " << libusb_strerror(rc);
321 libusb_free_transfer(write->transfer);
322 }
323 }
324
WriteLibusbConnection325 bool Write(std::unique_ptr<apacket> packet) final {
326 VLOG(USB) << "USB write: " << dump_header(&packet->msg);
327 Block header;
328 header.resize(sizeof(packet->msg));
329 memcpy(header.data(), &packet->msg, sizeof(packet->msg));
330
331 std::lock_guard<std::mutex> lock(write_mutex_);
332 if (terminated_) {
333 return false;
334 }
335
336 if (detached_) {
337 return true;
338 }
339
340 SubmitWrite(std::move(header));
341 if (!packet->payload.empty()) {
342 size_t payload_length = packet->payload.size();
343 SubmitWrite(std::move(packet->payload));
344
345 // If the payload is a multiple of the endpoint packet size, we
346 // need an explicit zero-sized transfer.
347 if (should_perform_zero_transfer(payload_length, zero_mask_)) {
348 VLOG(USB) << "submitting zero transfer for payload length " << payload_length;
349 Block empty;
350 SubmitWrite(std::move(empty));
351 }
352 }
353
354 return true;
355 }
356
GetDeviceDescriptorLibusbConnection357 std::optional<libusb_device_descriptor> GetDeviceDescriptor() {
358 libusb_device_descriptor device_desc;
359 int rc = libusb_get_device_descriptor(device_.get(), &device_desc);
360 if (rc != 0) {
361 LOG(WARNING) << "failed to get device descriptor for device at " << device_address_
362 << ": " << libusb_error_name(rc);
363 return {};
364 }
365 return device_desc;
366 }
367
FindInterfaceLibusbConnection368 bool FindInterface(libusb_device_descriptor* device_desc) {
369 if (device_desc->bDeviceClass != LIBUSB_CLASS_PER_INTERFACE) {
370 // Assume that all Android devices have the device class set to per interface.
371 // TODO: Is this assumption valid?
372 VLOG(USB) << "skipping device with incorrect class at " << device_address_;
373 return false;
374 }
375
376 libusb_config_descriptor* config_raw;
377 int rc = libusb_get_active_config_descriptor(device_.get(), &config_raw);
378 if (rc != 0) {
379 LOG(WARNING) << "failed to get active config descriptor for device at "
380 << device_address_ << ": " << libusb_error_name(rc);
381 return false;
382 }
383 const unique_config_descriptor config(config_raw);
384
385 // Use size_t for interface_num so <iostream>s don't mangle it.
386 size_t interface_num;
387 uint16_t zero_mask = 0;
388 uint8_t bulk_in = 0, bulk_out = 0;
389 size_t packet_size = 0;
390 bool found_adb = false;
391
392 for (interface_num = 0; interface_num < config->bNumInterfaces; ++interface_num) {
393 const libusb_interface& interface = config->interface[interface_num];
394
395 if (interface.num_altsetting == 0) {
396 continue;
397 }
398
399 const libusb_interface_descriptor& interface_desc = interface.altsetting[0];
400 if (!is_adb_interface(interface_desc.bInterfaceClass, interface_desc.bInterfaceSubClass,
401 interface_desc.bInterfaceProtocol)) {
402 VLOG(USB) << "skipping non-adb interface at " << device_address_ << " (interface "
403 << interface_num << ")";
404 continue;
405 }
406
407 if (interface.num_altsetting != 1) {
408 // Assume that interfaces with alternate settings aren't adb interfaces.
409 // TODO: Is this assumption valid?
410 LOG(WARNING) << "skipping interface with unexpected num_altsetting at "
411 << device_address_ << " (interface " << interface_num << ")";
412 continue;
413 }
414
415 VLOG(USB) << "found potential adb interface at " << device_address_ << " (interface "
416 << interface_num << ")";
417
418 bool found_in = false;
419 bool found_out = false;
420 for (size_t endpoint_num = 0; endpoint_num < interface_desc.bNumEndpoints;
421 ++endpoint_num) {
422 const auto& endpoint_desc = interface_desc.endpoint[endpoint_num];
423 const uint8_t endpoint_addr = endpoint_desc.bEndpointAddress;
424 const uint8_t endpoint_attr = endpoint_desc.bmAttributes;
425
426 const uint8_t transfer_type = endpoint_attr & LIBUSB_TRANSFER_TYPE_MASK;
427
428 if (transfer_type != LIBUSB_TRANSFER_TYPE_BULK) {
429 continue;
430 }
431
432 if (endpoint_is_output(endpoint_addr) && !found_out) {
433 found_out = true;
434 bulk_out = endpoint_addr;
435 zero_mask = endpoint_desc.wMaxPacketSize - 1;
436 } else if (!endpoint_is_output(endpoint_addr) && !found_in) {
437 found_in = true;
438 bulk_in = endpoint_addr;
439 }
440
441 size_t endpoint_packet_size = endpoint_desc.wMaxPacketSize;
442 CHECK(endpoint_packet_size != 0);
443 if (packet_size == 0) {
444 packet_size = endpoint_packet_size;
445 } else {
446 CHECK(packet_size == endpoint_packet_size);
447 }
448 }
449
450 if (found_in && found_out) {
451 found_adb = true;
452 break;
453 } else {
454 VLOG(USB) << "rejecting potential adb interface at " << device_address_
455 << "(interface " << interface_num << "): missing bulk endpoints "
456 << "(found_in = " << found_in << ", found_out = " << found_out << ")";
457 }
458 }
459
460 if (!found_adb) {
461 return false;
462 }
463
464 interface_num_ = interface_num;
465 write_endpoint_ = bulk_out;
466 read_endpoint_ = bulk_in;
467 zero_mask_ = zero_mask;
468 return true;
469 }
470
GetUsbDeviceAddressLibusbConnection471 std::string GetUsbDeviceAddress() const { return std::string("usb:") + device_address_; }
472
GetSerialLibusbConnection473 std::string GetSerial() {
474 std::string serial;
475
476 auto device_desc = GetDeviceDescriptor();
477
478 serial.resize(255);
479 int rc = libusb_get_string_descriptor_ascii(
480 device_handle_.get(), device_desc->iSerialNumber,
481 reinterpret_cast<unsigned char*>(&serial[0]), serial.length());
482 if (rc == 0) {
483 LOG(WARNING) << "received empty serial from device at " << device_address_;
484 return {};
485 } else if (rc < 0) {
486 LOG(WARNING) << "failed to get serial from device at " << device_address_
487 << libusb_error_name(rc);
488 return {};
489 }
490 serial.resize(rc);
491
492 return serial;
493 }
494
495 // libusb gives us an int which is a value from 'enum libusb_speed'
ToConnectionSpeedLibusbConnection496 static uint64_t ToConnectionSpeed(int speed) {
497 switch (speed) {
498 case LIBUSB_SPEED_LOW:
499 return 1;
500 case LIBUSB_SPEED_FULL:
501 return 12;
502 case LIBUSB_SPEED_HIGH:
503 return 480;
504 case LIBUSB_SPEED_SUPER:
505 return 5000;
506 case LIBUSB_SPEED_SUPER_PLUS:
507 return 10000;
508 case LIBUSB_SPEED_SUPER_PLUS_X2:
509 return 20000;
510 case LIBUSB_SPEED_UNKNOWN:
511 default:
512 return 0;
513 }
514 }
515
516 // libusb gives us a bitfield made of 'enum libusb_supported_speed' values
ExtractMaxSuperSpeedLibusbConnection517 static uint64_t ExtractMaxSuperSpeed(uint16_t wSpeedSupported) {
518 if (wSpeedSupported == 0) {
519 return 0;
520 }
521
522 int msb = 0;
523 while (wSpeedSupported >>= 1) {
524 msb++;
525 }
526
527 switch (1 << msb) {
528 case LIBUSB_LOW_SPEED_OPERATION:
529 return 1;
530 case LIBUSB_FULL_SPEED_OPERATION:
531 return 12;
532 case LIBUSB_HIGH_SPEED_OPERATION:
533 return 480;
534 case LIBUSB_SUPER_SPEED_OPERATION:
535 return 5000;
536 default:
537 return 0;
538 }
539 }
540
ExtractMaxSuperSpeedPlusLibusbConnection541 static uint64_t ExtractMaxSuperSpeedPlus(libusb_ssplus_usb_device_capability_descriptor* cap) {
542 // The exponents is one of {bytes, kB, MB, or GB}. We express speed in MB so we use a 0
543 // multiplier for value which would result in 0MB anyway.
544 static uint64_t exponent[] = {0, 0, 1, 1000};
545 uint64_t max_speed = 0;
546 for (uint8_t i = 0; i < cap->numSublinkSpeedAttributes; i++) {
547 libusb_ssplus_sublink_attribute* attr = &cap->sublinkSpeedAttributes[i];
548 uint64_t speed = attr->mantissa * exponent[attr->exponent];
549 max_speed = std::max(max_speed, speed);
550 }
551 return max_speed;
552 }
553
RetrieveSpeedsLibusbConnection554 void RetrieveSpeeds() {
555 negotiated_speed_ = ToConnectionSpeed(libusb_get_device_speed(device_.get()));
556
557 // To discover the maximum speed supported by an USB device, we walk its capability
558 // descriptors.
559 struct libusb_bos_descriptor* bos = nullptr;
560 if (libusb_get_bos_descriptor(device_handle_.get(), &bos)) {
561 return;
562 }
563
564 for (int i = 0; i < bos->bNumDeviceCaps; i++) {
565 switch (bos->dev_capability[i]->bDevCapabilityType) {
566 case LIBUSB_BT_SS_USB_DEVICE_CAPABILITY: {
567 libusb_ss_usb_device_capability_descriptor* cap = nullptr;
568 if (!libusb_get_ss_usb_device_capability_descriptor(
569 nullptr, bos->dev_capability[i], &cap)) {
570 max_speed_ =
571 std::max(max_speed_, ExtractMaxSuperSpeed(cap->wSpeedSupported));
572 libusb_free_ss_usb_device_capability_descriptor(cap);
573 }
574 } break;
575 case LIBUSB_BT_SUPERSPEED_PLUS_CAPABILITY: {
576 libusb_ssplus_usb_device_capability_descriptor* cap = nullptr;
577 if (!libusb_get_ssplus_usb_device_capability_descriptor(
578 nullptr, bos->dev_capability[i], &cap)) {
579 max_speed_ = std::max(max_speed_, ExtractMaxSuperSpeedPlus(cap));
580 libusb_free_ssplus_usb_device_capability_descriptor(cap);
581 }
582 } break;
583 default:
584 break;
585 }
586 }
587 libusb_free_bos_descriptor(bos);
588 }
589
OpenDeviceLibusbConnection590 bool OpenDevice(std::string* error) {
591 if (device_handle_) {
592 LOG_ERR(error, "device already open");
593 return false;
594 }
595
596 libusb_device_handle* handle_raw;
597 int rc = libusb_open(device_.get(), &handle_raw);
598 if (rc != 0) {
599 // TODO: Handle no permissions.
600 LOG_ERR(error, "failed to open device: %s", libusb_strerror(rc));
601 return false;
602 }
603
604 unique_device_handle handle(handle_raw);
605 device_handle_ = std::move(handle);
606
607 auto device_desc = GetDeviceDescriptor();
608 if (!device_desc) {
609 LOG_ERR(error, "failed to get device descriptor");
610 device_handle_.reset();
611 return false;
612 }
613
614 if (!FindInterface(&device_desc.value())) {
615 LOG_ERR(error, "failed to find adb interface");
616 device_handle_.reset();
617 return false;
618 }
619
620 serial_ = GetSerial();
621
622 VLOG(USB) << "successfully opened adb device at " << device_address_ << ", "
623 << StringPrintf("bulk_in = %#x, bulk_out = %#x", read_endpoint_, write_endpoint_);
624
625 // WARNING: this isn't released via RAII.
626 rc = libusb_claim_interface(device_handle_.get(), interface_num_);
627 if (rc != 0) {
628 LOG_ERR(error, "failed to claim adb interface for device '%s': %s", serial_.c_str(),
629 libusb_error_name(rc));
630 device_handle_.reset();
631 return false;
632 }
633
634 for (uint8_t endpoint : {read_endpoint_, write_endpoint_}) {
635 rc = libusb_clear_halt(device_handle_.get(), endpoint);
636 if (rc != 0) {
637 LOG_ERR(error, "failed to clear halt on device '%s' endpoint %#02x: %s",
638 serial_.c_str(), endpoint, libusb_error_name(rc));
639 libusb_release_interface(device_handle_.get(), interface_num_);
640 device_handle_.reset();
641 return false;
642 }
643 }
644
645 RetrieveSpeeds();
646 return true;
647 }
648
CancelReadTransferLibusbConnection649 void CancelReadTransfer(ReadBlock* read_block) REQUIRES(read_mutex_) {
650 if (!read_block->transfer) {
651 return;
652 }
653
654 if (!read_block->active) {
655 // There is no read_cb pending. Clean it up right now.
656 Cleanup(read_block);
657 return;
658 }
659
660 int rc = libusb_cancel_transfer(read_block->transfer);
661 if (rc != 0) {
662 LOG(WARNING) << "libusb_cancel_transfer failed: " << libusb_error_name(rc);
663 // There is no read_cb pending. Clean it up right now.
664 Cleanup(read_block);
665 return;
666 }
667 }
668
CloseDeviceLibusbConnection669 void CloseDevice() {
670 // This is rather messy, because of the lifecyle of libusb_transfers.
671 //
672 // We can't call libusb_free_transfer for a submitted transfer, we have to cancel it
673 // and free it in the callback. Complicating things more, it's possible for us to be in
674 // the callback for a transfer as the destructor is being called, at which point cancelling
675 // the transfer won't do anything (and it's possible that we'll submit the transfer again
676 // in the callback).
677 //
678 // Resolve this by setting an atomic flag before we lock to cancel transfers, and take the
679 // lock in the callbacks before checking the flag.
680
681 if (terminated_) {
682 return;
683 }
684
685 terminated_ = true;
686
687 {
688 std::unique_lock<std::mutex> lock(write_mutex_);
689 ScopedLockAssertion assumed_locked(write_mutex_);
690
691 std::erase_if(writes_, [](const auto& write_item) {
692 auto const& [id, write_block] = write_item;
693 int rc = libusb_cancel_transfer(write_block->transfer);
694 if (rc != 0) {
695 // libusb_cancel_transfer failed for some reason. We will
696 // never get a callback for this transfer. So we need to
697 // remove it from the list or we will hang below.
698 LOG(INFO) << "libusb_cancel_transfer failed: " << libusb_error_name(rc);
699 libusb_free_transfer(write_block->transfer);
700 return true;
701 }
702 // Wait for the write_cb to fire before removing.
703 return false;
704 });
705
706 // Wait here until the write callbacks have all fired and removed
707 // the remaining writes_.
708 destruction_cv_.wait(lock, [this]() {
709 ScopedLockAssertion assumed_locked(write_mutex_);
710 return writes_.empty();
711 });
712 }
713
714 {
715 std::unique_lock<std::mutex> lock(read_mutex_);
716 ScopedLockAssertion assumed_locked(read_mutex_);
717
718 CancelReadTransfer(&header_read_);
719 CancelReadTransfer(&payload_read_);
720
721 destruction_cv_.wait(lock, [this]() {
722 ScopedLockAssertion assumed_locked(read_mutex_);
723 return !header_read_.active && !payload_read_.active;
724 });
725
726 incoming_header_.reset();
727 }
728
729 if (device_handle_) {
730 int rc = libusb_release_interface(device_handle_.get(), interface_num_);
731 if (rc != 0) {
732 LOG(WARNING) << "libusb_release_interface failed: " << libusb_error_name(rc);
733 }
734 device_handle_.reset();
735 }
736 }
737
StartImplLibusbConnection738 bool StartImpl(std::string* error) {
739 if (!device_handle_) {
740 *error = "device not opened";
741 return false;
742 }
743
744 VLOG(USB) << "registered new usb device '" << serial_ << "'";
745 std::lock_guard lock(read_mutex_);
746 CreateRead(&header_read_, true);
747 CreateRead(&payload_read_, false);
748 SubmitRead(&header_read_, sizeof(amessage));
749
750 return true;
751 }
752
OnErrorLibusbConnection753 void OnError(const std::string& error) {
754 std::call_once(error_flag_, [this, &error]() {
755 if (transport_) {
756 transport_->HandleError(error);
757 }
758 });
759 }
760
AttachLibusbConnection761 virtual bool Attach(std::string* error) override final {
762 terminated_ = false;
763 detached_ = false;
764
765 if (!OpenDevice(error)) {
766 return false;
767 }
768
769 if (!StartImpl(error)) {
770 CloseDevice();
771 return false;
772 }
773
774 return true;
775 }
776
DetachLibusbConnection777 virtual bool Detach(std::string* error) override final {
778 detached_ = true;
779 CloseDevice();
780 return true;
781 }
782
ResetLibusbConnection783 virtual void Reset() override final {
784 VLOG(USB) << "resetting " << transport_->serial_name();
785 int rc = libusb_reset_device(device_handle_.get());
786 if (rc == 0) {
787 libusb_device* device = libusb_ref_device(device_.get());
788
789 Stop();
790
791 fdevent_run_on_looper([device]() {
792 process_device(device);
793 libusb_unref_device(device);
794 });
795 } else {
796 LOG(ERROR) << "libusb_reset_device failed: " << libusb_error_name(rc);
797 }
798 }
799
StartLibusbConnection800 virtual bool Start() override final {
801 std::string error;
802 if (!Attach(&error)) {
803 OnError(error);
804 return false;
805 }
806 return true;
807 }
808
StopLibusbConnection809 virtual void Stop() override final {
810 CloseDevice();
811 OnError("requested stop");
812 }
813
CreateLibusbConnection814 static std::optional<std::shared_ptr<LibusbConnection>> Create(unique_device device) {
815 auto connection = std::make_unique<LibusbConnection>(std::move(device));
816 if (!connection) {
817 LOG(FATAL) << "failed to construct LibusbConnection";
818 }
819
820 auto device_desc = connection->GetDeviceDescriptor();
821 if (!device_desc) {
822 VLOG(USB) << "ignoring device " << connection->GetUsbDeviceAddress()
823 << ": not an adb interface. (GetDeviceDescriptor)";
824 return {};
825 }
826
827 if (!connection->FindInterface(&device_desc.value())) {
828 VLOG(USB) << "ignoring device " << connection->GetUsbDeviceAddress()
829 << ": not an adb interface. (FindInterface)";
830 return {};
831 }
832
833 #if defined(__linux__)
834 std::string device_serial;
835 if (android::base::ReadFileToString(get_device_serial_path(connection->device_.get()),
836 &device_serial)) {
837 connection->serial_ = android::base::Trim(device_serial);
838 } else {
839 // We don't actually want to treat an unknown serial as an error because
840 // devices aren't able to communicate a serial number in early bringup.
841 // http://b/20883914
842 connection->serial_ = "<unknown>";
843 }
844 #else
845 // We need to open the device to get its serial on Windows and OS X.
846 std::string error;
847 if (!connection->OpenDevice(&error)) {
848 VLOG(USB) << "ignoring device " << connection->GetUsbDeviceAddress()
849 << ": not an adb interface. (OpenDevice)";
850 return {};
851 }
852 connection->serial_ = connection->GetSerial();
853 connection->CloseDevice();
854 #endif
855 if (!transport_server_owns_device(connection->GetUsbDeviceAddress(), connection->serial_)) {
856 VLOG(USB) << "ignoring device " << connection->GetUsbDeviceAddress() << " serial "
857 << connection->serial_ << ": this server owns '" << transport_get_one_device()
858 << "'";
859 return {};
860 }
861
862 return connection;
863 }
864
MaxSpeedMbpsLibusbConnection865 virtual uint64_t MaxSpeedMbps() override final { return max_speed_; }
866
NegotiatedSpeedMbpsLibusbConnection867 virtual uint64_t NegotiatedSpeedMbps() override final { return negotiated_speed_; }
868
869 unique_device device_;
870 unique_device_handle device_handle_;
871 std::string device_address_;
872 std::string serial_ = "<unknown>";
873
874 uint32_t interface_num_;
875 uint8_t write_endpoint_;
876 uint8_t read_endpoint_;
877
878 std::mutex read_mutex_;
879 ReadBlock header_read_ GUARDED_BY(read_mutex_);
880 ReadBlock payload_read_ GUARDED_BY(read_mutex_);
881 std::optional<amessage> incoming_header_ GUARDED_BY(read_mutex_);
882
883 std::mutex write_mutex_;
884 std::unordered_map<TransferId, std::unique_ptr<WriteBlock>> writes_ GUARDED_BY(write_mutex_);
885 std::atomic<size_t> next_write_id_ = 0;
886
887 std::once_flag error_flag_;
888 std::atomic<bool> terminated_ = false;
889 std::atomic<bool> detached_ = false;
890 std::condition_variable destruction_cv_;
891
892 size_t zero_mask_ = 0;
893
894 uint64_t negotiated_speed_ = 0;
895 uint64_t max_speed_ = 0;
896 };
897
898 static std::mutex usb_handles_mutex [[clang::no_destroy]];
899 static std::unordered_map<libusb_device*, std::weak_ptr<LibusbConnection>> usb_handles
900 [[clang::no_destroy]] GUARDED_BY(usb_handles_mutex);
901 static std::atomic<int> connecting_devices(0);
902
process_device(libusb_device * device_raw)903 static void process_device(libusb_device* device_raw) {
904 std::string device_address = "usb:" + get_device_address(device_raw);
905 VLOG(USB) << "device connected: " << device_address;
906
907 unique_device device(libusb_ref_device(device_raw));
908 auto connection_opt = LibusbConnection::Create(std::move(device));
909 if (!connection_opt) {
910 return;
911 }
912
913 auto connection = *connection_opt;
914
915 {
916 std::lock_guard<std::mutex> lock(usb_handles_mutex);
917 usb_handles.emplace(libusb_ref_device(device_raw), connection);
918 }
919
920 VLOG(USB) << "constructed LibusbConnection for device " << connection->serial_ << " ("
921 << device_address << ")";
922
923 register_libusb_transport(connection, connection->serial_.c_str(), device_address.c_str(),
924 true);
925 }
926
device_connected(libusb_device * device)927 static void device_connected(libusb_device* device) {
928 #if defined(__linux__)
929 // Android's host linux libusb uses netlink instead of udev for device hotplug notification,
930 // which means we can get hotplug notifications before udev has updated ownership/perms on the
931 // device. Since we're not going to be able to link against the system's libudev any time soon,
932 // poll for accessibility changes with inotify until a timeout expires.
933 libusb_ref_device(device);
934 auto thread = std::thread([device]() {
935 std::string bus_path = StringPrintf("/dev/bus/usb/%03d/", libusb_get_bus_number(device));
936 std::string device_path =
937 StringPrintf("%s/%03d", bus_path.c_str(), libusb_get_device_address(device));
938 auto deadline = std::chrono::steady_clock::now() + 1s;
939 unique_fd infd(inotify_init1(IN_CLOEXEC | IN_NONBLOCK));
940 if (infd == -1) {
941 PLOG(FATAL) << "failed to create inotify fd";
942 }
943
944 // Register the watch first, and then check for accessibility, to avoid a race.
945 // We can't watch the device file itself, as that requires us to be able to access it.
946 if (inotify_add_watch(infd.get(), bus_path.c_str(), IN_ATTRIB) == -1) {
947 PLOG(ERROR) << "failed to register inotify watch on '" << bus_path
948 << "', falling back to sleep";
949 std::this_thread::sleep_for(std::chrono::seconds(1));
950 } else {
951 adb_pollfd pfd = {.fd = infd.get(), .events = POLLIN, .revents = 0};
952
953 while (access(device_path.c_str(), R_OK | W_OK) == -1) {
954 auto timeout = deadline - std::chrono::steady_clock::now();
955 if (timeout < 0s) {
956 break;
957 }
958
959 uint64_t ms = timeout / 1ms;
960 int rc = adb_poll(&pfd, 1, ms);
961 if (rc == -1) {
962 if (errno == EINTR) {
963 continue;
964 } else {
965 LOG(WARNING) << "timeout expired while waiting for device accessibility";
966 break;
967 }
968 }
969
970 union {
971 struct inotify_event ev;
972 char bytes[sizeof(struct inotify_event) + NAME_MAX + 1];
973 } buf;
974
975 rc = adb_read(infd.get(), &buf, sizeof(buf));
976 if (rc == -1) {
977 break;
978 }
979
980 // We don't actually care about the data: we might get spurious events for
981 // other devices on the bus, but we'll double check in the loop condition.
982 continue;
983 }
984 }
985
986 process_device(device);
987 if (--connecting_devices == 0) {
988 adb_notify_device_scan_complete();
989 }
990 libusb_unref_device(device);
991 });
992 thread.detach();
993 #else
994 process_device(device);
995 #endif
996 }
997
device_disconnected(libusb_device * device)998 static void device_disconnected(libusb_device* device) {
999 usb_handles_mutex.lock();
1000 auto it = usb_handles.find(device);
1001 if (it != usb_handles.end()) {
1002 // We need to ensure that we don't destroy the LibusbConnection on this thread,
1003 // as we're in a context with internal libusb mutexes held.
1004 libusb_device* device = it->first;
1005 std::weak_ptr<LibusbConnection> connection_weak = it->second;
1006 usb_handles.erase(it);
1007 fdevent_run_on_looper([connection_weak]() {
1008 auto connection = connection_weak.lock();
1009 if (connection) {
1010 connection->Stop();
1011 VLOG(USB) << "libusb_hotplug: device disconnected: " << connection->serial_;
1012 } else {
1013 VLOG(USB) << "libusb_hotplug: device disconnected: (destroyed)";
1014 }
1015 });
1016 libusb_unref_device(device);
1017 }
1018 usb_handles_mutex.unlock();
1019 }
1020
1021 static auto& hotplug_queue = *new BlockingQueue<std::pair<libusb_hotplug_event, libusb_device*>>();
hotplug_thread()1022 static void hotplug_thread() {
1023 VLOG(USB) << "libusb hotplug thread started";
1024 adb_thread_setname("libusb hotplug");
1025 while (true) {
1026 hotplug_queue.PopAll([](std::pair<libusb_hotplug_event, libusb_device*> pair) {
1027 libusb_hotplug_event event = pair.first;
1028 libusb_device* device = pair.second;
1029 if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED) {
1030 VLOG(USB) << "libusb hotplug: device arrived";
1031 device_connected(device);
1032 } else if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT) {
1033 VLOG(USB) << "libusb hotplug: device left";
1034 device_disconnected(device);
1035 } else {
1036 LOG(WARNING) << "unknown libusb hotplug event: " << event;
1037 }
1038 });
1039 }
1040 }
1041
hotplug_callback(libusb_context *,libusb_device * device,libusb_hotplug_event event,void *)1042 static LIBUSB_CALL int hotplug_callback(libusb_context*, libusb_device* device,
1043 libusb_hotplug_event event, void*) {
1044 // We're called with the libusb lock taken. Call these on a separate thread outside of this
1045 // function so that the usb_handle mutex is always taken before the libusb mutex.
1046 static std::once_flag once;
1047 std::call_once(once, []() { std::thread(hotplug_thread).detach(); });
1048
1049 if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED) {
1050 ++connecting_devices;
1051 }
1052 hotplug_queue.Push({event, device});
1053 return 0;
1054 }
1055
1056 namespace libusb {
1057
usb_init()1058 void usb_init() {
1059 VLOG(USB) << "initializing libusb...";
1060 int rc = libusb_init(nullptr);
1061 if (rc != 0) {
1062 LOG(WARNING) << "failed to initialize libusb: " << libusb_error_name(rc);
1063 return;
1064 }
1065
1066 // Register the hotplug callback.
1067 rc = libusb_hotplug_register_callback(
1068 nullptr,
1069 static_cast<libusb_hotplug_event>(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED |
1070 LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT),
1071 LIBUSB_HOTPLUG_ENUMERATE, LIBUSB_HOTPLUG_MATCH_ANY, LIBUSB_HOTPLUG_MATCH_ANY,
1072 LIBUSB_CLASS_PER_INTERFACE, hotplug_callback, nullptr, nullptr);
1073
1074 if (rc != LIBUSB_SUCCESS) {
1075 LOG(FATAL) << "failed to register libusb hotplug callback";
1076 }
1077
1078 // Spawn a thread for libusb_handle_events.
1079 std::thread([]() {
1080 adb_thread_setname("libusb");
1081 while (true) {
1082 libusb_handle_events(nullptr);
1083 }
1084 }).detach();
1085 }
1086
1087 } // namespace libusb
1088