xap.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. """Interactions with compatible XAP devices
  2. """
  3. import json
  4. import random
  5. import gzip
  6. from milc import cli
  7. def _is_xap_usage(x):
  8. return x['usage_page'] == 0xFF51 and x['usage'] == 0x0058
  9. def _is_filtered_device(x):
  10. name = "%04x:%04x" % (x['vendor_id'], x['product_id'])
  11. return name.lower().startswith(cli.args.device.lower())
  12. def _search():
  13. devices = filter(_is_xap_usage, hid.enumerate())
  14. if cli.args.device:
  15. devices = filter(_is_filtered_device, devices)
  16. return list(devices)
  17. def print_dotted_output(kb_info_json, prefix=''):
  18. """Print the info.json in a plain text format with dot-joined keys.
  19. """
  20. for key in sorted(kb_info_json):
  21. new_prefix = f'{prefix}.{key}' if prefix else key
  22. if key in ['parse_errors', 'parse_warnings']:
  23. continue
  24. elif key == 'layouts' and prefix == '':
  25. cli.echo(' {fg_blue}layouts{fg_reset}: %s', ', '.join(sorted(kb_info_json['layouts'].keys())))
  26. elif isinstance(kb_info_json[key], dict):
  27. print_dotted_output(kb_info_json[key], new_prefix)
  28. elif isinstance(kb_info_json[key], list):
  29. cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, ', '.join(map(str, sorted(kb_info_json[key]))))
  30. else:
  31. cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, kb_info_json[key])
  32. def _list_devices():
  33. """Dump out available devices
  34. """
  35. cli.log.info('Available devices:')
  36. devices = _search()
  37. for dev in devices:
  38. device = hid.Device(path=dev['path'])
  39. data = _query_device_version(device)
  40. cli.log.info(" %04x:%04x %s %s [API:%s]", dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'], data['ver'])
  41. if cli.config.general.verbose:
  42. # TODO: better formatting like "lsusb -v"
  43. datalen = _query_device_info_len(device)
  44. data = []
  45. offset = 0
  46. while offset < datalen:
  47. data += _query_device_info(device, offset)
  48. offset += 32
  49. str_data = gzip.decompress(bytearray(data[:datalen]))
  50. print_dotted_output(json.loads(str_data))
  51. def _query_device_version(device):
  52. # gen token
  53. tok = random.getrandbits(16)
  54. temp = tok.to_bytes(2, byteorder='big')
  55. # send with padding
  56. padding = b"\x00" * 59
  57. device.write(temp + b'\x02\x00\x00' + padding)
  58. # get resp
  59. array_alpha = device.read(8, 100)
  60. # hex_string = " ".join("%02x" % b for b in array_alpha)
  61. # validate tok sent == resp
  62. ver = "UNKNOWN"
  63. if str(temp) == str(array_alpha[:2]):
  64. # to BCD string
  65. a = (array_alpha[7] << 24) + (array_alpha[6] << 16) + (array_alpha[5] << 8) + (array_alpha[4])
  66. ver = f'{a>>24}.{a>>16 & 0xFF}.{a & 0xFFFF}'
  67. return {'ver': ver}
  68. def _query_device_info_len(device):
  69. # gen token
  70. tok = random.getrandbits(16)
  71. temp = tok.to_bytes(2, byteorder='big')
  72. # send with padding
  73. padding = b"\x00" * 59
  74. device.write(temp + b'\x02\x01\x05' + padding)
  75. # get resp
  76. array_alpha = device.read(8, 100)
  77. # hex_string = " ".join("%02x" % b for b in array_alpha)
  78. # validate tok sent == resp
  79. datalen = "UNKNOWN"
  80. if str(temp) == str(array_alpha[:2]):
  81. # to BCD string
  82. a = (array_alpha[7] << 24) + (array_alpha[6] << 16) + (array_alpha[5] << 8) + (array_alpha[4])
  83. datalen = f'{a & 0xFFFF}'
  84. return int(datalen)
  85. def _query_device_info(device, offset):
  86. # gen token
  87. tok = random.getrandbits(16)
  88. temp = tok.to_bytes(2, byteorder='big')
  89. # send with padding
  90. padding = b"\x00" * 57
  91. device.write(temp + b'\x04\x01\x06' + (offset).to_bytes(2, byteorder='big') + padding)
  92. # get resp
  93. array_alpha = device.read(4 + 32, 100)
  94. # hex_string = " ".join("%02x" % b for b in array_alpha)
  95. # validate tok sent == resp
  96. if str(temp) == str(array_alpha[:2]):
  97. return array_alpha[4:]
  98. return None
  99. @cli.argument('-d', '--device', help='device to select - uses format <pid>:<vid>.')
  100. @cli.argument('-i', '--index', default=0, help='device index to select.')
  101. @cli.argument('-l', '--list', arg_only=True, action='store_true', help='List available devices.')
  102. @cli.subcommand('Acquire debugging information from usb XAP devices.', hidden=False if cli.config.user.developer else True)
  103. def xap(cli):
  104. """Acquire debugging information from XAP devices
  105. """
  106. # Lazy load to avoid issues
  107. global hid
  108. import hid
  109. if cli.args.list:
  110. return _list_devices()
  111. cli.log.warn("TODO: Device specific stuff")