Home | History | Annotate | Download | only in client
      1 /*
      2  * Copyright (C) 2007 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #define TRACE_TAG USB
     18 
     19 #include "sysdeps.h"
     20 
     21 // clang-format off
     22 #include <winsock2.h>  // winsock.h *must* be included before windows.h.
     23 #include <windows.h>
     24 // clang-format on
     25 #include <usb100.h>
     26 #include <winerror.h>
     27 
     28 #include <errno.h>
     29 #include <stdio.h>
     30 #include <stdlib.h>
     31 
     32 #include <algorithm>
     33 #include <mutex>
     34 #include <thread>
     35 
     36 #include <adb_api.h>
     37 
     38 #include <android-base/errors.h>
     39 
     40 #include "adb.h"
     41 #include "sysdeps/chrono.h"
     42 #include "transport.h"
     43 
     44 namespace native {
     45 
     46 /** Structure usb_handle describes our connection to the usb device via
     47   AdbWinApi.dll. This structure is returned from usb_open() routine and
     48   is expected in each subsequent call that is accessing the device.
     49 
     50   Most members are protected by usb_lock, except for adb_{read,write}_pipe which
     51   rely on AdbWinApi.dll's handle validation and AdbCloseHandle(endpoint)'s
     52   ability to break a thread out of pipe IO.
     53 */
     54 struct usb_handle : public ::usb_handle {
     55     /// Handle to USB interface
     56     ADBAPIHANDLE adb_interface;
     57 
     58     /// Handle to USB read pipe (endpoint)
     59     ADBAPIHANDLE adb_read_pipe;
     60 
     61     /// Handle to USB write pipe (endpoint)
     62     ADBAPIHANDLE adb_write_pipe;
     63 
     64     /// Interface name
     65     wchar_t* interface_name;
     66 
     67     /// Maximum packet size.
     68     unsigned max_packet_size;
     69 
     70     /// Mask for determining when to use zero length packets
     71     unsigned zero_mask;
     72 };
     73 
     74 /// Class ID assigned to the device by androidusb.sys
     75 static const GUID usb_class_id = ANDROID_USB_CLASS_ID;
     76 
     77 /// List of opened usb handles
     78 static std::vector<usb_handle*> handle_list;
     79 
     80 /// Locker for the list of opened usb handles
     81 static std::mutex& usb_lock = *new std::mutex();
     82 
     83 /// Checks if there is opened usb handle in handle_list for this device.
     84 int known_device(const wchar_t* dev_name);
     85 
     86 /// Checks if there is opened usb handle in handle_list for this device.
     87 /// usb_lock mutex must be held before calling this routine.
     88 int known_device_locked(const wchar_t* dev_name);
     89 
     90 /// Registers opened usb handle (adds it to handle_list).
     91 int register_new_device(usb_handle* handle);
     92 
     93 /// Checks if interface (device) matches certain criteria
     94 int recognized_device(usb_handle* handle);
     95 
     96 /// Enumerates present and available interfaces (devices), opens new ones and
     97 /// registers usb transport for them.
     98 void find_devices();
     99 
    100 /// Kicks all USB devices
    101 static void kick_devices();
    102 
    103 /// Entry point for thread that polls (every second) for new usb interfaces.
    104 /// This routine calls find_devices in infinite loop.
    105 static void device_poll_thread();
    106 
    107 /// Initializes this module
    108 void usb_init();
    109 
    110 /// Opens usb interface (device) by interface (device) name.
    111 usb_handle* do_usb_open(const wchar_t* interface_name);
    112 
    113 /// Writes data to the opened usb handle
    114 int usb_write(usb_handle* handle, const void* data, int len);
    115 
    116 /// Reads data using the opened usb handle
    117 int usb_read(usb_handle* handle, void* data, int len);
    118 
    119 /// Cleans up opened usb handle
    120 void usb_cleanup_handle(usb_handle* handle);
    121 
    122 /// Cleans up (but don't close) opened usb handle
    123 void usb_kick(usb_handle* handle);
    124 
    125 /// Closes opened usb handle
    126 int usb_close(usb_handle* handle);
    127 
    128 int known_device_locked(const wchar_t* dev_name) {
    129     if (NULL != dev_name) {
    130         // Iterate through the list looking for the name match.
    131         for (usb_handle* usb : handle_list) {
    132             // In Windows names are not case sensetive!
    133             if ((NULL != usb->interface_name) && (0 == wcsicmp(usb->interface_name, dev_name))) {
    134                 return 1;
    135             }
    136         }
    137     }
    138 
    139     return 0;
    140 }
    141 
    142 int known_device(const wchar_t* dev_name) {
    143     int ret = 0;
    144 
    145     if (NULL != dev_name) {
    146         std::lock_guard<std::mutex> lock(usb_lock);
    147         ret = known_device_locked(dev_name);
    148     }
    149 
    150     return ret;
    151 }
    152 
    153 int register_new_device(usb_handle* handle) {
    154     if (NULL == handle) return 0;
    155 
    156     std::lock_guard<std::mutex> lock(usb_lock);
    157 
    158     // Check if device is already in the list
    159     if (known_device_locked(handle->interface_name)) {
    160         return 0;
    161     }
    162 
    163     // Not in the list. Add this handle to the list.
    164     handle_list.push_back(handle);
    165 
    166     return 1;
    167 }
    168 
    169 void device_poll_thread() {
    170     adb_thread_setname("Device Poll");
    171     D("Created device thread");
    172 
    173     while (true) {
    174         find_devices();
    175         std::this_thread::sleep_for(1s);
    176     }
    177 }
    178 
    179 static LRESULT CALLBACK _power_window_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    180     switch (uMsg) {
    181         case WM_POWERBROADCAST:
    182             switch (wParam) {
    183                 case PBT_APMRESUMEAUTOMATIC:
    184                     // Resuming from sleep or hibernation, so kick all existing USB devices
    185                     // and then allow the device_poll_thread to redetect USB devices from
    186                     // scratch. If we don't do this, existing USB devices will never respond
    187                     // to us because they'll be waiting for the connect/auth handshake.
    188                     D("Received (WM_POWERBROADCAST, PBT_APMRESUMEAUTOMATIC) notification, "
    189                       "so kicking all USB devices\n");
    190                     kick_devices();
    191                     return TRUE;
    192             }
    193     }
    194     return DefWindowProcW(hwnd, uMsg, wParam, lParam);
    195 }
    196 
    197 static void _power_notification_thread() {
    198     // This uses a thread with its own window message pump to get power
    199     // notifications. If adb runs from a non-interactive service account, this
    200     // might not work (not sure). If that happens to not work, we could use
    201     // heavyweight WMI APIs to get power notifications. But for the common case
    202     // of a developer's interactive session, a window message pump is more
    203     // appropriate.
    204     D("Created power notification thread");
    205     adb_thread_setname("Power Notifier");
    206 
    207     // Window class names are process specific.
    208     static const WCHAR kPowerNotificationWindowClassName[] = L"PowerNotificationWindow";
    209 
    210     // Get the HINSTANCE corresponding to the module that _power_window_proc
    211     // is in (the main module).
    212     const HINSTANCE instance = GetModuleHandleW(NULL);
    213     if (!instance) {
    214         // This is such a common API call that this should never fail.
    215         fatal("GetModuleHandleW failed: %s",
    216               android::base::SystemErrorCodeToString(GetLastError()).c_str());
    217     }
    218 
    219     WNDCLASSEXW wndclass;
    220     memset(&wndclass, 0, sizeof(wndclass));
    221     wndclass.cbSize = sizeof(wndclass);
    222     wndclass.lpfnWndProc = _power_window_proc;
    223     wndclass.hInstance = instance;
    224     wndclass.lpszClassName = kPowerNotificationWindowClassName;
    225     if (!RegisterClassExW(&wndclass)) {
    226         fatal("RegisterClassExW failed: %s",
    227               android::base::SystemErrorCodeToString(GetLastError()).c_str());
    228     }
    229 
    230     if (!CreateWindowExW(WS_EX_NOACTIVATE, kPowerNotificationWindowClassName,
    231                          L"ADB Power Notification Window", WS_POPUP, 0, 0, 0, 0, NULL, NULL,
    232                          instance, NULL)) {
    233         fatal("CreateWindowExW failed: %s",
    234               android::base::SystemErrorCodeToString(GetLastError()).c_str());
    235     }
    236 
    237     MSG msg;
    238     while (GetMessageW(&msg, NULL, 0, 0)) {
    239         TranslateMessage(&msg);
    240         DispatchMessageW(&msg);
    241     }
    242 
    243     // GetMessageW() will return false if a quit message is posted. We don't
    244     // do that, but it might be possible for that to occur when logging off or
    245     // shutting down. Not a big deal since the whole process will be going away
    246     // soon anyway.
    247     D("Power notification thread exiting");
    248 }
    249 
    250 void usb_init() {
    251     std::thread(device_poll_thread).detach();
    252     std::thread(_power_notification_thread).detach();
    253 }
    254 
    255 void usb_cleanup() {}
    256 
    257 usb_handle* do_usb_open(const wchar_t* interface_name) {
    258     unsigned long name_len = 0;
    259 
    260     // Allocate our handle
    261     usb_handle* ret = (usb_handle*)calloc(1, sizeof(usb_handle));
    262     if (NULL == ret) {
    263         D("Could not allocate %u bytes for usb_handle: %s", sizeof(usb_handle), strerror(errno));
    264         goto fail;
    265     }
    266 
    267     // Create interface.
    268     ret->adb_interface = AdbCreateInterfaceByName(interface_name);
    269     if (NULL == ret->adb_interface) {
    270         D("AdbCreateInterfaceByName failed: %s",
    271           android::base::SystemErrorCodeToString(GetLastError()).c_str());
    272         goto fail;
    273     }
    274 
    275     // Open read pipe (endpoint)
    276     ret->adb_read_pipe = AdbOpenDefaultBulkReadEndpoint(
    277         ret->adb_interface, AdbOpenAccessTypeReadWrite, AdbOpenSharingModeReadWrite);
    278     if (NULL == ret->adb_read_pipe) {
    279         D("AdbOpenDefaultBulkReadEndpoint failed: %s",
    280           android::base::SystemErrorCodeToString(GetLastError()).c_str());
    281         goto fail;
    282     }
    283 
    284     // Open write pipe (endpoint)
    285     ret->adb_write_pipe = AdbOpenDefaultBulkWriteEndpoint(
    286         ret->adb_interface, AdbOpenAccessTypeReadWrite, AdbOpenSharingModeReadWrite);
    287     if (NULL == ret->adb_write_pipe) {
    288         D("AdbOpenDefaultBulkWriteEndpoint failed: %s",
    289           android::base::SystemErrorCodeToString(GetLastError()).c_str());
    290         goto fail;
    291     }
    292 
    293     // Save interface name
    294     // First get expected name length
    295     AdbGetInterfaceName(ret->adb_interface, NULL, &name_len, false);
    296     if (0 == name_len) {
    297         D("AdbGetInterfaceName returned name length of zero: %s",
    298           android::base::SystemErrorCodeToString(GetLastError()).c_str());
    299         goto fail;
    300     }
    301 
    302     ret->interface_name = (wchar_t*)malloc(name_len * sizeof(ret->interface_name[0]));
    303     if (NULL == ret->interface_name) {
    304         D("Could not allocate %lu characters for interface_name: %s", name_len, strerror(errno));
    305         goto fail;
    306     }
    307 
    308     // Now save the name
    309     if (!AdbGetInterfaceName(ret->adb_interface, ret->interface_name, &name_len, false)) {
    310         D("AdbGetInterfaceName failed: %s",
    311           android::base::SystemErrorCodeToString(GetLastError()).c_str());
    312         goto fail;
    313     }
    314 
    315     // We're done at this point
    316     return ret;
    317 
    318 fail:
    319     if (NULL != ret) {
    320         usb_cleanup_handle(ret);
    321         free(ret);
    322     }
    323 
    324     return NULL;
    325 }
    326 
    327 int usb_write(usb_handle* handle, const void* data, int len) {
    328     unsigned long time_out = 5000;
    329     unsigned long written = 0;
    330     int err = 0;
    331 
    332     D("usb_write %d", len);
    333     if (NULL == handle) {
    334         D("usb_write was passed NULL handle");
    335         err = EINVAL;
    336         goto fail;
    337     }
    338 
    339     // Perform write
    340     if (!AdbWriteEndpointSync(handle->adb_write_pipe, (void*)data, (unsigned long)len, &written,
    341                               time_out)) {
    342         D("AdbWriteEndpointSync failed: %s",
    343           android::base::SystemErrorCodeToString(GetLastError()).c_str());
    344         err = EIO;
    345         goto fail;
    346     }
    347 
    348     // Make sure that we've written what we were asked to write
    349     D("usb_write got: %ld, expected: %d", written, len);
    350     if (written != (unsigned long)len) {
    351         // If this occurs, this code should be changed to repeatedly call
    352         // AdbWriteEndpointSync() until all bytes are written.
    353         D("AdbWriteEndpointSync was supposed to write %d, but only wrote %ld", len, written);
    354         err = EIO;
    355         goto fail;
    356     }
    357 
    358     if (handle->zero_mask && (len & handle->zero_mask) == 0) {
    359         // Send a zero length packet
    360         if (!AdbWriteEndpointSync(handle->adb_write_pipe, (void*)data, 0, &written, time_out)) {
    361             D("AdbWriteEndpointSync of zero length packet failed: %s",
    362               android::base::SystemErrorCodeToString(GetLastError()).c_str());
    363             err = EIO;
    364             goto fail;
    365         }
    366     }
    367 
    368     return 0;
    369 
    370 fail:
    371     // Any failure should cause us to kick the device instead of leaving it a
    372     // zombie state with potential to hang.
    373     if (NULL != handle) {
    374         D("Kicking device due to error in usb_write");
    375         usb_kick(handle);
    376     }
    377 
    378     D("usb_write failed");
    379     errno = err;
    380     return -1;
    381 }
    382 
    383 int usb_read(usb_handle* handle, void* data, int len) {
    384     unsigned long time_out = 0;
    385     unsigned long read = 0;
    386     int err = 0;
    387     int orig_len = len;
    388 
    389     D("usb_read %d", len);
    390     if (NULL == handle) {
    391         D("usb_read was passed NULL handle");
    392         err = EINVAL;
    393         goto fail;
    394     }
    395 
    396     while (len == orig_len) {
    397         if (!AdbReadEndpointSync(handle->adb_read_pipe, data, len, &read, time_out)) {
    398             D("AdbReadEndpointSync failed: %s",
    399               android::base::SystemErrorCodeToString(GetLastError()).c_str());
    400             err = EIO;
    401             goto fail;
    402         }
    403         D("usb_read got: %ld, expected: %d", read, len);
    404 
    405         data = (char*)data + read;
    406         len -= read;
    407     }
    408 
    409     return orig_len - len;
    410 
    411 fail:
    412     // Any failure should cause us to kick the device instead of leaving it a
    413     // zombie state with potential to hang.
    414     if (NULL != handle) {
    415         D("Kicking device due to error in usb_read");
    416         usb_kick(handle);
    417     }
    418 
    419     D("usb_read failed");
    420     errno = err;
    421     return -1;
    422 }
    423 
    424 // Wrapper around AdbCloseHandle() that logs diagnostics.
    425 static void _adb_close_handle(ADBAPIHANDLE adb_handle) {
    426     if (!AdbCloseHandle(adb_handle)) {
    427         D("AdbCloseHandle(%p) failed: %s", adb_handle,
    428           android::base::SystemErrorCodeToString(GetLastError()).c_str());
    429     }
    430 }
    431 
    432 void usb_cleanup_handle(usb_handle* handle) {
    433     D("usb_cleanup_handle");
    434     if (NULL != handle) {
    435         if (NULL != handle->interface_name) free(handle->interface_name);
    436         // AdbCloseHandle(pipe) will break any threads out of pending IO calls and
    437         // wait until the pipe no longer uses the interface. Then we can
    438         // AdbCloseHandle() the interface.
    439         if (NULL != handle->adb_write_pipe) _adb_close_handle(handle->adb_write_pipe);
    440         if (NULL != handle->adb_read_pipe) _adb_close_handle(handle->adb_read_pipe);
    441         if (NULL != handle->adb_interface) _adb_close_handle(handle->adb_interface);
    442 
    443         handle->interface_name = NULL;
    444         handle->adb_write_pipe = NULL;
    445         handle->adb_read_pipe = NULL;
    446         handle->adb_interface = NULL;
    447     }
    448 }
    449 
    450 static void usb_kick_locked(usb_handle* handle) {
    451     // The reason the lock must be acquired before calling this function is in
    452     // case multiple threads are trying to kick the same device at the same time.
    453     usb_cleanup_handle(handle);
    454 }
    455 
    456 void usb_kick(usb_handle* handle) {
    457     D("usb_kick");
    458     if (NULL != handle) {
    459         std::lock_guard<std::mutex> lock(usb_lock);
    460         usb_kick_locked(handle);
    461     } else {
    462         errno = EINVAL;
    463     }
    464 }
    465 
    466 int usb_close(usb_handle* handle) {
    467     D("usb_close");
    468 
    469     if (NULL != handle) {
    470         // Remove handle from the list
    471         {
    472             std::lock_guard<std::mutex> lock(usb_lock);
    473             handle_list.erase(std::remove(handle_list.begin(), handle_list.end(), handle),
    474                               handle_list.end());
    475         }
    476 
    477         // Cleanup handle
    478         usb_cleanup_handle(handle);
    479         free(handle);
    480     }
    481 
    482     return 0;
    483 }
    484 
    485 size_t usb_get_max_packet_size(usb_handle* handle) {
    486     return handle->max_packet_size;
    487 }
    488 
    489 int recognized_device(usb_handle* handle) {
    490     if (NULL == handle) return 0;
    491 
    492     // Check vendor and product id first
    493     USB_DEVICE_DESCRIPTOR device_desc;
    494 
    495     if (!AdbGetUsbDeviceDescriptor(handle->adb_interface, &device_desc)) {
    496         D("AdbGetUsbDeviceDescriptor failed: %s",
    497           android::base::SystemErrorCodeToString(GetLastError()).c_str());
    498         return 0;
    499     }
    500 
    501     // Then check interface properties
    502     USB_INTERFACE_DESCRIPTOR interf_desc;
    503 
    504     if (!AdbGetUsbInterfaceDescriptor(handle->adb_interface, &interf_desc)) {
    505         D("AdbGetUsbInterfaceDescriptor failed: %s",
    506           android::base::SystemErrorCodeToString(GetLastError()).c_str());
    507         return 0;
    508     }
    509 
    510     // Must have two endpoints
    511     if (2 != interf_desc.bNumEndpoints) {
    512         return 0;
    513     }
    514 
    515     if (!is_adb_interface(interf_desc.bInterfaceClass, interf_desc.bInterfaceSubClass,
    516                           interf_desc.bInterfaceProtocol)) {
    517         return 0;
    518     }
    519 
    520     AdbEndpointInformation endpoint_info;
    521     // assuming zero is a valid bulk endpoint ID
    522     if (AdbGetEndpointInformation(handle->adb_interface, 0, &endpoint_info)) {
    523         handle->max_packet_size = endpoint_info.max_packet_size;
    524         handle->zero_mask = endpoint_info.max_packet_size - 1;
    525         D("device zero_mask: 0x%x", handle->zero_mask);
    526     } else {
    527         D("AdbGetEndpointInformation failed: %s",
    528           android::base::SystemErrorCodeToString(GetLastError()).c_str());
    529     }
    530 
    531     return 1;
    532 }
    533 
    534 void find_devices() {
    535     usb_handle* handle = NULL;
    536     char entry_buffer[2048];
    537     AdbInterfaceInfo* next_interface = (AdbInterfaceInfo*)(&entry_buffer[0]);
    538     unsigned long entry_buffer_size = sizeof(entry_buffer);
    539 
    540     // Enumerate all present and active interfaces.
    541     ADBAPIHANDLE enum_handle = AdbEnumInterfaces(usb_class_id, true, true, true);
    542 
    543     if (NULL == enum_handle) {
    544         D("AdbEnumInterfaces failed: %s",
    545           android::base::SystemErrorCodeToString(GetLastError()).c_str());
    546         return;
    547     }
    548 
    549     while (AdbNextInterface(enum_handle, next_interface, &entry_buffer_size)) {
    550         // Lets see if we already have this device in the list
    551         if (!known_device(next_interface->device_name)) {
    552             // This seems to be a new device. Open it!
    553             handle = do_usb_open(next_interface->device_name);
    554             if (NULL != handle) {
    555                 // Lets see if this interface (device) belongs to us
    556                 if (recognized_device(handle)) {
    557                     D("adding a new device %ls", next_interface->device_name);
    558 
    559                     // We don't request a wchar_t string from AdbGetSerialNumber() because of a bug
    560                     // in adb_winusb_interface.cpp:CopyMemory(buffer, ser_num->bString,
    561                     // bytes_written) where the last parameter should be (str_len *
    562                     // sizeof(wchar_t)). The bug reads 2 bytes past the end of a stack buffer in the
    563                     // best case, and in the unlikely case of a long serial number, it will read 2
    564                     // bytes past the end of a heap allocation. This doesn't affect the resulting
    565                     // string, but we should avoid the bad reads in the first place.
    566                     char serial_number[512];
    567                     unsigned long serial_number_len = sizeof(serial_number);
    568                     if (AdbGetSerialNumber(handle->adb_interface, serial_number, &serial_number_len,
    569                                            true)) {
    570                         // Lets make sure that we don't duplicate this device
    571                         if (register_new_device(handle)) {
    572                             register_usb_transport(handle, serial_number, NULL, 1);
    573                         } else {
    574                             D("register_new_device failed for %ls", next_interface->device_name);
    575                             usb_cleanup_handle(handle);
    576                             free(handle);
    577                         }
    578                     } else {
    579                         D("cannot get serial number: %s",
    580                           android::base::SystemErrorCodeToString(GetLastError()).c_str());
    581                         usb_cleanup_handle(handle);
    582                         free(handle);
    583                     }
    584                 } else {
    585                     usb_cleanup_handle(handle);
    586                     free(handle);
    587                 }
    588             }
    589         }
    590 
    591         entry_buffer_size = sizeof(entry_buffer);
    592     }
    593 
    594     if (GetLastError() != ERROR_NO_MORE_ITEMS) {
    595         // Only ERROR_NO_MORE_ITEMS is expected at the end of enumeration.
    596         D("AdbNextInterface failed: %s",
    597           android::base::SystemErrorCodeToString(GetLastError()).c_str());
    598     }
    599 
    600     _adb_close_handle(enum_handle);
    601 }
    602 
    603 static void kick_devices() {
    604     // Need to acquire lock to safely walk the list which might be modified
    605     // by another thread.
    606     std::lock_guard<std::mutex> lock(usb_lock);
    607     for (usb_handle* usb : handle_list) {
    608         usb_kick_locked(usb);
    609     }
    610 }
    611 
    612 }  // namespace native
    613