Home | History | Annotate | Download | only in adb
      1 /*
      2  * Copyright (C) 2009 bsdroid project
      3  *               Alexey Tarasov <tarasov (at) dodologics.com>
      4  *
      5  * Copyright (C) 2007 The Android Open Source Project
      6  *
      7  * Licensed under the Apache License, Version 2.0 (the "License");
      8  * you may not use this file except in compliance with the License.
      9  * You may obtain a copy of the License at
     10  *
     11  *      http://www.apache.org/licenses/LICENSE-2.0
     12  *
     13  * Unless required by applicable law or agreed to in writing, software
     14  * distributed under the License is distributed on an "AS IS" BASIS,
     15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     16  * See the License for the specific language governing permissions and
     17  * limitations under the License.
     18  */
     19 
     20 #include <sys/endian.h>
     21 #include <sys/ioctl.h>
     22 #include <sys/types.h>
     23 #include <sys/uio.h>
     24 
     25 #include <err.h>
     26 #include <errno.h>
     27 #include <poll.h>
     28 #include <stdio.h>
     29 #include <stdlib.h>
     30 #include <strings.h>
     31 #include <string.h>
     32 #include <sysexits.h>
     33 #include <unistd.h>
     34 #include <libusb.h>
     35 #include "sysdeps.h"
     36 
     37 #define   TRACE_TAG  TRACE_USB
     38 #include "adb.h"
     39 
     40 static adb_mutex_t usb_lock = ADB_MUTEX_INITIALIZER;
     41 static libusb_context *ctx = NULL;
     42 
     43 struct usb_handle
     44 {
     45     usb_handle            *prev;
     46     usb_handle            *next;
     47 
     48     libusb_device         *dev;
     49     libusb_device_handle  *devh;
     50     int                   interface;
     51     uint8_t               dev_bus;
     52     uint8_t               dev_addr;
     53 
     54     int                   zero_mask;
     55     unsigned char         end_point_address[2];
     56     char                  serial[128];
     57 
     58     adb_cond_t            notify;
     59     adb_mutex_t           lock;
     60 };
     61 
     62 static struct usb_handle handle_list = {
     63         .prev = &handle_list,
     64         .next = &handle_list,
     65 };
     66 
     67 void
     68 usb_cleanup()
     69 {
     70 	libusb_exit(ctx);
     71 }
     72 
     73 void
     74 report_bulk_libusb_error(int r)
     75 {
     76     switch (r) {
     77     case LIBUSB_ERROR_TIMEOUT:
     78         D("Transfer timeout\n");
     79         break;
     80 
     81     case LIBUSB_ERROR_PIPE:
     82         D("Control request is not supported\n");
     83         break;
     84 
     85     case LIBUSB_ERROR_OVERFLOW:
     86         D("Device offered more data\n");
     87         break;
     88 
     89     case LIBUSB_ERROR_NO_DEVICE :
     90         D("Device was disconnected\n");
     91         break;
     92 
     93     default:
     94         D("Error %d during transfer\n", r);
     95         break;
     96     };
     97 }
     98 
     99 static int
    100 usb_bulk_write(usb_handle *uh, const void *data, int len)
    101 {
    102     int r = 0;
    103     int transferred = 0;
    104 
    105     r = libusb_bulk_transfer(uh->devh, uh->end_point_address[1], (void *)data, len,
    106                              &transferred, 0);
    107 
    108     if (r != 0) {
    109         D("usb_bulk_write(): ");
    110         report_bulk_libusb_error(r);
    111         return r;
    112     }
    113 
    114     return (transferred);
    115 }
    116 
    117 static int
    118 usb_bulk_read(usb_handle *uh, void *data, int len)
    119 {
    120     int r = 0;
    121     int transferred = 0;
    122 
    123     r = libusb_bulk_transfer(uh->devh, uh->end_point_address[0], data, len,
    124                              &transferred, 0);
    125 
    126     if (r != 0) {
    127         D("usb_bulk_read(): ");
    128         report_bulk_libusb_error(r);
    129         return r;
    130     }
    131 
    132     return (transferred);
    133 }
    134 
    135 int
    136 usb_write(struct usb_handle *uh, const void *_data, int len)
    137 {
    138     unsigned char *data = (unsigned char*) _data;
    139     int n;
    140     int need_zero = 0;
    141 
    142     if (uh->zero_mask == 1) {
    143         if (!(len & uh->zero_mask)) {
    144             need_zero = 1;
    145         }
    146     }
    147 
    148     D("usb_write(): %p:%d -> transport %p\n", _data, len, uh);
    149 
    150     while (len > 0) {
    151         int xfer = (len > 4096) ? 4096 : len;
    152 
    153         n = usb_bulk_write(uh, data, xfer);
    154 
    155         if (n != xfer) {
    156             D("usb_write(): failed for transport %p (%d bytes left)\n", uh, len);
    157             return -1;
    158         }
    159 
    160         len -= xfer;
    161         data += xfer;
    162     }
    163 
    164     if (need_zero){
    165         n = usb_bulk_write(uh, _data, 0);
    166 
    167         if (n < 0) {
    168             D("usb_write(): failed to finish operation for transport %p\n", uh);
    169         }
    170         return n;
    171     }
    172 
    173     return 0;
    174 }
    175 
    176 int
    177 usb_read(struct usb_handle *uh, void *_data, int len)
    178 {
    179     unsigned char *data = (unsigned char*) _data;
    180     int n;
    181 
    182     D("usb_read(): %p:%d <- transport %p\n", _data, len, uh);
    183 
    184     while (len > 0) {
    185         int xfer = (len > 4096) ? 4096 : len;
    186 
    187         n = usb_bulk_read(uh, data, xfer);
    188 
    189         if (n != xfer) {
    190             if (n > 0) {
    191                 data += n;
    192                 len -= n;
    193                 continue;
    194             }
    195 
    196             D("usb_read(): failed for transport %p (%d bytes left)\n", uh, len);
    197             return -1;
    198         }
    199 
    200         len -= xfer;
    201         data += xfer;
    202     }
    203 
    204     return 0;
    205  }
    206 
    207 int
    208 usb_close(struct usb_handle *h)
    209 {
    210     D("usb_close(): closing transport %p\n", h);
    211     adb_mutex_lock(&usb_lock);
    212 
    213     h->next->prev = h->prev;
    214     h->prev->next = h->next;
    215     h->prev = NULL;
    216     h->next = NULL;
    217 
    218     libusb_release_interface(h->devh, h->interface);
    219     libusb_close(h->devh);
    220     libusb_unref_device(h->dev);
    221 
    222     adb_mutex_unlock(&usb_lock);
    223 
    224     free(h);
    225 
    226     return (0);
    227 }
    228 
    229 void usb_kick(struct usb_handle *h)
    230 {
    231     D("usb_cick(): kicking transport %p\n", h);
    232 
    233     adb_mutex_lock(&h->lock);
    234     unregister_usb_transport(h);
    235     adb_mutex_unlock(&h->lock);
    236 
    237     h->next->prev = h->prev;
    238     h->prev->next = h->next;
    239     h->prev = NULL;
    240     h->next = NULL;
    241 
    242     libusb_release_interface(h->devh, h->interface);
    243     libusb_close(h->devh);
    244     libusb_unref_device(h->dev);
    245     free(h);
    246 }
    247 
    248 int
    249 check_usb_interface(libusb_interface *interface,
    250                     libusb_device_descriptor *desc,
    251                     struct usb_handle *uh)
    252 {
    253     int e;
    254 
    255     if (interface->num_altsetting == 0) {
    256         D("check_usb_interface(): No interface settings\n");
    257         return -1;
    258     }
    259 
    260     libusb_interface_descriptor *idesc = &interface->altsetting[0];
    261 
    262     if (idesc->bNumEndpoints != 2) {
    263         D("check_usb_interface(): Interface have not 2 endpoints, ignoring\n");
    264         return -1;
    265     }
    266 
    267     for (e = 0; e < idesc->bNumEndpoints; e++) {
    268         libusb_endpoint_descriptor *edesc = &idesc->endpoint[e];
    269 
    270         if (edesc->bmAttributes != LIBUSB_TRANSFER_TYPE_BULK) {
    271             D("check_usb_interface(): Endpoint (%u) is not bulk (%u), ignoring\n",
    272                     edesc->bmAttributes, LIBUSB_TRANSFER_TYPE_BULK);
    273             return -1;
    274         }
    275 
    276         if (edesc->bEndpointAddress & LIBUSB_ENDPOINT_IN)
    277             uh->end_point_address[0] = edesc->bEndpointAddress;
    278         else
    279             uh->end_point_address[1] = edesc->bEndpointAddress;
    280 
    281             /* aproto 01 needs 0 termination */
    282         if (idesc->bInterfaceProtocol == 0x01) {
    283             uh->zero_mask = edesc->wMaxPacketSize - 1;
    284             D("check_usb_interface(): Forced Android interface protocol v.1\n");
    285         }
    286     }
    287 
    288     D("check_usb_interface(): Device: %04x:%04x "
    289       "iclass: %x, isclass: %x, iproto: %x ep: %x/%x-> ",
    290         desc->idVendor, desc->idProduct, idesc->bInterfaceClass,
    291 	idesc->bInterfaceSubClass, idesc->bInterfaceProtocol,
    292 	uh->end_point_address[0], uh->end_point_address[1]);
    293 
    294     if (!is_adb_interface(desc->idVendor, desc->idProduct,
    295             idesc->bInterfaceClass, idesc->bInterfaceSubClass,
    296             idesc->bInterfaceProtocol))
    297     {
    298         D("not matches\n");
    299         return -1;
    300     }
    301 
    302     D("matches\n");
    303     return 1;
    304 }
    305 
    306 int
    307 check_usb_interfaces(libusb_config_descriptor *config,
    308                      libusb_device_descriptor *desc, struct usb_handle *uh)
    309 {
    310     int i;
    311 
    312     for (i = 0; i < config->bNumInterfaces; ++i) {
    313         if (check_usb_interface(&config->interface[i], desc, uh) != -1) {
    314             /* found some interface and saved information about it */
    315             D("check_usb_interfaces(): Interface %d of %04x:%04x "
    316               "matches Android device\n", i, desc->idVendor,
    317 	      desc->idProduct);
    318 
    319             return  i;
    320         }
    321     }
    322 
    323     return -1;
    324 }
    325 
    326 int
    327 register_device(struct usb_handle *uh, const char *serial)
    328 {
    329     D("register_device(): Registering %p [%s] as USB transport\n",
    330        uh, serial);
    331 
    332     struct usb_handle *usb= NULL;
    333 
    334     usb = calloc(1, sizeof(struct usb_handle));
    335     memcpy(usb, uh, sizeof(struct usb_handle));
    336     strcpy(usb->serial, uh->serial);
    337 
    338     adb_cond_init(&usb->notify, 0);
    339     adb_mutex_init(&usb->lock, 0);
    340 
    341     adb_mutex_lock(&usb_lock);
    342 
    343     usb->next = &handle_list;
    344     usb->prev = handle_list.prev;
    345     usb->prev->next = usb;
    346     usb->next->prev = usb;
    347 
    348     adb_mutex_unlock(&usb_lock);
    349 
    350     register_usb_transport(usb, serial, NULL, 1);
    351 
    352     return (1);
    353 }
    354 
    355 int
    356 already_registered(usb_handle *uh)
    357 {
    358     struct usb_handle *usb= NULL;
    359     int exists = 0;
    360 
    361     adb_mutex_lock(&usb_lock);
    362 
    363     for (usb = handle_list.next; usb != &handle_list; usb = usb->next) {
    364         if ((usb->dev_bus == uh->dev_bus) &&
    365             (usb->dev_addr == uh->dev_addr))
    366         {
    367             exists = 1;
    368             break;
    369         }
    370     }
    371 
    372     adb_mutex_unlock(&usb_lock);
    373 
    374     return exists;
    375 }
    376 
    377 void
    378 check_device(libusb_device *dev)
    379 {
    380     struct usb_handle uh;
    381     int i = 0;
    382     int found = -1;
    383     char serial[256] = {0};
    384 
    385     libusb_device_descriptor desc;
    386     libusb_config_descriptor *config = NULL;
    387 
    388     int r = libusb_get_device_descriptor(dev, &desc);
    389 
    390     if (r != LIBUSB_SUCCESS) {
    391         D("check_device(): Failed to get device descriptor\n");
    392         return;
    393     }
    394 
    395     if ((desc.idVendor == 0) && (desc.idProduct == 0))
    396         return;
    397 
    398     D("check_device(): Probing usb device %04x:%04x\n",
    399         desc.idVendor, desc.idProduct);
    400 
    401     if (!is_adb_interface (desc.idVendor, desc.idProduct,
    402                            ADB_CLASS, ADB_SUBCLASS, ADB_PROTOCOL))
    403     {
    404         D("check_device(): Ignored due unknown vendor id\n");
    405         return;
    406     }
    407 
    408     uh.dev_bus = libusb_get_bus_number(dev);
    409     uh.dev_addr = libusb_get_device_address(dev);
    410 
    411     if (already_registered(&uh)) {
    412         D("check_device(): Device (bus: %d, address: %d) "
    413           "is already registered\n", uh.dev_bus, uh.dev_addr);
    414         return;
    415     }
    416 
    417     D("check_device(): Device bus: %d, address: %d\n",
    418         uh.dev_bus, uh.dev_addr);
    419 
    420     r = libusb_get_active_config_descriptor(dev, &config);
    421 
    422     if (r != 0) {
    423         if (r == LIBUSB_ERROR_NOT_FOUND) {
    424             D("check_device(): Device %4x:%4x is unconfigured\n",
    425                 desc.idVendor, desc.idProduct);
    426             return;
    427         }
    428 
    429         D("check_device(): Failed to get configuration for %4x:%4x\n",
    430             desc.idVendor, desc.idProduct);
    431         return;
    432     }
    433 
    434     if (config == NULL) {
    435         D("check_device(): Sanity check failed after "
    436           "getting active config\n");
    437         return;
    438     }
    439 
    440     if (config->interface != NULL) {
    441         found = check_usb_interfaces(config, &desc, &uh);
    442     }
    443 
    444     /* not needed anymore */
    445     libusb_free_config_descriptor(config);
    446 
    447     r = libusb_open(dev, &uh.devh);
    448     uh.dev = dev;
    449 
    450     if (r != 0) {
    451         switch (r) {
    452             case LIBUSB_ERROR_NO_MEM:
    453                 D("check_device(): Memory allocation problem\n");
    454                 break;
    455 
    456             case LIBUSB_ERROR_ACCESS:
    457                 D("check_device(): Permissions problem, "
    458                   "current user priveleges are messed up?\n");
    459                 break;
    460 
    461             case LIBUSB_ERROR_NO_DEVICE:
    462                 D("check_device(): Device disconected, bad cable?\n");
    463                 break;
    464 
    465             default:
    466                 D("check_device(): libusb triggered error %d\n", r);
    467         }
    468         // skip rest
    469         found = -1;
    470     }
    471 
    472     if (found >= 0) {
    473         D("check_device(): Device matches Android interface\n");
    474         // read the device's serial number
    475         memset(serial, 0, sizeof(serial));
    476         uh.interface = found;
    477 
    478         r = libusb_claim_interface(uh.devh, uh.interface);
    479 
    480         if (r < 0) {
    481             D("check_device(): Failed to claim interface %d\n",
    482                 uh.interface);
    483 
    484             goto fail;
    485         }
    486 
    487         if (desc.iSerialNumber) {
    488             // reading serial
    489             uint16_t    buffer[128] = {0};
    490             uint16_t    languages[128] = {0};
    491             int languageCount = 0;
    492 
    493             memset(languages, 0, sizeof(languages));
    494             r = libusb_control_transfer(uh.devh,
    495                 LIBUSB_ENDPOINT_IN |  LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
    496                 LIBUSB_REQUEST_GET_DESCRIPTOR, LIBUSB_DT_STRING << 8,
    497 		0, (uint8_t *)languages, sizeof(languages), 0);
    498 
    499             if (r <= 0) {
    500                 D("check_device(): Failed to get languages count\n");
    501                 goto fail;
    502             }
    503 
    504             languageCount = (r - 2) / 2;
    505 
    506             for (i = 1; i <= languageCount; ++i) {
    507                 memset(buffer, 0, sizeof(buffer));
    508 
    509                 r = libusb_control_transfer(uh.devh,
    510                     LIBUSB_ENDPOINT_IN |  LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
    511                     LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_STRING << 8) | desc.iSerialNumber,
    512 		    languages[i], (uint8_t *)buffer, sizeof(buffer), 0);
    513 
    514                 if (r > 0) { /* converting serial */
    515                     int j = 0;
    516                     r /= 2;
    517 
    518                     for (j = 1; j < r; ++j)
    519                         serial[j - 1] = buffer[j];
    520 
    521                     serial[j - 1] = '\0';
    522                     break; /* languagesCount cycle */
    523                 }
    524             }
    525 
    526             if (register_device(&uh, serial) == 0) {
    527                 D("check_device(): Failed to register device\n");
    528                 goto fail_interface;
    529             }
    530 
    531             libusb_ref_device(dev);
    532         }
    533     }
    534 
    535     return;
    536 
    537 fail_interface:
    538     libusb_release_interface(uh.devh, uh.interface);
    539 
    540 fail:
    541     libusb_close(uh.devh);
    542     uh.devh = NULL;
    543 }
    544 
    545 int
    546 check_device_connected(struct usb_handle *uh)
    547 {
    548     int r = libusb_kernel_driver_active(uh->devh, uh->interface);
    549 
    550     if (r == LIBUSB_ERROR_NO_DEVICE)
    551         return 0;
    552 
    553     if (r < 0)
    554         return -1;
    555 
    556     return 1;
    557 }
    558 
    559 void
    560 kick_disconnected()
    561 {
    562     struct usb_handle *usb= NULL;
    563 
    564     adb_mutex_lock(&usb_lock);
    565 
    566     for (usb = handle_list.next; usb != &handle_list; usb = usb->next) {
    567 
    568         if (check_device_connected(usb) == 0) {
    569             D("kick_disconnected(): Transport %p is not online anymore\n",
    570                 usb);
    571 
    572             usb_kick(usb);
    573         }
    574     }
    575 
    576     adb_mutex_unlock(&usb_lock);
    577 }
    578 
    579 void
    580 scan_usb_devices()
    581 {
    582     D("scan_usb_devices(): started\n");
    583 
    584     libusb_device **devs= NULL;
    585     libusb_device *dev= NULL;
    586     ssize_t cnt = libusb_get_device_list(ctx, &devs);
    587 
    588     if (cnt < 0) {
    589         D("scan_usb_devices(): Failed to get device list (error: %d)\n",
    590             cnt);
    591 
    592         return;
    593     }
    594 
    595     int i = 0;
    596 
    597     while ((dev = devs[i++]) != NULL) {
    598         check_device(dev);
    599     }
    600 
    601     libusb_free_device_list(devs, 1);
    602 }
    603 
    604 void *
    605 device_poll_thread(void* unused)
    606 {
    607     D("device_poll_thread(): Created USB scan thread\n");
    608 
    609     for (;;) {
    610         sleep(5);
    611         kick_disconnected();
    612         scan_usb_devices();
    613     }
    614 
    615     /* never reaching this point */
    616     return (NULL);
    617 }
    618 
    619 static void
    620 sigalrm_handler(int signo)
    621 {
    622     /* nothing */
    623 }
    624 
    625 void
    626 usb_init()
    627 {
    628     D("usb_init(): started\n");
    629     adb_thread_t        tid;
    630     struct sigaction actions;
    631 
    632     int r = libusb_init(&ctx);
    633 
    634     if (r != LIBUSB_SUCCESS) {
    635         err(EX_IOERR, "Failed to init libusb\n");
    636     }
    637 
    638     memset(&actions, 0, sizeof(actions));
    639 
    640     sigemptyset(&actions.sa_mask);
    641 
    642     actions.sa_flags = 0;
    643     actions.sa_handler = sigalrm_handler;
    644 
    645     sigaction(SIGALRM, &actions, NULL);
    646 
    647 	/* initial device scan */
    648 	scan_usb_devices();
    649 
    650 	/* starting USB event polling thread */
    651     if (adb_thread_create(&tid, device_poll_thread, NULL)) {
    652             err(EX_IOERR, "cannot create USB scan thread\n");
    653     }
    654 
    655     D("usb_init(): finished\n");
    656 }
    657 
    658