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 
63     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 
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 
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 
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 static bool FindUSBDevices() {
114     // Create the matching dictionary to find the Android device's adb interface.
115     CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBInterfaceClassName);
116     if (!matchingDict) {
117         LOG(ERROR) << "couldn't create USB matching dictionary";
118         return false;
119     }
120     // Create an iterator for all I/O Registry objects that match the dictionary.
121     io_iterator_t iter = 0;
122     kern_return_t kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter);
123     if (kr != KERN_SUCCESS) {
124         LOG(ERROR) << "failed to get matching services";
125         return false;
126     }
127     // Iterate over all matching objects.
128     AndroidInterfaceAdded(iter);
129     IOObjectRelease(iter);
130     return true;
131 }
132 
133 static void
134 AndroidInterfaceAdded(io_iterator_t iterator)
135 {
136     kern_return_t            kr;
137     io_service_t             usbDevice;
138     io_service_t             usbInterface;
139     IOCFPlugInInterface      **plugInInterface = NULL;
140     IOUSBInterfaceInterface500  **iface = NULL;
141     IOUSBDeviceInterface500  **dev = NULL;
142     HRESULT                  result;
143     SInt32                   score;
144     uint32_t                 locationId;
145     UInt8                    if_class, subclass, protocol;
146     UInt16                   vendor;
147     UInt16                   product;
148     UInt8                    serialIndex;
149     char                     serial[256];
150     std::string devpath;
151 
152     while ((usbInterface = IOIteratorNext(iterator))) {
153         //* Create an intermediate interface plugin
154         kr = IOCreatePlugInInterfaceForService(usbInterface,
155                                                kIOUSBInterfaceUserClientTypeID,
156                                                kIOCFPlugInInterfaceID,
157                                                &plugInInterface, &score);
158         IOObjectRelease(usbInterface);
159         if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
160             LOG(ERROR) << "Unable to create an interface plug-in (" << std::hex << kr << ")";
161             continue;
162         }
163 
164         //* This gets us the interface object
165         result = (*plugInInterface)->QueryInterface(
166             plugInInterface,
167             CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID500), (LPVOID*)&iface);
168         //* We only needed the plugin to get the interface, so discard it
169         (*plugInInterface)->Release(plugInInterface);
170         if (result || !iface) {
171             LOG(ERROR) << "Couldn't query the interface (" << std::hex << result << ")";
172             continue;
173         }
174 
175         kr = (*iface)->GetInterfaceClass(iface, &if_class);
176         kr = (*iface)->GetInterfaceSubClass(iface, &subclass);
177         kr = (*iface)->GetInterfaceProtocol(iface, &protocol);
178         if (!is_adb_interface(if_class, subclass, protocol)) {
179             // Ignore non-ADB devices.
180             LOG(DEBUG) << "Ignoring interface with incorrect class/subclass/protocol - " << if_class
181                        << ", " << subclass << ", " << protocol;
182             (*iface)->Release(iface);
183             continue;
184         }
185 
186         //* this gets us an ioservice, with which we will find the actual
187         //* device; after getting a plugin, and querying the interface, of
188         //* course.
189         //* Gotta love OS X
190         kr = (*iface)->GetDevice(iface, &usbDevice);
191         if (kIOReturnSuccess != kr || !usbDevice) {
192             LOG(ERROR) << "Couldn't grab device from interface (" << std::hex << kr << ")";
193             (*iface)->Release(iface);
194             continue;
195         }
196 
197         plugInInterface = NULL;
198         score = 0;
199         //* create an intermediate device plugin
200         kr = IOCreatePlugInInterfaceForService(usbDevice,
201                                                kIOUSBDeviceUserClientTypeID,
202                                                kIOCFPlugInInterfaceID,
203                                                &plugInInterface, &score);
204         //* only needed this to find the plugin
205         (void)IOObjectRelease(usbDevice);
206         if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
207             LOG(ERROR) << "Unable to create a device plug-in (" << std::hex << kr << ")";
208             (*iface)->Release(iface);
209             continue;
210         }
211 
212         result = (*plugInInterface)->QueryInterface(plugInInterface,
213             CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID500), (LPVOID*)&dev);
214         //* only needed this to query the plugin
215         (*plugInInterface)->Release(plugInInterface);
216         if (result || !dev) {
217             LOG(ERROR) << "Couldn't create a device interface (" << std::hex << result << ")";
218             (*iface)->Release(iface);
219             continue;
220         }
221 
222         //* Now after all that, we actually have a ref to the device and
223         //* the interface that matched our criteria
224         kr = (*dev)->GetDeviceVendor(dev, &vendor);
225         kr = (*dev)->GetDeviceProduct(dev, &product);
226         kr = (*dev)->GetLocationID(dev, &locationId);
227         if (kr == KERN_SUCCESS) {
228             devpath = android::base::StringPrintf("usb:%" PRIu32 "X", locationId);
229             if (IsKnownDevice(devpath)) {
230                 (*dev)->Release(dev);
231                 (*iface)->Release(iface);
232                 continue;
233             }
234         }
235         kr = (*dev)->USBGetSerialNumberStringIndex(dev, &serialIndex);
236 
237         if (serialIndex > 0) {
238             IOUSBDevRequest req;
239             UInt16          buffer[256];
240             UInt16          languages[128];
241 
242             memset(languages, 0, sizeof(languages));
243 
244             req.bmRequestType =
245                     USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
246             req.bRequest = kUSBRqGetDescriptor;
247             req.wValue = (kUSBStringDesc << 8) | 0;
248             req.wIndex = 0;
249             req.pData = languages;
250             req.wLength = sizeof(languages);
251             kr = (*dev)->DeviceRequest(dev, &req);
252 
253             if (kr == kIOReturnSuccess && req.wLenDone > 0) {
254 
255                 int langCount = (req.wLenDone - 2) / 2, lang;
256 
257                 for (lang = 1; lang <= langCount; lang++) {
258 
259                     memset(buffer, 0, sizeof(buffer));
260                     memset(&req, 0, sizeof(req));
261 
262                     req.bmRequestType =
263                             USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
264                     req.bRequest = kUSBRqGetDescriptor;
265                     req.wValue = (kUSBStringDesc << 8) | serialIndex;
266                     req.wIndex = languages[lang];
267                     req.pData = buffer;
268                     req.wLength = sizeof(buffer);
269                     kr = (*dev)->DeviceRequest(dev, &req);
270 
271                     if (kr == kIOReturnSuccess && req.wLenDone > 0) {
272                         int i, count;
273 
274                         // skip first word, and copy the rest to the serial string,
275                         // changing shorts to bytes.
276                         count = (req.wLenDone - 1) / 2;
277                         for (i = 0; i < count; i++)
278                                 serial[i] = buffer[i + 1];
279                         serial[i] = 0;
280                         break;
281                     }
282                 }
283             }
284         }
285 
286         (*dev)->Release(dev);
287 
288         VLOG(USB) << android::base::StringPrintf("Found vid=%04x pid=%04x serial=%s\n",
289                         vendor, product, serial);
290         if (devpath.empty()) {
291             devpath = serial;
292         }
293         if (IsKnownDevice(devpath)) {
294             (*iface)->USBInterfaceClose(iface);
295             (*iface)->Release(iface);
296             continue;
297         }
298 
299         std::unique_ptr<usb_handle> handle =
300             CheckInterface((IOUSBInterfaceInterface550**)iface, vendor, product);
301         if (handle == nullptr) {
302             LOG(ERROR) << "Could not find device interface";
303             (*iface)->Release(iface);
304             continue;
305         }
306         handle->devpath = devpath;
307         usb_handle* handle_p = handle.get();
308         VLOG(USB) << "Add usb device " << serial;
309         LOG(INFO) << "reported max packet size for " << serial << " is " << handle->max_packet_size;
310         AddDevice(std::move(handle));
311         register_usb_transport(reinterpret_cast<::usb_handle*>(handle_p), serial, devpath.c_str(),
312                                1);
313     }
314 }
315 
316 // Used to clear both the endpoints before starting.
317 // When adb quits, we might clear the host endpoint but not the device.
318 // So we make sure both sides are clear before starting up.
319 static bool ClearPipeStallBothEnds(IOUSBInterfaceInterface550** interface, UInt8 bulkEp) {
320     IOReturn rc = (*interface)->ClearPipeStallBothEnds(interface, bulkEp);
321     if (rc != kIOReturnSuccess) {
322         LOG(ERROR) << "Could not clear pipe stall both ends: " << std::hex << rc;
323         return false;
324     }
325     return true;
326 }
327 
328 //* TODO: simplify this further since we only register to get ADB interface
329 //* subclass+protocol events
330 static std::unique_ptr<usb_handle> CheckInterface(IOUSBInterfaceInterface550** interface,
331                                                   UInt16 vendor, UInt16 product) {
332     std::unique_ptr<usb_handle> handle;
333     IOReturn kr;
334     UInt8 interfaceNumEndpoints, interfaceClass, interfaceSubClass, interfaceProtocol;
335     UInt8 endpoint;
336 
337     //* Now open the interface.  This will cause the pipes associated with
338     //* the endpoints in the interface descriptor to be instantiated
339     kr = (*interface)->USBInterfaceOpen(interface);
340     if (kr != kIOReturnSuccess) {
341         LOG(ERROR) << "Could not open interface: " << std::hex << kr;
342         return NULL;
343     }
344 
345     //* Get the number of endpoints associated with this interface
346     kr = (*interface)->GetNumEndpoints(interface, &interfaceNumEndpoints);
347     if (kr != kIOReturnSuccess) {
348         LOG(ERROR) << "Unable to get number of endpoints: " << std::hex << kr;
349         goto err_get_num_ep;
350     }
351 
352     //* Get interface class, subclass and protocol
353     if ((*interface)->GetInterfaceClass(interface, &interfaceClass) != kIOReturnSuccess ||
354             (*interface)->GetInterfaceSubClass(interface, &interfaceSubClass) != kIOReturnSuccess ||
355             (*interface)->GetInterfaceProtocol(interface, &interfaceProtocol) != kIOReturnSuccess) {
356             LOG(ERROR) << "Unable to get interface class, subclass and protocol";
357             goto err_get_interface_class;
358     }
359 
360     //* check to make sure interface class, subclass and protocol match ADB
361     //* avoid opening mass storage endpoints
362     if (!is_adb_interface(interfaceClass, interfaceSubClass, interfaceProtocol)) {
363         goto err_bad_adb_interface;
364     }
365 
366     handle.reset(new usb_handle);
367     if (handle == nullptr) {
368         goto err_bad_adb_interface;
369     }
370 
371     //* Iterate over the endpoints for this interface and find the first
372     //* bulk in/out pipes available.  These will be our read/write pipes.
373     for (endpoint = 1; endpoint <= interfaceNumEndpoints; endpoint++) {
374         UInt8   transferType;
375         UInt16  maxPacketSize;
376         UInt8   interval;
377         UInt8   number;
378         UInt8   direction;
379         UInt8 maxBurst;
380         UInt8 mult;
381         UInt16 bytesPerInterval;
382 
383         kr = (*interface)
384                  ->GetPipePropertiesV2(interface, endpoint, &direction, &number, &transferType,
385                                        &maxPacketSize, &interval, &maxBurst, &mult,
386                                        &bytesPerInterval);
387         if (kr != kIOReturnSuccess) {
388             LOG(ERROR) << "FindDeviceInterface - could not get pipe properties: "
389                        << std::hex << kr;
390             goto err_get_pipe_props;
391         }
392 
393         if (kUSBBulk != transferType) continue;
394 
395         if (kUSBIn == direction) {
396             handle->bulkIn = endpoint;
397             if (!ClearPipeStallBothEnds(interface, handle->bulkIn)) goto err_get_pipe_props;
398         }
399 
400         if (kUSBOut == direction) {
401             handle->bulkOut = endpoint;
402             if (!ClearPipeStallBothEnds(interface, handle->bulkOut)) goto err_get_pipe_props;
403         }
404 
405         if (maxBurst != 0)
406             // bMaxBurst is the number of additional packets in the burst.
407             maxPacketSize /= (maxBurst + 1);
408 
409         // mult is only relevant for isochronous endpoints.
410         CHECK_EQ(0, mult);
411 
412         handle->zero_mask = maxPacketSize - 1;
413         handle->max_packet_size = maxPacketSize;
414     }
415 
416     handle->interface = interface;
417     return handle;
418 
419 err_get_pipe_props:
420 err_bad_adb_interface:
421 err_get_interface_class:
422 err_get_num_ep:
423     (*interface)->USBInterfaceClose(interface);
424     return nullptr;
425 }
426 
427 std::mutex& operate_device_lock = *new std::mutex();
428 
429 static void RunLoopThread() {
430     adb_thread_setname("RunLoop");
431 
432     VLOG(USB) << "RunLoopThread started";
433     while (true) {
434         {
435             std::lock_guard<std::mutex> lock_guard(operate_device_lock);
436             FindUSBDevices();
437             KickDisconnectedDevices();
438         }
439         // Signal the parent that we are running
440         usb_inited_flag = true;
441         std::this_thread::sleep_for(1s);
442     }
443     VLOG(USB) << "RunLoopThread done";
444 }
445 
446 void usb_cleanup() NO_THREAD_SAFETY_ANALYSIS {
447     VLOG(USB) << "usb_cleanup";
448     // Wait until usb operations in RunLoopThread finish, and prevent further operations.
449     operate_device_lock.lock();
450     close_usb_devices();
451 }
452 
453 void usb_init() {
454     static bool initialized = false;
455     if (!initialized) {
456         usb_inited_flag = false;
457 
458         std::thread(RunLoopThread).detach();
459 
460         // Wait for initialization to finish
461         while (!usb_inited_flag) {
462             std::this_thread::sleep_for(100ms);
463         }
464 
465         adb_notify_device_scan_complete();
466         initialized = true;
467     }
468 }
469 
470 int usb_write(usb_handle *handle, const void *buf, int len)
471 {
472     IOReturn    result;
473 
474     if (!len)
475         return 0;
476 
477     if (!handle || handle->dead)
478         return -1;
479 
480     if (NULL == handle->interface) {
481         LOG(ERROR) << "usb_write interface was null";
482         return -1;
483     }
484 
485     if (0 == handle->bulkOut) {
486         LOG(ERROR) << "bulkOut endpoint not assigned";
487         return -1;
488     }
489 
490     result =
491         (*handle->interface)->WritePipe(handle->interface, handle->bulkOut, (void *)buf, len);
492 
493     if ((result == 0) && (handle->zero_mask)) {
494         /* we need 0-markers and our transfer */
495         if(!(len & handle->zero_mask)) {
496             result =
497                 (*handle->interface)->WritePipe(
498                         handle->interface, handle->bulkOut, (void *)buf, 0);
499         }
500     }
501 
502     if (!result)
503         return len;
504 
505     LOG(ERROR) << "usb_write failed with status: " << std::hex << result;
506     return -1;
507 }
508 
509 int usb_read(usb_handle *handle, void *buf, int len)
510 {
511     IOReturn result;
512     UInt32  numBytes = len;
513 
514     if (!len) {
515         return 0;
516     }
517 
518     if (!handle || handle->dead) {
519         return -1;
520     }
521 
522     if (NULL == handle->interface) {
523         LOG(ERROR) << "usb_read interface was null";
524         return -1;
525     }
526 
527     if (0 == handle->bulkIn) {
528         LOG(ERROR) << "bulkIn endpoint not assigned";
529         return -1;
530     }
531 
532     result = (*handle->interface)->ReadPipe(handle->interface, handle->bulkIn, buf, &numBytes);
533 
534     if (kIOUSBPipeStalled == result) {
535         LOG(ERROR) << "Pipe stalled, clearing stall.\n";
536         (*handle->interface)->ClearPipeStall(handle->interface, handle->bulkIn);
537         result = (*handle->interface)->ReadPipe(handle->interface, handle->bulkIn, buf, &numBytes);
538     }
539 
540     if (kIOReturnSuccess == result)
541         return numBytes;
542     else {
543         LOG(ERROR) << "usb_read failed with status: " << std::hex << result;
544     }
545 
546     return -1;
547 }
548 
549 int usb_close(usb_handle *handle)
550 {
551     std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
552     for (auto it = g_usb_handles.begin(); it != g_usb_handles.end(); ++it) {
553         if ((*it).get() == handle) {
554             g_usb_handles.erase(it);
555             break;
556         }
557     }
558     return 0;
559 }
560 
561 void usb_reset(usb_handle* handle) {
562     // Unimplemented on OS X.
563     usb_kick(handle);
564 }
565 
566 static void usb_kick_locked(usb_handle *handle)
567 {
568     LOG(INFO) << "Kicking handle";
569     /* release the interface */
570     if (!handle)
571         return;
572 
573     if (!handle->dead)
574     {
575         handle->dead = true;
576         (*handle->interface)->USBInterfaceClose(handle->interface);
577         (*handle->interface)->Release(handle->interface);
578     }
579 }
580 
581 void usb_kick(usb_handle *handle) {
582     // Use the lock to avoid multiple thread kicking the device at the same time.
583     std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
584     usb_kick_locked(handle);
585 }
586 
587 size_t usb_get_max_packet_size(usb_handle* handle) {
588     return handle->max_packet_size;
589 }
590