xap.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. """Interactions with compatible XAP devices
  2. """
  3. import json
  4. import random
  5. import gzip
  6. from platform import platform
  7. from milc import cli
  8. def _is_xap_usage(x):
  9. return x['usage_page'] == 0xFF51 and x['usage'] == 0x0058
  10. def _is_filtered_device(x):
  11. name = "%04x:%04x" % (x['vendor_id'], x['product_id'])
  12. return name.lower().startswith(cli.args.device.lower())
  13. def _search():
  14. devices = filter(_is_xap_usage, hid.enumerate())
  15. if cli.args.device:
  16. devices = filter(_is_filtered_device, devices)
  17. return list(devices)
  18. def print_dotted_output(kb_info_json, prefix=''):
  19. """Print the info.json in a plain text format with dot-joined keys.
  20. """
  21. for key in sorted(kb_info_json):
  22. new_prefix = f'{prefix}.{key}' if prefix else key
  23. if key in ['parse_errors', 'parse_warnings']:
  24. continue
  25. elif key == 'layouts' and prefix == '':
  26. cli.echo(' {fg_blue}layouts{fg_reset}: %s', ', '.join(sorted(kb_info_json['layouts'].keys())))
  27. elif isinstance(kb_info_json[key], bytes):
  28. conv = "".join(["{:02X}".format(b) for b in kb_info_json[key]])
  29. cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, conv)
  30. elif isinstance(kb_info_json[key], dict):
  31. print_dotted_output(kb_info_json[key], new_prefix)
  32. elif isinstance(kb_info_json[key], list):
  33. data = kb_info_json[key]
  34. if len(data) and isinstance(data[0], dict):
  35. for index, item in enumerate(data, start=0):
  36. cli.echo(' {fg_blue}%s.%s{fg_reset}: %s', new_prefix, index, str(item))
  37. else:
  38. cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, ', '.join(sorted(map(str, data))))
  39. else:
  40. cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, kb_info_json[key])
  41. def _xap_transaction(device, sub, route, *args):
  42. # gen token
  43. tok = random.getrandbits(16)
  44. token = tok.to_bytes(2, byteorder='little')
  45. # send with padding
  46. # TODO: this code is total garbage
  47. args_data = []
  48. args_len = 2
  49. if len(args) == 1:
  50. if isinstance(args[0], (bytes, bytearray)):
  51. args_len += len(args[0])
  52. args_data = args[0]
  53. else:
  54. args_len += 2
  55. args_data = args[0].to_bytes(2, byteorder='little')
  56. padding_len = 64 - 3 - args_len
  57. padding = b"\x00" * padding_len
  58. if args_data:
  59. padding = args_data + padding
  60. buffer = token + args_len.to_bytes(1, byteorder='little') + sub.to_bytes(1, byteorder='little') + route.to_bytes(1, byteorder='little') + padding
  61. # prepend 0 on windows because reasons...
  62. if 'windows' in platform().lower():
  63. buffer = b"\x00" + buffer
  64. device.write(buffer)
  65. # get resp
  66. array_alpha = device.read(64, 100)
  67. # validate tok sent == resp
  68. if str(token) != str(array_alpha[:2]):
  69. return None
  70. if int(array_alpha[2]) != 0x01:
  71. return None
  72. payload_len = int(array_alpha[3])
  73. return array_alpha[4:4 + payload_len]
  74. def _query_device(device):
  75. ver_data = _xap_transaction(device, 0x00, 0x00)
  76. if not ver_data:
  77. return {'xap': 'UNKNOWN', 'secure': 'UNKNOWN'}
  78. # to u32 to BCD string
  79. a = (ver_data[3] << 24) + (ver_data[2] << 16) + (ver_data[1] << 8) + (ver_data[0])
  80. ver = f'{a>>24}.{a>>16 & 0xFF}.{a & 0xFFFF}'
  81. secure = int.from_bytes(_xap_transaction(device, 0x00, 0x03), 'little')
  82. secure = 'unlocked' if secure == 2 else 'LOCKED'
  83. return {'xap': ver, 'secure': secure}
  84. def _query_device_id(device):
  85. return _xap_transaction(device, 0x01, 0x08)
  86. def _query_device_info_len(device):
  87. len_data = _xap_transaction(device, 0x01, 0x05)
  88. if not len_data:
  89. return 0
  90. # to u32
  91. return (len_data[3] << 24) + (len_data[2] << 16) + (len_data[1] << 8) + (len_data[0])
  92. def _query_device_info_chunk(device, offset):
  93. return _xap_transaction(device, 0x01, 0x06, offset)
  94. def _query_device_info(device):
  95. datalen = _query_device_info_len(device)
  96. if not datalen:
  97. return {}
  98. data = []
  99. offset = 0
  100. while offset < datalen:
  101. data += _query_device_info_chunk(device, offset)
  102. offset += 32
  103. str_data = gzip.decompress(bytearray(data[:datalen]))
  104. return json.loads(str_data)
  105. def _list_devices():
  106. """Dump out available devices
  107. """
  108. cli.log.info('Available devices:')
  109. devices = _search()
  110. for dev in devices:
  111. device = hid.Device(path=dev['path'])
  112. data = _query_device(device)
  113. cli.log.info(" %04x:%04x %s %s [API:%s] %s", dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'], data['xap'], data['secure'])
  114. if cli.config.general.verbose:
  115. # TODO: better formatting like "lsusb -v"?
  116. data = _query_device_info(device)
  117. data["_id"] = _query_device_id(device)
  118. print_dotted_output(data)
  119. def xap_dump_keymap(device):
  120. # get layer count
  121. layers = _xap_transaction(device, 0x04, 0x01)
  122. layers = int.from_bytes(layers, "little")
  123. print(f'layers:{layers}')
  124. # get keycode [layer:0, row:0, col:0]
  125. # keycode = _xap_transaction(device, 0x04, 0x02, b"\x00\x00\x00")
  126. # get encoder [layer:0, index:0, clockwise:0]
  127. keycode = _xap_transaction(device, 0x05, 0x02, b"\x00\x00\x00")
  128. keycode = int.from_bytes(keycode, "little")
  129. keycode_map = {
  130. # TODO: this should be data driven...
  131. 0x04: 'KC_A',
  132. 0x05: 'KC_B',
  133. 0x29: 'KC_ESCAPE',
  134. 0xF9: 'KC_MS_WH_UP',
  135. }
  136. print(f'keycode:{keycode_map.get(keycode, "unknown")}')
  137. def xap_doit():
  138. print("xap_doit")
  139. # Reboot
  140. # _xap_transaction(device, 0x01, 0x07)
  141. exit(1)
  142. def xap_broadcast_listen(device):
  143. try:
  144. cli.log.info("Listening for XAP broadcasts...")
  145. while 1:
  146. array_alpha = device.read(64, 100)
  147. if str(b"\xFF\xFF") == str(array_alpha[:2]):
  148. if array_alpha[2] == 1:
  149. cli.log.info(" Broadcast: Secure[%02x]", array_alpha[4])
  150. else:
  151. cli.log.info(" Broadcast: type[%02x] data:[%02x]", array_alpha[2], array_alpha[4])
  152. except KeyboardInterrupt:
  153. cli.log.info("Stopping...")
  154. def xap_unlock(device):
  155. _xap_transaction(device, 0x00, 0x04)
  156. @cli.argument('-d', '--device', help='device to select - uses format <pid>:<vid>.')
  157. @cli.argument('-i', '--index', default=0, help='device index to select.')
  158. @cli.argument('-l', '--list', arg_only=True, action='store_true', help='List available devices.')
  159. @cli.argument('action', nargs='?', arg_only=True)
  160. @cli.subcommand('Acquire debugging information from usb XAP devices.', hidden=False if cli.config.user.developer else True)
  161. def xap(cli):
  162. """Acquire debugging information from XAP devices
  163. """
  164. # Lazy load to avoid issues
  165. global hid
  166. import hid
  167. if cli.args.list:
  168. return _list_devices()
  169. # Connect to first available device
  170. devices = _search()
  171. if not devices:
  172. cli.log.error("No devices found!")
  173. return False
  174. dev = devices[0]
  175. device = hid.Device(path=dev['path'])
  176. cli.log.info("Connected to:%04x:%04x %s %s", dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'])
  177. # xap_doit(device)
  178. if cli.args.action == 'unlock':
  179. xap_unlock(device)
  180. cli.log.info("Done")
  181. elif cli.args.action == 'dump':
  182. xap_dump_keymap(device)
  183. elif cli.args.action == 'listen':
  184. xap_broadcast_listen(device)
  185. elif not cli.args.action:
  186. xap_broadcast_listen(device)