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