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