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