1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
// Copyright (C) 2021-2022 Robin Krahl <robin.krahl@ireas.org>
// SPDX-License-Identifier: Apache-2.0 or MIT

//! Error types for `ctaphid` operations.

use std::{error, fmt};

use ctaphid_types::Command;

/// Error type for `ctaphid` operations.
#[derive(Debug)]
pub enum Error {
    /// A command-specific error.
    CommandError(CommandError),
    /// An error that occured while sending a CTAPHID request.
    RequestError(RequestError),
    /// An error that occured while receiving a CTAPHID response.
    ResponseError(ResponseError),
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::CommandError(error) => Some(error),
            Self::RequestError(error) => Some(error),
            Self::ResponseError(error) => Some(error),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CommandError(_) => "command execution failed",
            Self::RequestError(_) => "failed to send CTAPHID request",
            Self::ResponseError(_) => "failed to receive CTAPHID response",
        }
        .fmt(f)
    }
}

impl From<CommandError> for Error {
    fn from(error: CommandError) -> Self {
        Self::CommandError(error)
    }
}

impl From<RequestError> for Error {
    fn from(error: RequestError) -> Self {
        Self::RequestError(error)
    }
}

impl From<ResponseError> for Error {
    fn from(error: ResponseError) -> Self {
        Self::ResponseError(error)
    }
}

/// A command-specific error.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum CommandError {
    /// A CBOR response contained a non-zero status code.
    CborError(u8),
    /// A ping response with wrong data was received.
    InvalidPingData,
    /// The command is not supported by the device.
    NotSupported(Command),
}

impl error::Error for CommandError {}

impl fmt::Display for CommandError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CborError(error) => write!(f, "received a CBOR response with status {:x}", error),
            Self::InvalidPingData => "received a ping response with wrong data".fmt(f),
            Self::NotSupported(command) => write!(
                f,
                "the command {:?} is not supported by the device",
                command
            ),
        }
    }
}

/// An error that occured while sending a request to a CTAPHID device.
#[derive(Debug)]
pub enum RequestError {
    /// The request could not be written completely.
    IncompleteWrite,
    /// The request message could not be fragmented into CTAPHID packets.
    MessageFragmentationFailed(ctaphid_types::FragmentationError),
    /// A request packet could not be sent to the device.
    PacketSendingFailed(Box<dyn std::error::Error + Send + Sync>),
    /// A request packet could not be serialized.
    PacketSerializationFailed(ctaphid_types::SerializationError),
}

impl error::Error for RequestError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::MessageFragmentationFailed(err) => Some(err),
            Self::PacketSendingFailed(err) => Some(err.as_ref()),
            Self::PacketSerializationFailed(err) => Some(err),
            _ => None,
        }
    }
}

impl fmt::Display for RequestError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::IncompleteWrite => "the request could not be written completely",
            Self::MessageFragmentationFailed(_) => {
                "the request message could not be fragmented into CTAPHID packets"
            }
            Self::PacketSendingFailed(_) => "a request packet could not be sent to the device",
            Self::PacketSerializationFailed(_) => "a request packet could not be serialized",
        }
        .fmt(f)
    }
}

/// An error that occured while receiving a response from a CTAPHID device.
#[derive(Debug)]
pub enum ResponseError {
    /// The command execution failed.
    CommandFailed(ctaphid_types::DeviceError),
    /// The response message could not be assembled from CTAPHID packets.
    MessageDefragmentationFailed(ctaphid_types::DefragmentationError),
    /// A response packet could not be parsed.
    PacketParsingFailed(ctaphid_types::ParseError),
    /// A response packet could not be received from the device.
    PacketReceivingFailed(Box<dyn std::error::Error + Send + Sync>),
    /// The device did not response within the specified timeout.
    Timeout,
    /// The device returned an error packet without an error code.
    MissingErrorCode,
    /// The device returned a response packet with an unexpected command ID.
    UnexpectedCommand {
        /// The expected command ID.
        expected: Command,
        /// The actual command ID.
        actual: Command,
    },
    /// The device sent an unexpected KEEPALIVE message while waiting for the response to a
    /// command.
    UnexpectedKeepAlive(Command),
    /// The device returned response data although an empty response was expected.
    UnexpectedResponseData(Vec<u8>),
}

impl error::Error for ResponseError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::CommandFailed(err) => Some(err),
            Self::MessageDefragmentationFailed(err) => Some(err),
            Self::PacketParsingFailed(err) => Some(err),
            Self::PacketReceivingFailed(err) => Some(err.as_ref()),
            _ => None,
        }
    }
}

impl fmt::Display for ResponseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CommandFailed(_) => "the command execution failed".fmt(f),
            Self::MessageDefragmentationFailed(_) => {
                "the response message could not be assembled from CTAPHID packets".fmt(f)
            }
            Self::PacketParsingFailed(_) => "a response packet could not be serialized".fmt(f),
            Self::PacketReceivingFailed(_) => {
                "a response packet could not be received from the device".fmt(f)
            }
            Self::Timeout => "no response was received within the specified timeout".fmt(f),
            Self::MissingErrorCode => "an error packet does not contain an error code".fmt(f),
            Self::UnexpectedCommand { expected, actual } => write!(
                f,
                "expected a response packet for command {:?} but received {:?}",
                expected, actual
            ),
            Self::UnexpectedKeepAlive(command) => {
                write!(
                    f,
                    "expected a response message to a {:?} command but received a KEEPALIVE message",
                    command
                )
            }
            Self::UnexpectedResponseData(data) => {
                write!(f, "expected an empty response but received {:x?}", data)
            }
        }
    }
}