Home | History | Annotate | Download | only in adb
      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 #include <winsock2.h>
     18 #include <windows.h>
     19 #include <winerror.h>
     20 #include <errno.h>
     21 #include <usb100.h>
     22 #include <adb_api.h>
     23 #include <stdio.h>
     24 
     25 #include "sysdeps.h"
     26 
     27 #define   TRACE_TAG  TRACE_USB
     28 #include "adb.h"
     29 
     30 /** Structure usb_handle describes our connection to the usb device via
     31   AdbWinApi.dll. This structure is returned from usb_open() routine and
     32   is expected in each subsequent call that is accessing the device.
     33 */
     34 struct usb_handle {
     35   /// Previous entry in the list of opened usb handles
     36   usb_handle *prev;
     37 
     38   /// Next entry in the list of opened usb handles
     39   usb_handle *next;
     40 
     41   /// Handle to USB interface
     42   ADBAPIHANDLE  adb_interface;
     43 
     44   /// Handle to USB read pipe (endpoint)
     45   ADBAPIHANDLE  adb_read_pipe;
     46 
     47   /// Handle to USB write pipe (endpoint)
     48   ADBAPIHANDLE  adb_write_pipe;
     49 
     50   /// Interface name
     51   char*         interface_name;
     52 
     53   /// Mask for determining when to use zero length packets
     54   unsigned zero_mask;
     55 };
     56 
     57 /// Class ID assigned to the device by androidusb.sys
     58 static const GUID usb_class_id = ANDROID_USB_CLASS_ID;
     59 
     60 /// List of opened usb handles
     61 static usb_handle handle_list = {
     62   .prev = &handle_list,
     63   .next = &handle_list,
     64 };
     65 
     66 /// Locker for the list of opened usb handles
     67 ADB_MUTEX_DEFINE( usb_lock );
     68 
     69 /// Checks if there is opened usb handle in handle_list for this device.
     70 int known_device(const char* dev_name);
     71 
     72 /// Checks if there is opened usb handle in handle_list for this device.
     73 /// usb_lock mutex must be held before calling this routine.
     74 int known_device_locked(const char* dev_name);
     75 
     76 /// Registers opened usb handle (adds it to handle_list).
     77 int register_new_device(usb_handle* handle);
     78 
     79 /// Checks if interface (device) matches certain criteria
     80 int recognized_device(usb_handle* handle);
     81 
     82 /// Enumerates present and available interfaces (devices), opens new ones and
     83 /// registers usb transport for them.
     84 void find_devices();
     85 
     86 /// Entry point for thread that polls (every second) for new usb interfaces.
     87 /// This routine calls find_devices in infinite loop.
     88 void* device_poll_thread(void* unused);
     89 
     90 /// Initializes this module
     91 void usb_init();
     92 
     93 /// Cleans up this module
     94 void usb_cleanup();
     95 
     96 /// Opens usb interface (device) by interface (device) name.
     97 usb_handle* do_usb_open(const wchar_t* interface_name);
     98 
     99 /// Writes data to the opened usb handle
    100 int usb_write(usb_handle* handle, const void* data, int len);
    101 
    102 /// Reads data using the opened usb handle
    103 int usb_read(usb_handle *handle, void* data, int len);
    104 
    105 /// Cleans up opened usb handle
    106 void usb_cleanup_handle(usb_handle* handle);
    107 
    108 /// Cleans up (but don't close) opened usb handle
    109 void usb_kick(usb_handle* handle);
    110 
    111 /// Closes opened usb handle
    112 int usb_close(usb_handle* handle);
    113 
    114 /// Gets interface (device) name for an opened usb handle
    115 const char *usb_name(usb_handle* handle);
    116 
    117 int known_device_locked(const char* dev_name) {
    118   usb_handle* usb;
    119 
    120   if (NULL != dev_name) {
    121     // Iterate through the list looking for the name match.
    122     for(usb = handle_list.next; usb != &handle_list; usb = usb->next) {
    123       // In Windows names are not case sensetive!
    124       if((NULL != usb->interface_name) &&
    125          (0 == stricmp(usb->interface_name, dev_name))) {
    126         return 1;
    127       }
    128     }
    129   }
    130 
    131   return 0;
    132 }
    133 
    134 int known_device(const char* dev_name) {
    135   int ret = 0;
    136 
    137   if (NULL != dev_name) {
    138     adb_mutex_lock(&usb_lock);
    139     ret = known_device_locked(dev_name);
    140     adb_mutex_unlock(&usb_lock);
    141   }
    142 
    143   return ret;
    144 }
    145 
    146 int register_new_device(usb_handle* handle) {
    147   if (NULL == handle)
    148     return 0;
    149 
    150   adb_mutex_lock(&usb_lock);
    151 
    152   // Check if device is already in the list
    153   if (known_device_locked(handle->interface_name)) {
    154     adb_mutex_unlock(&usb_lock);
    155     return 0;
    156   }
    157 
    158   // Not in the list. Add this handle to the list.
    159   handle->next = &handle_list;
    160   handle->prev = handle_list.prev;
    161   handle->prev->next = handle;
    162   handle->next->prev = handle;
    163 
    164   adb_mutex_unlock(&usb_lock);
    165 
    166   return 1;
    167 }
    168 
    169 void* device_poll_thread(void* unused) {
    170   D("Created device thread\n");
    171 
    172   while(1) {
    173     find_devices();
    174     adb_sleep_ms(1000);
    175   }
    176 
    177   return NULL;
    178 }
    179 
    180 void usb_init() {
    181   adb_thread_t tid;
    182 
    183   if(adb_thread_create(&tid, device_poll_thread, NULL)) {
    184     fatal_errno("cannot create input thread");
    185   }
    186 }
    187 
    188 void usb_cleanup() {
    189 }
    190 
    191 usb_handle* do_usb_open(const wchar_t* interface_name) {
    192   // Allocate our handle
    193   usb_handle* ret = (usb_handle*)malloc(sizeof(usb_handle));
    194   if (NULL == ret)
    195     return NULL;
    196 
    197   // Set linkers back to the handle
    198   ret->next = ret;
    199   ret->prev = ret;
    200 
    201   // Create interface.
    202   ret->adb_interface = AdbCreateInterfaceByName(interface_name);
    203 
    204   if (NULL == ret->adb_interface) {
    205     free(ret);
    206     errno = GetLastError();
    207     return NULL;
    208   }
    209 
    210   // Open read pipe (endpoint)
    211   ret->adb_read_pipe =
    212     AdbOpenDefaultBulkReadEndpoint(ret->adb_interface,
    213                                    AdbOpenAccessTypeReadWrite,
    214                                    AdbOpenSharingModeReadWrite);
    215   if (NULL != ret->adb_read_pipe) {
    216     // Open write pipe (endpoint)
    217     ret->adb_write_pipe =
    218       AdbOpenDefaultBulkWriteEndpoint(ret->adb_interface,
    219                                       AdbOpenAccessTypeReadWrite,
    220                                       AdbOpenSharingModeReadWrite);
    221     if (NULL != ret->adb_write_pipe) {
    222       // Save interface name
    223       unsigned long name_len = 0;
    224 
    225       // First get expected name length
    226       AdbGetInterfaceName(ret->adb_interface,
    227                           NULL,
    228                           &name_len,
    229                           true);
    230       if (0 != name_len) {
    231         ret->interface_name = (char*)malloc(name_len);
    232 
    233         if (NULL != ret->interface_name) {
    234           // Now save the name
    235           if (AdbGetInterfaceName(ret->adb_interface,
    236                                   ret->interface_name,
    237                                   &name_len,
    238                                   true)) {
    239             // We're done at this point
    240             return ret;
    241           }
    242         } else {
    243           SetLastError(ERROR_OUTOFMEMORY);
    244         }
    245       }
    246     }
    247   }
    248 
    249   // Something went wrong.
    250   int saved_errno = GetLastError();
    251   usb_cleanup_handle(ret);
    252   free(ret);
    253   SetLastError(saved_errno);
    254 
    255   return NULL;
    256 }
    257 
    258 int usb_write(usb_handle* handle, const void* data, int len) {
    259   unsigned long time_out = 5000;
    260   unsigned long written = 0;
    261   int ret;
    262 
    263   D("usb_write %d\n", len);
    264   if (NULL != handle) {
    265     // Perform write
    266     ret = AdbWriteEndpointSync(handle->adb_write_pipe,
    267                                (void*)data,
    268                                (unsigned long)len,
    269                                &written,
    270                                time_out);
    271     int saved_errno = GetLastError();
    272 
    273     if (ret) {
    274       // Make sure that we've written what we were asked to write
    275       D("usb_write got: %ld, expected: %d\n", written, len);
    276       if (written == (unsigned long)len) {
    277         if(handle->zero_mask && (len & handle->zero_mask) == 0) {
    278           // Send a zero length packet
    279           AdbWriteEndpointSync(handle->adb_write_pipe,
    280                                (void*)data,
    281                                0,
    282                                &written,
    283                                time_out);
    284         }
    285         return 0;
    286       }
    287     } else {
    288       // assume ERROR_INVALID_HANDLE indicates we are disconnected
    289       if (saved_errno == ERROR_INVALID_HANDLE)
    290         usb_kick(handle);
    291     }
    292     errno = saved_errno;
    293   } else {
    294     D("usb_write NULL handle\n");
    295     SetLastError(ERROR_INVALID_HANDLE);
    296   }
    297 
    298   D("usb_write failed: %d\n", errno);
    299 
    300   return -1;
    301 }
    302 
    303 int usb_read(usb_handle *handle, void* data, int len) {
    304   unsigned long time_out = 0;
    305   unsigned long read = 0;
    306   int ret;
    307 
    308   D("usb_read %d\n", len);
    309   if (NULL != handle) {
    310     while (len > 0) {
    311       int xfer = (len > 4096) ? 4096 : len;
    312 
    313       ret = AdbReadEndpointSync(handle->adb_read_pipe,
    314                                   data,
    315                                   (unsigned long)xfer,
    316                                   &read,
    317                                   time_out);
    318       int saved_errno = GetLastError();
    319       D("usb_write got: %ld, expected: %d, errno: %d\n", read, xfer, saved_errno);
    320       if (ret) {
    321         data = (char *)data + read;
    322         len -= read;
    323 
    324         if (len == 0)
    325           return 0;
    326       } else {
    327         // assume ERROR_INVALID_HANDLE indicates we are disconnected
    328         if (saved_errno == ERROR_INVALID_HANDLE)
    329           usb_kick(handle);
    330         break;
    331       }
    332       errno = saved_errno;
    333     }
    334   } else {
    335     D("usb_read NULL handle\n");
    336     SetLastError(ERROR_INVALID_HANDLE);
    337   }
    338 
    339   D("usb_read failed: %d\n", errno);
    340 
    341   return -1;
    342 }
    343 
    344 void usb_cleanup_handle(usb_handle* handle) {
    345   if (NULL != handle) {
    346     if (NULL != handle->interface_name)
    347       free(handle->interface_name);
    348     if (NULL != handle->adb_write_pipe)
    349       AdbCloseHandle(handle->adb_write_pipe);
    350     if (NULL != handle->adb_read_pipe)
    351       AdbCloseHandle(handle->adb_read_pipe);
    352     if (NULL != handle->adb_interface)
    353       AdbCloseHandle(handle->adb_interface);
    354 
    355     handle->interface_name = NULL;
    356     handle->adb_write_pipe = NULL;
    357     handle->adb_read_pipe = NULL;
    358     handle->adb_interface = NULL;
    359   }
    360 }
    361 
    362 void usb_kick(usb_handle* handle) {
    363   if (NULL != handle) {
    364     adb_mutex_lock(&usb_lock);
    365 
    366     usb_cleanup_handle(handle);
    367 
    368     adb_mutex_unlock(&usb_lock);
    369   } else {
    370     SetLastError(ERROR_INVALID_HANDLE);
    371     errno = ERROR_INVALID_HANDLE;
    372   }
    373 }
    374 
    375 int usb_close(usb_handle* handle) {
    376   D("usb_close\n");
    377 
    378   if (NULL != handle) {
    379     // Remove handle from the list
    380     adb_mutex_lock(&usb_lock);
    381 
    382     if ((handle->next != handle) && (handle->prev != handle)) {
    383       handle->next->prev = handle->prev;
    384       handle->prev->next = handle->next;
    385       handle->prev = handle;
    386       handle->next = handle;
    387     }
    388 
    389     adb_mutex_unlock(&usb_lock);
    390 
    391     // Cleanup handle
    392     usb_cleanup_handle(handle);
    393     free(handle);
    394   }
    395 
    396   return 0;
    397 }
    398 
    399 const char *usb_name(usb_handle* handle) {
    400   if (NULL == handle) {
    401     SetLastError(ERROR_INVALID_HANDLE);
    402     errno = ERROR_INVALID_HANDLE;
    403     return NULL;
    404   }
    405 
    406   return (const char*)handle->interface_name;
    407 }
    408 
    409 int recognized_device(usb_handle* handle) {
    410   if (NULL == handle)
    411     return 0;
    412 
    413   // Check vendor and product id first
    414   USB_DEVICE_DESCRIPTOR device_desc;
    415 
    416   if (!AdbGetUsbDeviceDescriptor(handle->adb_interface,
    417                                  &device_desc)) {
    418     return 0;
    419   }
    420 
    421   // Then check interface properties
    422   USB_INTERFACE_DESCRIPTOR interf_desc;
    423 
    424   if (!AdbGetUsbInterfaceDescriptor(handle->adb_interface,
    425                                     &interf_desc)) {
    426     return 0;
    427   }
    428 
    429   // Must have two endpoints
    430   if (2 != interf_desc.bNumEndpoints) {
    431     return 0;
    432   }
    433 
    434   if (is_adb_interface(device_desc.idVendor, device_desc.idProduct,
    435       interf_desc.bInterfaceClass, interf_desc.bInterfaceSubClass, interf_desc.bInterfaceProtocol)) {
    436 
    437     if(interf_desc.bInterfaceProtocol == 0x01) {
    438       AdbEndpointInformation endpoint_info;
    439       // assuming zero is a valid bulk endpoint ID
    440       if (AdbGetEndpointInformation(handle->adb_interface, 0, &endpoint_info)) {
    441         handle->zero_mask = endpoint_info.max_packet_size - 1;
    442       }
    443     }
    444 
    445     return 1;
    446   }
    447 
    448   return 0;
    449 }
    450 
    451 void find_devices() {
    452         usb_handle* handle = NULL;
    453   char entry_buffer[2048];
    454   char interf_name[2048];
    455   AdbInterfaceInfo* next_interface = (AdbInterfaceInfo*)(&entry_buffer[0]);
    456   unsigned long entry_buffer_size = sizeof(entry_buffer);
    457   char* copy_name;
    458 
    459   // Enumerate all present and active interfaces.
    460   ADBAPIHANDLE enum_handle =
    461     AdbEnumInterfaces(usb_class_id, true, true, true);
    462 
    463   if (NULL == enum_handle)
    464     return;
    465 
    466   while (AdbNextInterface(enum_handle, next_interface, &entry_buffer_size)) {
    467     // TODO: FIXME - temp hack converting wchar_t into char.
    468     // It would be better to change AdbNextInterface so it will return
    469     // interface name as single char string.
    470     const wchar_t* wchar_name = next_interface->device_name;
    471     for(copy_name = interf_name;
    472         L'\0' != *wchar_name;
    473         wchar_name++, copy_name++) {
    474       *copy_name = (char)(*wchar_name);
    475     }
    476     *copy_name = '\0';
    477 
    478     // Lets see if we already have this device in the list
    479     if (!known_device(interf_name)) {
    480       // This seems to be a new device. Open it!
    481         handle = do_usb_open(next_interface->device_name);
    482         if (NULL != handle) {
    483         // Lets see if this interface (device) belongs to us
    484         if (recognized_device(handle)) {
    485           D("adding a new device %s\n", interf_name);
    486           char serial_number[512];
    487           unsigned long serial_number_len = sizeof(serial_number);
    488           if (AdbGetSerialNumber(handle->adb_interface,
    489                                 serial_number,
    490                                 &serial_number_len,
    491                                 true)) {
    492             // Lets make sure that we don't duplicate this device
    493             if (register_new_device(handle)) {
    494               register_usb_transport(handle, serial_number, NULL, 1);
    495             } else {
    496               D("register_new_device failed for %s\n", interf_name);
    497               usb_cleanup_handle(handle);
    498               free(handle);
    499             }
    500           } else {
    501             D("cannot get serial number\n");
    502             usb_cleanup_handle(handle);
    503             free(handle);
    504           }
    505         } else {
    506           usb_cleanup_handle(handle);
    507           free(handle);
    508         }
    509       }
    510     }
    511 
    512     entry_buffer_size = sizeof(entry_buffer);
    513   }
    514 
    515   AdbCloseHandle(enum_handle);
    516 }
    517