gadget.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. # Copyright 2014 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Generic USB gadget functionality.
  5. """
  6. from __future__ import print_function
  7. import struct
  8. import msos20_descriptors
  9. import usb_constants
  10. import usb_descriptors
  11. class Gadget(object):
  12. """Basic functionality for a USB device.
  13. Implements standard control requests assuming that a subclass will handle
  14. class- or vendor-specific requests.
  15. """
  16. def __init__(self, device_desc, fs_config_desc, hs_config_desc):
  17. """Create a USB gadget device.
  18. Args:
  19. device_desc: USB device descriptor.
  20. fs_config_desc: Low/full-speed device descriptor.
  21. hs_config_desc: High-speed device descriptor.
  22. """
  23. self._speed = usb_constants.Speed.UNKNOWN
  24. self._chip = None
  25. self._device_desc = device_desc
  26. self._fs_config_desc = fs_config_desc
  27. self._hs_config_desc = hs_config_desc
  28. # dict mapping language codes to a dict mapping indexes to strings
  29. self._strings = {}
  30. self._bos_descriptor = None
  31. # dict mapping interface numbers to a set of endpoint addresses
  32. self._active_endpoints = {}
  33. # dict mapping endpoint addresses to interfaces
  34. self._endpoint_interface_map = {}
  35. self._ms_vendor_code_v1 = None
  36. self._ms_vendor_code_v2 = None
  37. self._ms_compat_ids = {}
  38. self._ms_os20_config_subset = None
  39. def GetDeviceDescriptor(self):
  40. return self._device_desc
  41. def GetFullSpeedConfigurationDescriptor(self):
  42. return self._fs_config_desc
  43. def GetHighSpeedConfigurationDescriptor(self):
  44. return self._hs_config_desc
  45. def GetConfigurationDescriptor(self):
  46. if self._speed == usb_constants.Speed.FULL:
  47. return self._fs_config_desc
  48. elif self._speed == usb_constants.Speed.HIGH:
  49. return self._hs_config_desc
  50. else:
  51. raise RuntimeError('Device is not connected.')
  52. def GetSpeed(self):
  53. return self._speed
  54. def AddStringDescriptor(self, index, value, lang=0x0409):
  55. """Add a string descriptor to this device.
  56. Args:
  57. index: String descriptor index (matches 'i' fields in descriptors).
  58. value: The string.
  59. lang: Language code (default: English).
  60. Raises:
  61. ValueError: The index or language code is invalid.
  62. """
  63. if index < 1 or index > 255:
  64. raise ValueError('String descriptor index out of range.')
  65. if lang < 0 or lang > 0xffff:
  66. raise ValueError('String descriptor language code out of range.')
  67. lang_strings = self._strings.setdefault(lang, {})
  68. lang_strings[index] = value
  69. def EnableMicrosoftOSDescriptorsV1(self, vendor_code=0x01):
  70. if vendor_code < 0 or vendor_code > 255:
  71. raise ValueError('Vendor code out of range.')
  72. if vendor_code == self._ms_vendor_code_v1:
  73. raise ValueError('OS Descriptor v1 vendor code conflicts with v2.')
  74. self._ms_vendor_code_v1 = vendor_code
  75. def EnableMicrosoftOSDescriptorsV2(self, vendor_code=0x02):
  76. if vendor_code < 0 or vendor_code > 255:
  77. raise ValueError('Vendor code out of range.')
  78. if vendor_code == self._ms_vendor_code_v1:
  79. raise ValueError('OS Descriptor v2 vendor code conflicts with v1.')
  80. self._ms_vendor_code_v2 = vendor_code
  81. self._ms_os20_descriptor_set = \
  82. msos20_descriptors.DescriptorSetHeader(dwWindowsVersion=0x06030000)
  83. # Gadget devices currently only support one configuration. Contrary to
  84. # Microsoft's documentation the bConfigurationValue field should be set to
  85. # the index passed to GET_DESCRIPTOR that returned the configuration instead
  86. # of the configuration's bConfigurationValue field. (i.e. 0 instead of 1).
  87. #
  88. # https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/ae64282c-3bc3-49af-8391-4d174479d9e7/microsoft-os-20-descriptors-not-working-on-an-interface-of-a-composite-usb-device
  89. self._ms_os20_config_subset = msos20_descriptors.ConfigurationSubsetHeader(
  90. bConfigurationValue=0)
  91. self._ms_os20_descriptor_set.Add(self._ms_os20_config_subset)
  92. self._ms_os20_platform_descriptor = \
  93. msos20_descriptors.PlatformCapabilityDescriptor(
  94. dwWindowsVersion=0x06030000,
  95. bMS_VendorCode=self._ms_vendor_code_v2)
  96. self._ms_os20_platform_descriptor.SetDescriptorSet(
  97. self._ms_os20_descriptor_set)
  98. self.AddDeviceCapabilityDescriptor(self._ms_os20_platform_descriptor)
  99. def SetMicrosoftCompatId(self, interface_number, compat_id, sub_compat_id=''):
  100. self._ms_compat_ids[interface_number] = (compat_id, sub_compat_id)
  101. if self._ms_os20_config_subset is not None:
  102. function_header = msos20_descriptors.FunctionSubsetHeader(
  103. bFirstInterface=interface_number)
  104. function_header.Add(msos20_descriptors.CompatibleId(
  105. CompatibleID=compat_id, SubCompatibleID=sub_compat_id))
  106. self._ms_os20_config_subset.Add(function_header)
  107. def AddDeviceCapabilityDescriptor(self, device_capability):
  108. """Add a device capability descriptor to this device.
  109. Args:
  110. device_capability: The Descriptor object.
  111. """
  112. if self._bos_descriptor is None:
  113. self._bos_descriptor = usb_descriptors.BosDescriptor()
  114. self._bos_descriptor.AddDeviceCapability(device_capability)
  115. def Connected(self, chip, speed):
  116. """The device has been connected to a USB host.
  117. Args:
  118. chip: USB controller.
  119. speed: Connection speed.
  120. """
  121. self._speed = speed
  122. self._chip = chip
  123. def Disconnected(self):
  124. """The device has been disconnected from the USB host."""
  125. self._speed = usb_constants.Speed.UNKNOWN
  126. self._chip = None
  127. self._active_endpoints.clear()
  128. self._endpoint_interface_map.clear()
  129. def IsConnected(self):
  130. return self._chip is not None
  131. def ControlRead(self, request_type, request, value, index, length):
  132. """Handle a read on the control pipe (endpoint zero).
  133. Args:
  134. request_type: bmRequestType field of the setup packet.
  135. request: bRequest field of the setup packet.
  136. value: wValue field of the setup packet.
  137. index: wIndex field of the setup packet.
  138. length: Maximum amount of data the host expects the device to return.
  139. Returns:
  140. A buffer to return to the USB host with len <= length on success or
  141. None to stall the pipe.
  142. """
  143. assert request_type & usb_constants.Dir.IN
  144. typ = request_type & usb_constants.Type.MASK
  145. recipient = request_type & usb_constants.Recipient.MASK
  146. if typ == usb_constants.Type.STANDARD:
  147. return self.StandardControlRead(
  148. recipient, request, value, index, length)
  149. elif typ == usb_constants.Type.CLASS:
  150. return self.ClassControlRead(
  151. recipient, request, value, index, length)
  152. elif typ == usb_constants.Type.VENDOR:
  153. return self.VendorControlRead(
  154. recipient, request, value, index, length)
  155. def ControlWrite(self, request_type, request, value, index, data):
  156. """Handle a write to the control pipe (endpoint zero).
  157. Args:
  158. request_type: bmRequestType field of the setup packet.
  159. request: bRequest field of the setup packet.
  160. value: wValue field of the setup packet.
  161. index: wIndex field of the setup packet.
  162. data: Data stage of the request.
  163. Returns:
  164. True on success, None to stall the pipe.
  165. """
  166. assert not request_type & usb_constants.Dir.IN
  167. typ = request_type & usb_constants.Type.MASK
  168. recipient = request_type & usb_constants.Recipient.MASK
  169. if typ == usb_constants.Type.STANDARD:
  170. return self.StandardControlWrite(
  171. recipient, request, value, index, data)
  172. elif typ == usb_constants.Type.CLASS:
  173. return self.ClassControlWrite(
  174. recipient, request, value, index, data)
  175. elif typ == usb_constants.Type.VENDOR:
  176. return self.VendorControlWrite(
  177. recipient, request, value, index, data)
  178. def SendPacket(self, endpoint, data):
  179. """Send a data packet on the given endpoint.
  180. Args:
  181. endpoint: Endpoint address.
  182. data: Data buffer.
  183. Raises:
  184. ValueError: If the endpoint address is not valid.
  185. RuntimeError: If the device is not connected.
  186. """
  187. if self._chip is None:
  188. raise RuntimeError('Device is not connected.')
  189. if not endpoint & usb_constants.Dir.IN:
  190. raise ValueError('Cannot write to non-input endpoint.')
  191. self._chip.SendPacket(endpoint, data)
  192. def ReceivePacket(self, endpoint, data):
  193. """Handle an incoming data packet on one of the device's active endpoints.
  194. This method should be overridden by a subclass implementing endpoint-based
  195. data transfers.
  196. Args:
  197. endpoint: Endpoint address.
  198. data: Data buffer.
  199. """
  200. pass
  201. def HaltEndpoint(self, endpoint):
  202. """Signals a STALL condition to the host on the given endpoint.
  203. Args:
  204. endpoint: Endpoint address.
  205. """
  206. self._chip.HaltEndpoint(endpoint)
  207. def StandardControlRead(self, recipient, request, value, index, length):
  208. """Handle standard control transfers.
  209. Args:
  210. recipient: Request recipient (device, interface, endpoint, etc.)
  211. request: bRequest field of the setup packet.
  212. value: wValue field of the setup packet.
  213. index: wIndex field of the setup packet.
  214. length: Maximum amount of data the host expects the device to return.
  215. Returns:
  216. A buffer to return to the USB host with len <= length on success or
  217. None to stall the pipe.
  218. """
  219. if recipient == usb_constants.Recipient.DEVICE:
  220. if request == usb_constants.Request.GET_DESCRIPTOR:
  221. desc_type = value >> 8
  222. desc_index = value & 0xff
  223. desc_lang = index
  224. print('GetDescriptor(recipient={}, type={}, index={}, lang={})'.format(
  225. recipient, desc_type, desc_index, desc_lang))
  226. return self.GetDescriptor(recipient, desc_type, desc_index, desc_lang,
  227. length)
  228. def GetDescriptor(self, recipient, typ, index, lang, length):
  229. """Handle a standard GET_DESCRIPTOR request.
  230. See Universal Serial Bus Specification Revision 2.0 section 9.4.3.
  231. Args:
  232. recipient: Request recipient (device, interface, endpoint, etc.)
  233. typ: Descriptor type.
  234. index: Descriptor index.
  235. lang: Descriptor language code.
  236. length: Maximum amount of data the host expects the device to return.
  237. Returns:
  238. The value of the descriptor or None to stall the pipe.
  239. """
  240. if typ == usb_constants.DescriptorType.STRING:
  241. return self.GetStringDescriptor(index, lang, length)
  242. elif typ == usb_constants.DescriptorType.BOS:
  243. return self.GetBosDescriptor(length)
  244. def ClassControlRead(self, recipient, request, value, index, length):
  245. """Handle class-specific control transfers.
  246. This function should be overridden by a subclass implementing a particular
  247. device class.
  248. Args:
  249. recipient: Request recipient (device, interface, endpoint, etc.)
  250. request: bRequest field of the setup packet.
  251. value: wValue field of the setup packet.
  252. index: wIndex field of the setup packet.
  253. length: Maximum amount of data the host expects the device to return.
  254. Returns:
  255. A buffer to return to the USB host with len <= length on success or
  256. None to stall the pipe.
  257. """
  258. _ = recipient, request, value, index, length
  259. return None
  260. def VendorControlRead(self, recipient, request, value, index, length):
  261. """Handle vendor-specific control transfers.
  262. This function should be overridden by a subclass if implementing a device
  263. that responds to vendor-specific requests.
  264. Args:
  265. recipient: Request recipient (device, interface, endpoint, etc.)
  266. request: bRequest field of the setup packet.
  267. value: wValue field of the setup packet.
  268. index: wIndex field of the setup packet.
  269. length: Maximum amount of data the host expects the device to return.
  270. Returns:
  271. A buffer to return to the USB host with len <= length on success or
  272. None to stall the pipe.
  273. """
  274. if (self._ms_vendor_code_v1 is not None and
  275. request == self._ms_vendor_code_v1 and
  276. (recipient == usb_constants.Recipient.DEVICE or
  277. recipient == usb_constants.Recipient.INTERFACE)):
  278. return self.GetMicrosoftOSDescriptorV1(recipient, value, index, length)
  279. if (self._ms_vendor_code_v2 is not None and
  280. request == self._ms_vendor_code_v2 and
  281. recipient == usb_constants.Recipient.DEVICE and
  282. value == 0x0000 and
  283. index == 0x0007):
  284. return self.GetMicrosoftOSDescriptorV2(length)
  285. return None
  286. def StandardControlWrite(self, recipient, request, value, index, data):
  287. """Handle standard control transfers.
  288. Args:
  289. recipient: Request recipient (device, interface, endpoint, etc.)
  290. request: bRequest field of the setup packet.
  291. value: wValue field of the setup packet.
  292. index: wIndex field of the setup packet.
  293. data: Data stage of the request.
  294. Returns:
  295. True on success, None to stall the pipe.
  296. """
  297. _ = data
  298. if request == usb_constants.Request.SET_CONFIGURATION:
  299. if recipient == usb_constants.Recipient.DEVICE:
  300. return self.SetConfiguration(value)
  301. elif request == usb_constants.Request.SET_INTERFACE:
  302. if recipient == usb_constants.Recipient.INTERFACE:
  303. return self.SetInterface(index, value)
  304. def ClassControlWrite(self, recipient, request, value, index, data):
  305. """Handle class-specific control transfers.
  306. This function should be overridden by a subclass implementing a particular
  307. device class.
  308. Args:
  309. recipient: Request recipient (device, interface, endpoint, etc.)
  310. request: bRequest field of the setup packet.
  311. value: wValue field of the setup packet.
  312. index: wIndex field of the setup packet.
  313. data: Data stage of the request.
  314. Returns:
  315. True on success, None to stall the pipe.
  316. """
  317. _ = recipient, request, value, index, data
  318. return None
  319. def VendorControlWrite(self, recipient, request, value, index, data):
  320. """Handle vendor-specific control transfers.
  321. This function should be overridden by a subclass if implementing a device
  322. that responds to vendor-specific requests.
  323. Args:
  324. recipient: Request recipient (device, interface, endpoint, etc.)
  325. request: bRequest field of the setup packet.
  326. value: wValue field of the setup packet.
  327. index: wIndex field of the setup packet.
  328. data: Data stage of the request.
  329. Returns:
  330. True on success, None to stall the pipe.
  331. """
  332. _ = recipient, request, value, index, data
  333. return None
  334. def GetStringDescriptor(self, index, lang, length):
  335. """Handle a GET_DESCRIPTOR(String) request from the host.
  336. Descriptor index 0 returns the set of languages supported by the device.
  337. All other indices return the string descriptors registered with those
  338. indices.
  339. See Universal Serial Bus Specification Revision 2.0 section 9.6.7.
  340. Args:
  341. index: Descriptor index.
  342. lang: Descriptor language code.
  343. length: Maximum amount of data the host expects the device to return.
  344. Returns:
  345. The string descriptor or None to stall the pipe if the descriptor is not
  346. found.
  347. """
  348. if index == 0:
  349. length = 2 + len(self._strings) * 2
  350. header = struct.pack('<BB', length, usb_constants.DescriptorType.STRING)
  351. lang_codes = [struct.pack('<H', lang)
  352. for lang in self._strings.iterkeys()]
  353. buf = header + ''.join(lang_codes)
  354. assert len(buf) == length
  355. return buf[:length]
  356. if index == 0xEE and lang == 0 and self._ms_vendor_code_v1 is not None:
  357. # See https://msdn.microsoft.com/en-us/windows/hardware/gg463179 for the
  358. # definition of this special string descriptor.
  359. buf = (struct.pack('<BB', 18, usb_constants.DescriptorType.STRING) +
  360. 'MSFT100'.encode('UTF-16LE') +
  361. struct.pack('<BB', self._ms_vendor_code_v1, 0))
  362. assert len(buf) == 18
  363. return buf[:length]
  364. elif lang not in self._strings:
  365. return None
  366. elif index not in self._strings[lang]:
  367. return None
  368. else:
  369. descriptor = usb_descriptors.StringDescriptor(
  370. bString=self._strings[lang][index])
  371. return descriptor.Encode()[:length]
  372. def GetMicrosoftOSDescriptorV1(self, recipient, value, index, length):
  373. """Handle a the Microsoft OS 1.0 Descriptor request from the host.
  374. See https://msdn.microsoft.com/en-us/windows/hardware/gg463179 for the
  375. format of these descriptors.
  376. Args:
  377. recipient: Request recipient (device or interface)
  378. value: wValue field of the setup packet.
  379. index: wIndex field of the setup packet.
  380. length: Maximum amount of data the host expects the device to return.
  381. Returns:
  382. The descriptor or None to stall the pipe if the descriptor is not
  383. supported.
  384. """
  385. _ = recipient, value
  386. if index == 0x0004:
  387. return self.GetMicrosoftCompatIds(length)
  388. def GetMicrosoftCompatIds(self, length):
  389. interfaces = self.GetConfigurationDescriptor().GetInterfaces()
  390. max_interface = max([iface.bInterfaceNumber for iface in interfaces])
  391. header = struct.pack('<IHHBxxxxxxx',
  392. 16 + 24 * (max_interface + 1),
  393. 0x0100,
  394. 0x0004,
  395. max_interface + 1)
  396. if length <= len(header):
  397. return header[:length]
  398. buf = header
  399. for interface in xrange(max_interface + 1):
  400. compat_id, sub_compat_id = self._ms_compat_ids.get(interface, ('', ''))
  401. buf += struct.pack('<BB8s8sxxxxxx',
  402. interface, 0x01, compat_id, sub_compat_id)
  403. return buf[:length]
  404. def GetMicrosoftOSDescriptorV2(self, length):
  405. return self._ms_os20_descriptor_set.Encode()[:length]
  406. def GetBosDescriptor(self, length):
  407. """Handle a GET_DESCRIPTOR(BOS) request from the host.
  408. Device capability descriptors can be added to the Binary Device Object Store
  409. returned by this method by calling AddDeviceCapabilityDescriptor.
  410. See Universal Serial Bus 3.1 Specification, Revision 1.0 section 9.6.2.
  411. Args:
  412. length: Maximum amount of data the host expects the device to return.
  413. Returns:
  414. The device's binary object store descriptor or None to stall the pipe if
  415. no device capability descriptors have been configured.
  416. """
  417. if self._bos_descriptor is None:
  418. return None
  419. return self._bos_descriptor.Encode()[:length]
  420. def SetConfiguration(self, index):
  421. """Handle a SET_CONFIGURATION request from the host.
  422. See Universal Serial Bus Specification Revision 2.0 section 9.4.7.
  423. Args:
  424. index: Configuration index selected.
  425. Returns:
  426. True on success, None on error to stall the pipe.
  427. """
  428. print('SetConfiguration({})'.format(index))
  429. for endpoint_addrs in self._active_endpoints.values():
  430. for endpoint_addr in endpoint_addrs:
  431. self._chip.StopEndpoint(endpoint_addr)
  432. endpoint_addrs.clear()
  433. self._endpoint_interface_map.clear();
  434. if index == 0:
  435. # SET_CONFIGRATION(0) puts the device into the Address state which
  436. # Windows does before suspending the port.
  437. return True
  438. elif index != 1:
  439. return None
  440. config_desc = self.GetConfigurationDescriptor()
  441. for interface_desc in config_desc.GetInterfaces():
  442. if interface_desc.bAlternateSetting != 0:
  443. continue
  444. endpoint_addrs = self._active_endpoints.setdefault(
  445. interface_desc.bInterfaceNumber, set())
  446. for endpoint_desc in interface_desc.GetEndpoints():
  447. self._chip.StartEndpoint(endpoint_desc)
  448. endpoint_addrs.add(endpoint_desc.bEndpointAddress)
  449. self._endpoint_interface_map[endpoint_desc.bEndpointAddress] = \
  450. interface_desc.bInterfaceNumber
  451. return True
  452. def SetInterface(self, interface, alt_setting):
  453. """Handle a SET_INTERFACE request from the host.
  454. See Universal Serial Bus Specification Revision 2.0 section 9.4.10.
  455. Args:
  456. interface: Interface number to configure.
  457. alt_setting: Alternate setting to select.
  458. Returns:
  459. True on success, None on error to stall the pipe.
  460. """
  461. print('SetInterface({}, {})'.format(interface, alt_setting))
  462. config_desc = self.GetConfigurationDescriptor()
  463. interface_desc = None
  464. for interface_option in config_desc.GetInterfaces():
  465. if (interface_option.bInterfaceNumber == interface and
  466. interface_option.bAlternateSetting == alt_setting):
  467. interface_desc = interface_option
  468. if interface_desc is None:
  469. return None
  470. endpoint_addrs = self._active_endpoints.setdefault(interface, set())
  471. for endpoint_addr in endpoint_addrs:
  472. self._chip.StopEndpoint(endpoint_addr)
  473. del self._endpoint_interface_map[endpoint_addr]
  474. for endpoint_desc in interface_desc.GetEndpoints():
  475. self._chip.StartEndpoint(endpoint_desc)
  476. endpoint_addrs.add(endpoint_desc.bEndpointAddress)
  477. self._endpoint_interface_map[endpoint_desc.bEndpointAddress] = \
  478. interface_desc.bInterfaceNumber
  479. return True
  480. def GetInterfaceForEndpoint(self, endpoint_addr):
  481. return self._endpoint_interface_map.get(endpoint_addr)