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 #include <CoreFoundation/CoreFoundation.h>
24 
25 #include <IOKit/IOKitLib.h>
26 #include <IOKit/IOCFPlugIn.h>
27 #include <IOKit/usb/IOUSBLib.h>
28 #include <IOKit/IOMessage.h>
29 #include <mach/mach_port.h>
30 
31 #include <inttypes.h>
32 #include <stdio.h>
33 
34 #include <atomic>
35 #include <chrono>
36 #include <memory>
37 #include <mutex>
38 #include <thread>
39 #include <vector>
40 
41 #include <android-base/logging.h>
42 #include <android-base/stringprintf.h>
43 #include <android-base/thread_annotations.h>
44 
45 #include "adb.h"
46 #include "transport.h"
47 
48 using namespace std::chrono_literals;
49 
50 struct usb_handle
51 {
52     UInt8 bulkIn;
53     UInt8 bulkOut;
54     IOUSBInterfaceInterface550** interface;
55     unsigned int zero_mask;
56     size_t max_packet_size;
57 
58     // For garbage collecting disconnected devices.
59     bool mark;
60     std::string devpath;
61     std::atomic<bool> dead;
62 
usb_handleusb_handle63     usb_handle()
64         : bulkIn(0),
65           bulkOut(0),
66           interface(nullptr),
67           zero_mask(0),
68           max_packet_size(0),
69           mark(false),
70           dead(false) {}
71 };
72 
73 static std::atomic<bool> usb_inited_flag;
74 
75 static auto& g_usb_handles_mutex = *new std::mutex();
76 static auto& g_usb_handles = *new std::vector<std::unique_ptr<usb_handle>>();
77 
IsKnownDevice(const std::string & devpath)78 static bool IsKnownDevice(const std::string& devpath) {
79     std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
80     for (auto& usb : g_usb_handles) {
81         if (usb->devpath == devpath) {
82             // Set mark flag to indicate this device is still alive.
83             usb->mark = true;
84             return true;
85         }
86     }
87     return false;
88 }
89 
90 static void usb_kick_locked(usb_handle* handle);
91 
KickDisconnectedDevices()92 static void KickDisconnectedDevices() {
93     std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
94     for (auto& usb : g_usb_handles) {
95         if (!usb->mark) {
96             usb_kick_locked(usb.get());
97         } else {
98             usb->mark = false;
99         }
100     }
101 }
102 
AddDevice(std::unique_ptr<usb_handle> handle)103 static void AddDevice(std::unique_ptr<usb_handle> handle) {
104     handle->mark = true;
105     std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
106     g_usb_handles.push_back(std::move(handle));
107 }
108 
109 static void AndroidInterfaceAdded(io_iterator_t iterator);
110 static std::unique_ptr<usb_handle> CheckInterface(IOUSBInterfaceInterface550** iface, UInt16 vendor,
111                                                   UInt16 product);
112 
113 // Flag-guarded (using host env variable) feature that turns on
114 // the ability to clear the device-side endpoint also before
115 // starting. See public bug https://issuetracker.google.com/issues/37055927
116 // for historical context.
clear_endpoints()117 static bool clear_endpoints() {
118     static const char* env(getenv("ADB_OSX_USB_CLEAR_ENDPOINTS"));
119     static bool result = env && strcmp("1", env) == 0;
120     return result;
121 }
122 
FindUSBDevices()123 static bool FindUSBDevices() {
124     // Create the matching dictionary to find the Android device's adb interface.
125     CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBInterfaceClassName);
126     if (!matchingDict) {
127         LOG(ERROR) << "couldn't create USB matching dictionary";
128         return false;
129     }
130     // Create an iterator for all I/O Registry objects that match the dictionary.
131     io_iterator_t iter = 0;
132     kern_return_t kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter);
133     if (kr != KERN_SUCCESS) {
134         LOG(ERROR) << "failed to get matching services";
135         return false;
136     }
137     // Iterate over all matching objects.
138     AndroidInterfaceAdded(iter);
139     IOObjectRelease(iter);
140     return true;
141 }
142 
143 static void
AndroidInterfaceAdded(io_iterator_t iterator)144 AndroidInterfaceAdded(io_iterator_t iterator)
145 {
146     kern_return_t            kr;
147     io_service_t             usbDevice;
148     io_service_t             usbInterface;
149     IOCFPlugInInterface      **plugInInterface = NULL;
150     IOUSBInterfaceInterface500  **iface = NULL;
151     IOUSBDeviceInterface500  **dev = NULL;
152     HRESULT                  result;
153     SInt32                   score;
154     uint32_t                 locationId;
155     UInt8                    if_class, subclass, protocol;
156     UInt16                   vendor;
157     UInt16                   product;
158     UInt8                    serialIndex;
159     char                     serial[256];
160     std::string devpath;
161 
162     while ((usbInterface = IOIteratorNext(iterator))) {
163         //* Create an intermediate interface plugin
164         kr = IOCreatePlugInInterfaceForService(usbInterface,
165                                                kIOUSBInterfaceUserClientTypeID,
166                                                kIOCFPlugInInterfaceID,
167                                                &plugInInterface, &score);
168         IOObjectRelease(usbInterface);
169         if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
170             LOG(ERROR) << "Unable to create an interface plug-in (" << std::hex << kr << ")";
171             continue;
172         }
173 
174         //* This gets us the interface object
175         result = (*plugInInterface)->QueryInterface(
176             plugInInterface,
177             CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID500), (LPVOID*)&iface);
178         //* We only needed the plugin to get the interface, so discard it
179         (*plugInInterface)->Release(plugInInterface);
180         if (result || !iface) {
181             LOG(ERROR) << "Couldn't query the interface (" << std::hex << result << ")";
182             continue;
183         }
184 
185         kr = (*iface)->GetInterfaceClass(iface, &if_class);
186         kr = (*iface)->GetInterfaceSubClass(iface, &subclass);
187         kr = (*iface)->GetInterfaceProtocol(iface, &protocol);
188         if (!is_adb_interface(if_class, subclass, protocol)) {
189             // Ignore non-ADB devices (interface with incorrect
190             // class/subclass/protocol).
191             (*iface)->Release(iface);
192             continue;
193         }
194 
195         //* this gets us an ioservice, with which we will find the actual
196         //* device; after getting a plugin, and querying the interface, of
197         //* course.
198         //* Gotta love OS X
199         kr = (*iface)->GetDevice(iface, &usbDevice);
200         if (kIOReturnSuccess != kr || !usbDevice) {
201             LOG(ERROR) << "Couldn't grab device from interface (" << std::hex << kr << ")";
202             (*iface)->Release(iface);
203             continue;
204         }
205 
206         plugInInterface = NULL;
207         score = 0;
208         //* create an intermediate device plugin
209         kr = IOCreatePlugInInterfaceForService(usbDevice,
210                                                kIOUSBDeviceUserClientTypeID,
211                                                kIOCFPlugInInterfaceID,
212                                                &plugInInterface, &score);
213         //* only needed this to find the plugin
214         (void)IOObjectRelease(usbDevice);
215         if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
216             LOG(ERROR) << "Unable to create a device plug-in (" << std::hex << kr << ")";
217             (*iface)->Release(iface);
218             continue;
219         }
220 
221         result = (*plugInInterface)->QueryInterface(plugInInterface,
222             CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID500), (LPVOID*)&dev);
223         //* only needed this to query the plugin
224         (*plugInInterface)->Release(plugInInterface);
225         if (result || !dev) {
226             LOG(ERROR) << "Couldn't create a device interface (" << std::hex << result << ")";
227             (*iface)->Release(iface);
228             continue;
229         }
230 
231         //* Now after all that, we actually have a ref to the device and
232         //* the interface that matched our criteria
233         kr = (*dev)->GetDeviceVendor(dev, &vendor);
234         kr = (*dev)->GetDeviceProduct(dev, &product);
235         kr = (*dev)->GetLocationID(dev, &locationId);
236         if (kr == KERN_SUCCESS) {
237             devpath = android::base::StringPrintf("usb:%" PRIu32 "X", locationId);
238             if (IsKnownDevice(devpath)) {
239                 (*dev)->Release(dev);
240                 (*iface)->Release(iface);
241                 continue;
242             }
243         }
244         kr = (*dev)->USBGetSerialNumberStringIndex(dev, &serialIndex);
245 
246         if (serialIndex > 0) {
247             IOUSBDevRequest req;
248             UInt16          buffer[256];
249             UInt16          languages[128];
250 
251             memset(languages, 0, sizeof(languages));
252 
253             req.bmRequestType =
254                     USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
255             req.bRequest = kUSBRqGetDescriptor;
256             req.wValue = (kUSBStringDesc << 8) | 0;
257             req.wIndex = 0;
258             req.pData = languages;
259             req.wLength = sizeof(languages);
260             kr = (*dev)->DeviceRequest(dev, &req);
261 
262             if (kr == kIOReturnSuccess && req.wLenDone > 0) {
263 
264                 int langCount = (req.wLenDone - 2) / 2, lang;
265 
266                 for (lang = 1; lang <= langCount; lang++) {
267                     memset(buffer, 0, sizeof(buffer));
268                     memset(&req, 0, sizeof(req));
269 
270                     req.bmRequestType =
271                             USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
272                     req.bRequest = kUSBRqGetDescriptor;
273                     req.wValue = (kUSBStringDesc << 8) | serialIndex;
274                     req.wIndex = languages[lang];
275                     req.pData = buffer;
276                     req.wLength = sizeof(buffer);
277                     kr = (*dev)->DeviceRequest(dev, &req);
278 
279                     if (kr == kIOReturnSuccess && req.wLenDone > 0) {
280                         int i, count;
281 
282                         // skip first word, and copy the rest to the serial string,
283                         // changing shorts to bytes.
284                         count = (req.wLenDone - 1) / 2;
285                         for (i = 0; i < count; i++)
286                                 serial[i] = buffer[i + 1];
287                         serial[i] = 0;
288                         break;
289                     }
290                 }
291             }
292         }
293 
294         (*dev)->Release(dev);
295 
296         VLOG(USB) << android::base::StringPrintf("Found vid=%04x pid=%04x serial=%s\n",
297                         vendor, product, serial);
298         if (devpath.empty()) {
299             devpath = serial;
300         }
301         if (IsKnownDevice(devpath)) {
302             (*iface)->USBInterfaceClose(iface);
303             (*iface)->Release(iface);
304             continue;
305         }
306 
307         if (!transport_server_owns_device(devpath, serial)) {
308             // We aren't allowed to communicate with this device. Don't open this device.
309             D("ignoring device: not owned by this server dev_path: '%s', serial: '%s'",
310               devpath.c_str(), serial);
311             continue;
312         }
313 
314         std::unique_ptr<usb_handle> handle =
315             CheckInterface((IOUSBInterfaceInterface550**)iface, vendor, product);
316         if (handle == nullptr) {
317             LOG(ERROR) << "Could not find device interface";
318             (*iface)->Release(iface);
319             continue;
320         }
321         handle->devpath = devpath;
322         usb_handle* handle_p = handle.get();
323         VLOG(USB) << "Add usb device " << serial;
324         LOG(INFO) << "reported max packet size for " << serial << " is " << handle->max_packet_size;
325         AddDevice(std::move(handle));
326         register_usb_transport(reinterpret_cast<::usb_handle*>(handle_p), serial, devpath.c_str(),
327                                1);
328     }
329 }
330 
331 // Used to clear both the endpoints before starting.
332 // When adb quits, we might clear the host endpoint but not the device.
333 // So we make sure both sides are clear before starting up.
334 // Returns true if:
335 //      - the feature is disabled (OSX/host only)
336 //      - the feature is enabled and successfully clears both endpoints
337 // Returns false otherwise (if an error is encountered)
ClearPipeStallBothEnds(IOUSBInterfaceInterface550 ** interface,UInt8 bulkEp)338 static bool ClearPipeStallBothEnds(IOUSBInterfaceInterface550** interface, UInt8 bulkEp) {
339     // If feature-disabled, (silently) bypass clearing both
340     // endpoints (including device-side).
341     if (!clear_endpoints()) {
342         return true;
343     }
344 
345     IOReturn rc = (*interface)->ClearPipeStallBothEnds(interface, bulkEp);
346     if (rc != kIOReturnSuccess) {
347         LOG(ERROR) << "Could not clear pipe stall both ends: " << std::hex << rc;
348         return false;
349     }
350     return true;
351 }
352 
353 //* TODO: simplify this further since we only register to get ADB interface
354 //* subclass+protocol events
CheckInterface(IOUSBInterfaceInterface550 ** interface,UInt16 vendor,UInt16 product)355 static std::unique_ptr<usb_handle> CheckInterface(IOUSBInterfaceInterface550** interface,
356                                                   UInt16 vendor, UInt16 product) {
357     std::unique_ptr<usb_handle> handle;
358     IOReturn kr;
359     UInt8 interfaceNumEndpoints, interfaceClass, interfaceSubClass, interfaceProtocol;
360     UInt8 endpoint;
361 
362     //* Now open the interface.  This will cause the pipes associated with
363     //* the endpoints in the interface descriptor to be instantiated
364     kr = (*interface)->USBInterfaceOpen(interface);
365     if (kr != kIOReturnSuccess) {
366         LOG(ERROR) << "Could not open interface: " << std::hex << kr;
367         return NULL;
368     }
369 
370     //* Get the number of endpoints associated with this interface
371     kr = (*interface)->GetNumEndpoints(interface, &interfaceNumEndpoints);
372     if (kr != kIOReturnSuccess) {
373         LOG(ERROR) << "Unable to get number of endpoints: " << std::hex << kr;
374         goto err_get_num_ep;
375     }
376 
377     //* Get interface class, subclass and protocol
378     if ((*interface)->GetInterfaceClass(interface, &interfaceClass) != kIOReturnSuccess ||
379             (*interface)->GetInterfaceSubClass(interface, &interfaceSubClass) != kIOReturnSuccess ||
380             (*interface)->GetInterfaceProtocol(interface, &interfaceProtocol) != kIOReturnSuccess) {
381             LOG(ERROR) << "Unable to get interface class, subclass and protocol";
382             goto err_get_interface_class;
383     }
384 
385     //* check to make sure interface class, subclass and protocol match ADB
386     //* avoid opening mass storage endpoints
387     if (!is_adb_interface(interfaceClass, interfaceSubClass, interfaceProtocol)) {
388         goto err_bad_adb_interface;
389     }
390 
391     handle.reset(new usb_handle);
392     if (handle == nullptr) {
393         goto err_bad_adb_interface;
394     }
395 
396     //* Iterate over the endpoints for this interface and find the first
397     //* bulk in/out pipes available.  These will be our read/write pipes.
398     for (endpoint = 1; endpoint <= interfaceNumEndpoints; ++endpoint) {
399         UInt8   transferType;
400         UInt16  endPointMaxPacketSize = 0;
401         UInt8   interval;
402 
403         // Attempt to retrieve the 'true' packet-size from supported interface.
404         kr = (*interface)
405                  ->GetEndpointProperties(interface, 0, endpoint,
406                     kUSBOut,
407                     &transferType,
408                     &endPointMaxPacketSize, &interval);
409         if (kr == kIOReturnSuccess) {
410             CHECK_NE(0, endPointMaxPacketSize);
411         }
412 
413         UInt16  pipePropMaxPacketSize;
414         UInt8   number;
415         UInt8   direction;
416         UInt8 maxBurst;
417         UInt8 mult;
418         UInt16 bytesPerInterval;
419 
420         // Proceed with extracting the transfer direction, so we can fill in the
421         // appropriate fields (bulkIn or bulkOut).
422         kr = (*interface)->GetPipePropertiesV2(interface, endpoint,
423                                        &direction, &number, &transferType,
424                                        &pipePropMaxPacketSize, &interval,
425                                        &maxBurst, &mult,
426                                        &bytesPerInterval);
427         if (kr != kIOReturnSuccess) {
428             LOG(ERROR) << "FindDeviceInterface - could not get pipe properties: "
429                        << std::hex << kr;
430             goto err_get_pipe_props;
431         }
432 
433         if (kUSBBulk != transferType) continue;
434 
435         if (kUSBIn == direction) {
436             handle->bulkIn = endpoint;
437 
438             if (!ClearPipeStallBothEnds(interface, handle->bulkIn)) {
439                 goto err_get_pipe_props;
440             }
441         }
442 
443         if (kUSBOut == direction) {
444             handle->bulkOut = endpoint;
445 
446             if (!ClearPipeStallBothEnds(interface, handle->bulkOut)) {
447                 goto err_get_pipe_props;
448             }
449         }
450 
451         // Compute the packet-size, in case the system did not return the correct value.
452         if (endPointMaxPacketSize == 0 && maxBurst != 0) {
453             // bMaxBurst is the number of additional packets in the burst.
454             endPointMaxPacketSize = pipePropMaxPacketSize / (maxBurst + 1);
455         }
456 
457         // mult is only relevant for isochronous endpoints.
458         CHECK_EQ(0, mult);
459 
460         handle->zero_mask = endPointMaxPacketSize - 1;
461         handle->max_packet_size = endPointMaxPacketSize;
462     }
463 
464     handle->interface = interface;
465     return handle;
466 
467 err_get_pipe_props:
468 err_bad_adb_interface:
469 err_get_interface_class:
470 err_get_num_ep:
471     (*interface)->USBInterfaceClose(interface);
472     return nullptr;
473 }
474 
475 std::mutex& operate_device_lock = *new std::mutex();
476 
RunLoopThread()477 static void RunLoopThread() {
478     adb_thread_setname("RunLoop");
479 
480     VLOG(USB) << "RunLoopThread started";
481     while (true) {
482         {
483             std::lock_guard<std::mutex> lock_guard(operate_device_lock);
484             FindUSBDevices();
485             KickDisconnectedDevices();
486         }
487         // Signal the parent that we are running
488         usb_inited_flag = true;
489         std::this_thread::sleep_for(1s);
490     }
491     VLOG(USB) << "RunLoopThread done";
492 }
493 
usb_cleanup()494 void usb_cleanup() NO_THREAD_SAFETY_ANALYSIS {
495     VLOG(USB) << "usb_cleanup";
496     // Wait until usb operations in RunLoopThread finish, and prevent further operations.
497     operate_device_lock.lock();
498     close_usb_devices();
499 }
500 
usb_init()501 void usb_init() {
502     static bool initialized = false;
503     if (!initialized) {
504         usb_inited_flag = false;
505 
506         std::thread(RunLoopThread).detach();
507 
508         // Wait for initialization to finish
509         while (!usb_inited_flag) {
510             std::this_thread::sleep_for(100ms);
511         }
512 
513         adb_notify_device_scan_complete();
514         initialized = true;
515     }
516 }
517 
usb_write(usb_handle * handle,const void * buf,int len)518 int usb_write(usb_handle *handle, const void *buf, int len)
519 {
520     IOReturn    result;
521 
522     if (!len)
523         return 0;
524 
525     if (!handle || handle->dead)
526         return -1;
527 
528     if (NULL == handle->interface) {
529         LOG(ERROR) << "usb_write interface was null";
530         return -1;
531     }
532 
533     if (0 == handle->bulkOut) {
534         LOG(ERROR) << "bulkOut endpoint not assigned";
535         return -1;
536     }
537 
538     result =
539         (*handle->interface)->WritePipe(handle->interface, handle->bulkOut, (void *)buf, len);
540 
541     if ((result == 0) && (handle->zero_mask)) {
542         /* we need 0-markers and our transfer */
543         if(!(len & handle->zero_mask)) {
544             result =
545                 (*handle->interface)->WritePipe(
546                         handle->interface, handle->bulkOut, (void *)buf, 0);
547         }
548     }
549 
550     if (!result)
551         return len;
552 
553     LOG(ERROR) << "usb_write failed with status: " << std::hex << result;
554     return -1;
555 }
556 
usb_read(usb_handle * handle,void * buf,int len)557 int usb_read(usb_handle *handle, void *buf, int len)
558 {
559     IOReturn result;
560     UInt32  numBytes = len;
561 
562     if (!len) {
563         return 0;
564     }
565 
566     if (!handle || handle->dead) {
567         return -1;
568     }
569 
570     if (NULL == handle->interface) {
571         LOG(ERROR) << "usb_read interface was null";
572         return -1;
573     }
574 
575     if (0 == handle->bulkIn) {
576         LOG(ERROR) << "bulkIn endpoint not assigned";
577         return -1;
578     }
579 
580     result = (*handle->interface)->ReadPipe(handle->interface, handle->bulkIn, buf, &numBytes);
581 
582     if (kIOUSBPipeStalled == result) {
583         LOG(ERROR) << "Pipe stalled, clearing stall.\n";
584         (*handle->interface)->ClearPipeStall(handle->interface, handle->bulkIn);
585         result = (*handle->interface)->ReadPipe(handle->interface, handle->bulkIn, buf, &numBytes);
586     }
587 
588     if (kIOReturnSuccess == result)
589         return numBytes;
590     else {
591         LOG(ERROR) << "usb_read failed with status: " << std::hex << result;
592     }
593 
594     return -1;
595 }
596 
usb_close(usb_handle * handle)597 int usb_close(usb_handle *handle)
598 {
599     std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
600     for (auto it = g_usb_handles.begin(); it != g_usb_handles.end(); ++it) {
601         if ((*it).get() == handle) {
602             g_usb_handles.erase(it);
603             break;
604         }
605     }
606     return 0;
607 }
608 
usb_reset(usb_handle * handle)609 void usb_reset(usb_handle* handle) {
610     // Unimplemented on OS X.
611     usb_kick(handle);
612 }
613 
usb_kick_locked(usb_handle * handle)614 static void usb_kick_locked(usb_handle *handle)
615 {
616     LOG(INFO) << "Kicking handle";
617     /* release the interface */
618     if (!handle)
619         return;
620 
621     if (!handle->dead)
622     {
623         handle->dead = true;
624         (*handle->interface)->USBInterfaceClose(handle->interface);
625         (*handle->interface)->Release(handle->interface);
626     }
627 }
628 
usb_kick(usb_handle * handle)629 void usb_kick(usb_handle *handle) {
630     // Use the lock to avoid multiple thread kicking the device at the same time.
631     std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
632     usb_kick_locked(handle);
633 }
634 
usb_get_max_packet_size(usb_handle * handle)635 size_t usb_get_max_packet_size(usb_handle* handle) {
636     return handle->max_packet_size;
637 }
638