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