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 
known_device_locked(const wchar_t * dev_name)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 
known_device(const wchar_t * dev_name)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 
register_new_device(usb_handle * handle)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 
device_poll_thread()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 
_power_window_proc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam)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 
_power_notification_thread()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 
usb_init()251 void usb_init() {
252     std::thread(device_poll_thread).detach();
253     std::thread(_power_notification_thread).detach();
254 }
255 
usb_cleanup()256 void usb_cleanup() {
257     // On Windows, shutting down the server without releasing USB interfaces makes claiming
258     // them again unstable upon next startup.
259     if (is_libusb_enabled()) {
260         VLOG(USB) << "Windows libusb cleanup";
261         close_usb_devices();
262     }
263 }
264 
do_usb_open(const wchar_t * interface_name)265 usb_handle* do_usb_open(const wchar_t* interface_name) {
266     unsigned long name_len = 0;
267 
268     // Allocate our handle
269     usb_handle* ret = (usb_handle*)calloc(1, sizeof(usb_handle));
270     if (nullptr == ret) {
271         D("Could not allocate %u bytes for usb_handle: %s", sizeof(usb_handle), strerror(errno));
272         goto fail;
273     }
274 
275     // Create interface.
276     ret->adb_interface = AdbCreateInterfaceByName(interface_name);
277     if (nullptr == ret->adb_interface) {
278         D("AdbCreateInterfaceByName failed: %s",
279           android::base::SystemErrorCodeToString(GetLastError()).c_str());
280         goto fail;
281     }
282 
283     // Open read pipe (endpoint)
284     ret->adb_read_pipe = AdbOpenDefaultBulkReadEndpoint(
285         ret->adb_interface, AdbOpenAccessTypeReadWrite, AdbOpenSharingModeReadWrite);
286     if (nullptr == ret->adb_read_pipe) {
287         D("AdbOpenDefaultBulkReadEndpoint failed: %s",
288           android::base::SystemErrorCodeToString(GetLastError()).c_str());
289         goto fail;
290     }
291 
292     // Open write pipe (endpoint)
293     ret->adb_write_pipe = AdbOpenDefaultBulkWriteEndpoint(
294         ret->adb_interface, AdbOpenAccessTypeReadWrite, AdbOpenSharingModeReadWrite);
295     if (nullptr == ret->adb_write_pipe) {
296         D("AdbOpenDefaultBulkWriteEndpoint failed: %s",
297           android::base::SystemErrorCodeToString(GetLastError()).c_str());
298         goto fail;
299     }
300 
301     // Save interface name
302     // First get expected name length
303     AdbGetInterfaceName(ret->adb_interface, nullptr, &name_len, false);
304     if (0 == name_len) {
305         D("AdbGetInterfaceName returned name length of zero: %s",
306           android::base::SystemErrorCodeToString(GetLastError()).c_str());
307         goto fail;
308     }
309 
310     ret->interface_name = (wchar_t*)malloc(name_len * sizeof(ret->interface_name[0]));
311     if (nullptr == ret->interface_name) {
312         D("Could not allocate %lu characters for interface_name: %s", name_len, strerror(errno));
313         goto fail;
314     }
315 
316     // Now save the name
317     if (!AdbGetInterfaceName(ret->adb_interface, ret->interface_name, &name_len, false)) {
318         D("AdbGetInterfaceName failed: %s",
319           android::base::SystemErrorCodeToString(GetLastError()).c_str());
320         goto fail;
321     }
322 
323     // We're done at this point
324     return ret;
325 
326 fail:
327     if (nullptr != ret) {
328         usb_cleanup_handle(ret);
329         free(ret);
330     }
331 
332     return nullptr;
333 }
334 
usb_write(usb_handle * handle,const void * data,int len)335 int usb_write(usb_handle* handle, const void* data, int len) {
336     unsigned long time_out = 5000;
337     unsigned long written = 0;
338     int err = 0;
339 
340     D("usb_write %d", len);
341     if (nullptr == handle) {
342         D("usb_write was passed NULL handle");
343         err = EINVAL;
344         goto fail;
345     }
346 
347     // Perform write
348     if (!AdbWriteEndpointSync(handle->adb_write_pipe, (void*)data, (unsigned long)len, &written,
349                               time_out)) {
350         D("AdbWriteEndpointSync failed: %s",
351           android::base::SystemErrorCodeToString(GetLastError()).c_str());
352         err = EIO;
353         goto fail;
354     }
355 
356     // Make sure that we've written what we were asked to write
357     D("usb_write got: %ld, expected: %d", written, len);
358     if (written != (unsigned long)len) {
359         // If this occurs, this code should be changed to repeatedly call
360         // AdbWriteEndpointSync() until all bytes are written.
361         D("AdbWriteEndpointSync was supposed to write %d, but only wrote %ld", len, written);
362         err = EIO;
363         goto fail;
364     }
365 
366     if (handle->zero_mask && (len & handle->zero_mask) == 0) {
367         // Send a zero length packet
368         unsigned long dummy;
369         if (!AdbWriteEndpointSync(handle->adb_write_pipe, (void*)data, 0, &dummy, time_out)) {
370             D("AdbWriteEndpointSync of zero length packet failed: %s",
371               android::base::SystemErrorCodeToString(GetLastError()).c_str());
372             err = EIO;
373             goto fail;
374         }
375     }
376 
377     return written;
378 
379 fail:
380     // Any failure should cause us to kick the device instead of leaving it a
381     // zombie state with potential to hang.
382     if (nullptr != handle) {
383         D("Kicking device due to error in usb_write");
384         usb_kick(handle);
385     }
386 
387     D("usb_write failed");
388     errno = err;
389     return -1;
390 }
391 
usb_read(usb_handle * handle,void * data,int len)392 int usb_read(usb_handle* handle, void* data, int len) {
393     unsigned long time_out = 0;
394     unsigned long read = 0;
395     int err = 0;
396     int orig_len = len;
397 
398     D("usb_read %d", len);
399     if (nullptr == handle) {
400         D("usb_read was passed NULL handle");
401         err = EINVAL;
402         goto fail;
403     }
404 
405     while (len == orig_len) {
406         if (!AdbReadEndpointSync(handle->adb_read_pipe, data, len, &read, time_out)) {
407             D("AdbReadEndpointSync failed: %s",
408               android::base::SystemErrorCodeToString(GetLastError()).c_str());
409             err = EIO;
410             goto fail;
411         }
412         D("usb_read got: %ld, expected: %d", read, len);
413 
414         data = (char*)data + read;
415         len -= read;
416     }
417 
418     return orig_len - len;
419 
420 fail:
421     // Any failure should cause us to kick the device instead of leaving it a
422     // zombie state with potential to hang.
423     if (nullptr != handle) {
424         D("Kicking device due to error in usb_read");
425         usb_kick(handle);
426     }
427 
428     D("usb_read failed");
429     errno = err;
430     return -1;
431 }
432 
433 // Wrapper around AdbCloseHandle() that logs diagnostics.
_adb_close_handle(ADBAPIHANDLE adb_handle)434 static void _adb_close_handle(ADBAPIHANDLE adb_handle) {
435     if (!AdbCloseHandle(adb_handle)) {
436         D("AdbCloseHandle(%p) failed: %s", adb_handle,
437           android::base::SystemErrorCodeToString(GetLastError()).c_str());
438     }
439 }
440 
usb_cleanup_handle(usb_handle * handle)441 void usb_cleanup_handle(usb_handle* handle) {
442     D("usb_cleanup_handle");
443     if (nullptr != handle) {
444         if (nullptr != handle->interface_name) free(handle->interface_name);
445         // AdbCloseHandle(pipe) will break any threads out of pending IO calls and
446         // wait until the pipe no longer uses the interface. Then we can
447         // AdbCloseHandle() the interface.
448         if (nullptr != handle->adb_write_pipe) _adb_close_handle(handle->adb_write_pipe);
449         if (nullptr != handle->adb_read_pipe) _adb_close_handle(handle->adb_read_pipe);
450         if (nullptr != handle->adb_interface) _adb_close_handle(handle->adb_interface);
451 
452         handle->interface_name = nullptr;
453         handle->adb_write_pipe = nullptr;
454         handle->adb_read_pipe = nullptr;
455         handle->adb_interface = nullptr;
456     }
457 }
458 
usb_reset(usb_handle * handle)459 void usb_reset(usb_handle* handle) {
460     // Unimplemented on Windows.
461     usb_kick(handle);
462 }
463 
usb_kick_locked(usb_handle * handle)464 static void usb_kick_locked(usb_handle* handle) {
465     // The reason the lock must be acquired before calling this function is in
466     // case multiple threads are trying to kick the same device at the same time.
467     usb_cleanup_handle(handle);
468 }
469 
usb_kick(usb_handle * handle)470 void usb_kick(usb_handle* handle) {
471     D("usb_kick");
472     if (nullptr != handle) {
473         std::lock_guard<std::mutex> lock(usb_lock);
474         usb_kick_locked(handle);
475     } else {
476         errno = EINVAL;
477     }
478 }
479 
usb_close(usb_handle * handle)480 int usb_close(usb_handle* handle) {
481     D("usb_close");
482 
483     if (nullptr != handle) {
484         // Remove handle from the list
485         {
486             std::lock_guard<std::mutex> lock(usb_lock);
487             handle_list.erase(std::remove(handle_list.begin(), handle_list.end(), handle),
488                               handle_list.end());
489         }
490 
491         // Cleanup handle
492         usb_cleanup_handle(handle);
493         free(handle);
494     }
495 
496     return 0;
497 }
498 
usb_get_max_packet_size(usb_handle * handle)499 size_t usb_get_max_packet_size(usb_handle* handle) {
500     return handle->max_packet_size;
501 }
502 
recognized_device(usb_handle * handle)503 int recognized_device(usb_handle* handle) {
504     if (nullptr == handle) return 0;
505 
506     // Check vendor and product id first
507     USB_DEVICE_DESCRIPTOR device_desc;
508 
509     if (!AdbGetUsbDeviceDescriptor(handle->adb_interface, &device_desc)) {
510         D("AdbGetUsbDeviceDescriptor failed: %s",
511           android::base::SystemErrorCodeToString(GetLastError()).c_str());
512         return 0;
513     }
514 
515     // Then check interface properties
516     USB_INTERFACE_DESCRIPTOR interf_desc;
517 
518     if (!AdbGetUsbInterfaceDescriptor(handle->adb_interface, &interf_desc)) {
519         D("AdbGetUsbInterfaceDescriptor failed: %s",
520           android::base::SystemErrorCodeToString(GetLastError()).c_str());
521         return 0;
522     }
523 
524     // Must have two endpoints
525     if (2 != interf_desc.bNumEndpoints) {
526         return 0;
527     }
528 
529     if (!is_adb_interface(interf_desc.bInterfaceClass, interf_desc.bInterfaceSubClass,
530                           interf_desc.bInterfaceProtocol)) {
531         return 0;
532     }
533 
534     AdbEndpointInformation endpoint_info;
535     // assuming zero is a valid bulk endpoint ID
536     if (AdbGetEndpointInformation(handle->adb_interface, 0, &endpoint_info)) {
537         handle->max_packet_size = endpoint_info.max_packet_size;
538         handle->zero_mask = endpoint_info.max_packet_size - 1;
539         D("device zero_mask: 0x%x", handle->zero_mask);
540     } else {
541         D("AdbGetEndpointInformation failed: %s",
542           android::base::SystemErrorCodeToString(GetLastError()).c_str());
543     }
544 
545     return 1;
546 }
547 
find_devices()548 void find_devices() {
549     usb_handle* handle = nullptr;
550     char entry_buffer[2048];
551     AdbInterfaceInfo* next_interface = (AdbInterfaceInfo*)(&entry_buffer[0]);
552     unsigned long entry_buffer_size = sizeof(entry_buffer);
553 
554     // Enumerate all present and active interfaces.
555     ADBAPIHANDLE enum_handle = AdbEnumInterfaces(usb_class_id, true, true, true);
556 
557     if (nullptr == enum_handle) {
558         D("AdbEnumInterfaces failed: %s",
559           android::base::SystemErrorCodeToString(GetLastError()).c_str());
560         return;
561     }
562 
563     while (AdbNextInterface(enum_handle, next_interface, &entry_buffer_size)) {
564         // Lets see if we already have this device in the list
565         if (!known_device(next_interface->device_name)) {
566             // This seems to be a new device. Open it!
567             handle = do_usb_open(next_interface->device_name);
568             if (nullptr != handle) {
569                 // Lets see if this interface (device) belongs to us
570                 if (recognized_device(handle)) {
571                     D("adding a new device %ls", next_interface->device_name);
572 
573                     // We don't request a wchar_t string from AdbGetSerialNumber() because of a bug
574                     // in adb_winusb_interface.cpp:CopyMemory(buffer, ser_num->bString,
575                     // bytes_written) where the last parameter should be (str_len *
576                     // sizeof(wchar_t)). The bug reads 2 bytes past the end of a stack buffer in the
577                     // best case, and in the unlikely case of a long serial number, it will read 2
578                     // bytes past the end of a heap allocation. This doesn't affect the resulting
579                     // string, but we should avoid the bad reads in the first place.
580                     char serial_number[512];
581                     unsigned long serial_number_len = sizeof(serial_number);
582                     if (AdbGetSerialNumber(handle->adb_interface, serial_number, &serial_number_len,
583                                            true)) {
584                         if (!transport_server_owns_device(serial_number)) {
585                             // We aren't allowed to communicate with this device. Don't open this
586                             // device.
587                             D("ignoring device: not owned by this server serial: '%s'",
588                               serial_number);
589                             usb_cleanup_handle(handle);
590                             free(handle);
591                             return;
592                         }
593                         // Lets make sure that we don't duplicate this device
594                         if (register_new_device(handle)) {
595                             register_usb_transport(handle, serial_number, nullptr, 1);
596                         } else {
597                             D("register_new_device failed for %ls", next_interface->device_name);
598                             usb_cleanup_handle(handle);
599                             free(handle);
600                         }
601                     } else {
602                         D("cannot get serial number: %s",
603                           android::base::SystemErrorCodeToString(GetLastError()).c_str());
604                         usb_cleanup_handle(handle);
605                         free(handle);
606                     }
607                 } else {
608                     usb_cleanup_handle(handle);
609                     free(handle);
610                 }
611             }
612         }
613 
614         entry_buffer_size = sizeof(entry_buffer);
615     }
616 
617     if (GetLastError() != ERROR_NO_MORE_ITEMS) {
618         // Only ERROR_NO_MORE_ITEMS is expected at the end of enumeration.
619         D("AdbNextInterface failed: %s",
620           android::base::SystemErrorCodeToString(GetLastError()).c_str());
621     }
622 
623     _adb_close_handle(enum_handle);
624 }
625 
kick_devices()626 static void kick_devices() {
627     // Need to acquire lock to safely walk the list which might be modified
628     // by another thread.
629     std::lock_guard<std::mutex> lock(usb_lock);
630     for (usb_handle* usb : handle_list) {
631         usb_kick_locked(usb);
632     }
633 }
634