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