1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2025-02-08 13:42:41 +00:00

transport: better ways to handle errors when enumerating devices

This commit is contained in:
matejcik 2018-05-24 19:14:05 +02:00
parent 97fa4670ac
commit e779a251fb
6 changed files with 50 additions and 32 deletions

View File

@ -150,6 +150,7 @@ class BaseClient(object):
# Implements very basic layer of sending raw protobuf # Implements very basic layer of sending raw protobuf
# messages to device and getting its response back. # messages to device and getting its response back.
def __init__(self, transport, **kwargs): def __init__(self, transport, **kwargs):
LOG.info("creating client instance for device: {}".format(transport.get_path()))
self.transport = transport self.transport = transport
super(BaseClient, self).__init__() # *args, **kwargs) super(BaseClient, self).__init__() # *args, **kwargs)

View File

@ -17,6 +17,13 @@
# You should have received a copy of the GNU Lesser General Public License # You should have received a copy of the GNU Lesser General Public License
# along with this library. If not, see <http://www.gnu.org/licenses/>. # along with this library. If not, see <http://www.gnu.org/licenses/>.
import importlib
import logging
from typing import Iterable, Type, List, Set
LOG = logging.getLogger(__name__)
class TransportException(Exception): class TransportException(Exception):
pass pass
@ -63,54 +70,52 @@ class Transport(object):
raise TransportException('{} device not found: {}'.format(cls.PATH_PREFIX, path)) raise TransportException('{} device not found: {}'.format(cls.PATH_PREFIX, path))
def all_transports(): def all_transports() -> Iterable[Type[Transport]]:
transports = [] transports = set() # type: Set[Type[Transport]]
try: for modname in ("bridge", "hid", "udp", "webusb"):
from .bridge import BridgeTransport try:
transports.append(BridgeTransport) # Import the module and find the Transport class.
except: # To avoid iterating over every item, the module should assign its Transport class
pass # to a constant named TRANSPORT.
module = importlib.import_module("." + modname, __name__)
try: try:
from .hid import HidTransport transports.add(getattr(module, "TRANSPORT"))
transports.append(HidTransport) except AttributeError:
except: LOG.warning("Skipping broken module {}".format(modname))
pass except ImportError as e:
LOG.info("Failed to import module {}: {}".format(modname, e))
try:
from .udp import UdpTransport
transports.append(UdpTransport)
except:
pass
try:
from .webusb import WebUsbTransport
transports.append(WebUsbTransport)
except:
pass
return transports return transports
def enumerate_devices(): def enumerate_devices() -> Iterable[Transport]:
return [device devices = [] # type: List[Transport]
for transport in all_transports() for transport in all_transports():
for device in transport.enumerate()] try:
found = transport.enumerate()
LOG.info("Enumerating {}: found {} devices".format(transport.__name__, len(found)))
devices.extend(found)
except NotImplementedError:
LOG.error("{} does not implement device enumeration".format(transport.__name__))
except Exception as e:
LOG.error("Failed to enumerate {}. {}: {}".format(transport.__name__, e.__class__.__name__, e))
return devices
def get_transport(path=None, prefix_search=False): def get_transport(path: str = None, prefix_search: bool = False) -> Transport:
if path is None: if path is None:
try: try:
return enumerate_devices()[0] return next(iter(enumerate_devices()))
except IndexError: except IndexError:
raise Exception("No TREZOR device found") from None raise Exception("No TREZOR device found") from None
# Find whether B is prefix of A (transport name is part of the path) # Find whether B is prefix of A (transport name is part of the path)
# or A is prefix of B (path is a prefix, or a name, of transport). # or A is prefix of B (path is a prefix, or a name, of transport).
# This naively expects that no two transports have a common prefix. # This naively expects that no two transports have a common prefix.
def match_prefix(a, b): def match_prefix(a: str, b: str) -> bool:
return a.startswith(b) or b.startswith(a) return a.startswith(b) or b.startswith(a)
LOG.info("looking for device by {}: {}".format("prefix" if prefix_search else "full path", path))
transports = [t for t in all_transports() if match_prefix(path, t.PATH_PREFIX)] transports = [t for t in all_transports() if match_prefix(path, t.PATH_PREFIX)]
if transports: if transports:
return transports[0].find_by_path(path, prefix_search=prefix_search) return transports[0].find_by_path(path, prefix_search=prefix_search)

View File

@ -106,3 +106,6 @@ class BridgeTransport(Transport):
extra={'protobuf': msg}) extra={'protobuf': msg})
self.response = None self.response = None
return msg return msg
TRANSPORT = BridgeTransport

View File

@ -180,3 +180,6 @@ def is_wirelink(dev):
def is_debuglink(dev): def is_debuglink(dev):
return (dev['usage_page'] == 0xFF01 or dev['interface_number'] == 1) return (dev['usage_page'] == 0xFF01 or dev['interface_number'] == 1)
TRANSPORT = HidTransport

View File

@ -124,3 +124,6 @@ class UdpTransport(Transport):
if len(chunk) != 64: if len(chunk) != 64:
raise TransportException('Unexpected chunk size: %d' % len(chunk)) raise TransportException('Unexpected chunk size: %d' % len(chunk))
return bytearray(chunk) return bytearray(chunk)
TRANSPORT = UdpTransport

View File

@ -188,3 +188,6 @@ def is_vendor_class(dev):
def dev_to_str(dev): def dev_to_str(dev):
return ':'.join(str(x) for x in ['%03i' % (dev.getBusNumber(), )] + dev.getPortNumberList()) return ':'.join(str(x) for x in ['%03i' % (dev.getBusNumber(), )] + dev.getPortNumberList())
TRANSPORT = WebUsbTransport