xap.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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], dict):
  28. print_dotted_output(kb_info_json[key], new_prefix)
  29. elif isinstance(kb_info_json[key], list):
  30. data = kb_info_json[key]
  31. if len(data) and isinstance(data[0], dict):
  32. for index, item in enumerate(data, start=0):
  33. cli.echo(' {fg_blue}%s.%s{fg_reset}: %s', new_prefix, index, str(item))
  34. else:
  35. cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, ', '.join(sorted(map(str, data))))
  36. else:
  37. cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, kb_info_json[key])
  38. def _xap_transaction(device, sub, route, ret_len, *args):
  39. # gen token
  40. tok = random.getrandbits(16)
  41. token = tok.to_bytes(2, byteorder='little')
  42. # send with padding
  43. # TODO: this code is total garbage
  44. args_data = []
  45. args_len = 2
  46. if len(args) == 1:
  47. if isinstance(args[0], (bytes, bytearray)):
  48. args_len += len(args[0])
  49. args_data = args[0]
  50. else:
  51. args_len += 2
  52. args_data = args[0].to_bytes(2, byteorder='little')
  53. padding_len = 64 - 3 - args_len
  54. padding = b"\x00" * padding_len
  55. if args_data:
  56. padding = args_data + padding
  57. buffer = token + args_len.to_bytes(1, byteorder='little') + sub.to_bytes(1, byteorder='little') + route.to_bytes(1, byteorder='little') + padding
  58. # prepend 0 on windows because reasons...
  59. if 'windows' in platform().lower():
  60. buffer = b"\x00" + buffer
  61. device.write(buffer)
  62. # get resp
  63. array_alpha = device.read(4 + ret_len, 100)
  64. # validate tok sent == resp
  65. if str(token) != str(array_alpha[:2]):
  66. return None
  67. return array_alpha[4:]
  68. def _query_device(device):
  69. ver_data = _xap_transaction(device, 0x00, 0x00, 4)
  70. if not ver_data:
  71. return {'xap': 'UNKNOWN'}
  72. # to u32 to BCD string
  73. a = (ver_data[3] << 24) + (ver_data[2] << 16) + (ver_data[1] << 8) + (ver_data[0])
  74. ver = f'{a>>24}.{a>>16 & 0xFF}.{a & 0xFFFF}'
  75. secure = int.from_bytes(_xap_transaction(device, 0x00, 0x03, 1), 'little')
  76. secure = 'unlocked' if secure == 2 else 'LOCKED'
  77. return {'xap': ver, 'secure': secure}
  78. def _query_device_info_len(device):
  79. len_data = _xap_transaction(device, 0x01, 0x05, 4)
  80. if not len_data:
  81. return 0
  82. # to u32
  83. return (len_data[3] << 24) + (len_data[2] << 16) + (len_data[1] << 8) + (len_data[0])
  84. def _query_device_info_chunk(device, offset):
  85. return _xap_transaction(device, 0x01, 0x06, 32, offset)
  86. def _query_device_info(device):
  87. datalen = _query_device_info_len(device)
  88. if not datalen:
  89. return {}
  90. data = []
  91. offset = 0
  92. while offset < datalen:
  93. data += _query_device_info_chunk(device, offset)
  94. offset += 32
  95. str_data = gzip.decompress(bytearray(data[:datalen]))
  96. return json.loads(str_data)
  97. def _list_devices():
  98. """Dump out available devices
  99. """
  100. cli.log.info('Available devices:')
  101. devices = _search()
  102. for dev in devices:
  103. device = hid.Device(path=dev['path'])
  104. data = _query_device(device)
  105. 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'])
  106. if cli.config.general.verbose:
  107. # TODO: better formatting like "lsusb -v"?
  108. data = _query_device_info(device)
  109. print_dotted_output(data)
  110. # _xap_transaction(device, 0x01, 0x07, 1)
  111. @cli.argument('-d', '--device', help='device to select - uses format <pid>:<vid>.')
  112. @cli.argument('-i', '--index', default=0, help='device index to select.')
  113. @cli.argument('-l', '--list', arg_only=True, action='store_true', help='List available devices.')
  114. @cli.subcommand('Acquire debugging information from usb XAP devices.', hidden=False if cli.config.user.developer else True)
  115. def xap(cli):
  116. """Acquire debugging information from XAP devices
  117. """
  118. # Lazy load to avoid issues
  119. global hid
  120. import hid
  121. if cli.args.list:
  122. return _list_devices()
  123. # Connect to first available device
  124. dev = _search()[0]
  125. device = hid.Device(path=dev['path'])
  126. cli.log.info("Connected to:%04x:%04x %s %s", dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'])
  127. # get layer count
  128. layers = _xap_transaction(device, 0x04, 0x01, 1)
  129. layers = int.from_bytes(layers, "little")
  130. print(f'layers:{layers}')
  131. # get keycode [layer:0, row:0, col:0]
  132. keycode = _xap_transaction(device, 0x04, 0x02, 2, b"\x00\x00\x00")
  133. keycode = int.from_bytes(keycode, "little")
  134. keycode_map = {
  135. 0x29: 'KC_ESCAPE'
  136. }
  137. print('keycode:' + keycode_map.get(keycode, 'unknown'))
  138. # Reboot
  139. # _xap_transaction(device, 0x01, 0x07, 1)