xap.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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. cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, ', '.join(map(str, sorted(kb_info_json[key]))))
  31. else:
  32. cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, kb_info_json[key])
  33. def _xap_transaction(device, sub, route, ret_len, *args):
  34. # gen token
  35. tok = random.getrandbits(16)
  36. token = tok.to_bytes(2, byteorder='big')
  37. # send with padding
  38. # TODO: this code is total garbage
  39. args_data = []
  40. args_len = 2
  41. if len(args) == 1:
  42. args_len += 2
  43. args_data = args[0].to_bytes(2, byteorder='big')
  44. padding = b"\x00" * (64 - 3 - args_len)
  45. if args_data:
  46. padding = args_data + padding
  47. buffer = token + args_len.to_bytes(1, byteorder='big') + sub.to_bytes(1, byteorder='big') + route.to_bytes(1, byteorder='big') + padding
  48. # prepend 0 on windows because reasons...
  49. if 'windows' in platform().lower():
  50. buffer = b"\x00" + buffer
  51. device.write(buffer)
  52. # get resp
  53. array_alpha = device.read(4 + ret_len, 100)
  54. # validate tok sent == resp
  55. if str(token) != str(array_alpha[:2]):
  56. return None
  57. return array_alpha[4:]
  58. def _query_device_version(device):
  59. ver_data = _xap_transaction(device, 0x00, 0x00, 4)
  60. if not ver_data:
  61. return {'xap': 'UNKNOWN'}
  62. # to u32 to BCD string
  63. a = (ver_data[3] << 24) + (ver_data[2] << 16) + (ver_data[1] << 8) + (ver_data[0])
  64. ver = f'{a>>24}.{a>>16 & 0xFF}.{a & 0xFFFF}'
  65. return {'xap': ver}
  66. def _query_device_info_len(device):
  67. len_data = _xap_transaction(device, 0x01, 0x05, 4)
  68. if not len_data:
  69. return 0
  70. # to u32
  71. return (len_data[3] << 24) + (len_data[2] << 16) + (len_data[1] << 8) + (len_data[0])
  72. def _query_device_info_chunk(device, offset):
  73. return _xap_transaction(device, 0x01, 0x06, 32, offset)
  74. def _query_device_info(device):
  75. datalen = _query_device_info_len(device)
  76. if not datalen:
  77. return {}
  78. data = []
  79. offset = 0
  80. while offset < datalen:
  81. data += _query_device_info_chunk(device, offset)
  82. offset += 32
  83. str_data = gzip.decompress(bytearray(data[:datalen]))
  84. return json.loads(str_data)
  85. def _list_devices():
  86. """Dump out available devices
  87. """
  88. cli.log.info('Available devices:')
  89. devices = _search()
  90. for dev in devices:
  91. device = hid.Device(path=dev['path'])
  92. data = _query_device_version(device)
  93. cli.log.info(" %04x:%04x %s %s [API:%s]", dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'], data['xap'])
  94. if cli.config.general.verbose:
  95. # TODO: better formatting like "lsusb -v"?
  96. data = _query_device_info(device)
  97. print_dotted_output(data)
  98. @cli.argument('-d', '--device', help='device to select - uses format <pid>:<vid>.')
  99. @cli.argument('-i', '--index', default=0, help='device index to select.')
  100. @cli.argument('-l', '--list', arg_only=True, action='store_true', help='List available devices.')
  101. @cli.subcommand('Acquire debugging information from usb XAP devices.', hidden=False if cli.config.user.developer else True)
  102. def xap(cli):
  103. """Acquire debugging information from XAP devices
  104. """
  105. # Lazy load to avoid issues
  106. global hid
  107. import hid
  108. if cli.args.list:
  109. return _list_devices()
  110. cli.log.warn("TODO: Device specific stuff")