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