Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HID connectivity improvements #237

Merged
merged 2 commits into from
Nov 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions fido2/hid/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@
open_connection = backend.open_connection


class ConnectionFailure(Exception):
"""The CTAP connection failed or returned an invalid response."""


@unique
class CTAPHID(IntEnum):
PING = 0x01
Expand Down Expand Up @@ -109,7 +113,7 @@ def __init__(self, descriptor: HidDescriptor, connection):
response = self.call(CTAPHID.INIT, nonce)
r_nonce, response = response[:8], response[8:]
if r_nonce != nonce:
raise Exception("Wrong nonce")
raise ConnectionFailure("Wrong nonce")
(
self._channel_id,
self._u2fhid_version,
Expand Down Expand Up @@ -163,6 +167,18 @@ def call(
on_keepalive: Optional[Callable[[int], None]] = None,
) -> bytes:
event = event or Event()

while True:
try:
return self._do_call(cmd, data, event, on_keepalive)
except CtapError as e:
if e.code == CtapError.ERR.CHANNEL_BUSY:
if not event.wait(0.1):
logger.warning("CTAP channel busy, trying again...")
continue # Keep retrying on BUSY while not cancelled
raise

def _do_call(self, cmd, data, event, on_keepalive):
remaining = data
seq = 0

Expand Down Expand Up @@ -194,7 +210,7 @@ def call(
r_channel = struct.unpack_from(">I", recv)[0]
recv = recv[4:]
if r_channel != self._channel_id:
raise Exception("Wrong channel")
raise ConnectionFailure("Wrong channel")

if not response: # Initialization packet
r_cmd, r_len = struct.unpack_from(">BH", recv)
Expand All @@ -220,7 +236,7 @@ def call(
r_seq = struct.unpack_from(">B", recv)[0]
recv = recv[1:]
if r_seq != seq:
raise Exception("Wrong sequence number")
raise ConnectionFailure("Wrong sequence number")
seq += 1

response += recv
Expand Down