1use std::error::Error as StdError;
2use std::fmt;
3use std::time::SystemTimeError;
4
5use crate::tls::rustls::msgs::enums::{AlertDescription, ContentType, HandshakeType};
6use crate::tls::rustls::rand;
7
8#[derive(Debug, PartialEq, Clone)]
11pub struct CorruptMessagePayload {
12 location: &'static core::panic::Location<'static>,
13 kind: ContentType,
14}
15
16impl CorruptMessagePayload {
17 pub fn content_type(&self) -> ContentType {
19 self.kind
20 }
21}
22
23#[derive(Debug, PartialEq, Clone)]
25pub enum Error {
26 InappropriateMessage {
32 expect_types: Vec<ContentType>,
34 got_type: ContentType,
36 },
37
38 InappropriateHandshakeMessage {
42 expect_types: Vec<HandshakeType>,
44 got_type: HandshakeType,
46 },
47
48 CorruptMessage,
50
51 CorruptMessagePayload(CorruptMessagePayload),
53
54 NoCertificatesPresented,
56
57 UnsupportedNameType,
59
60 DecryptError,
62
63 EncryptError,
66
67 PeerIncompatibleError(String),
70
71 PeerMisbehavedError(String),
74
75 AlertReceived(AlertDescription),
77
78 InvalidCertificateEncoding,
80
81 InvalidCertificateSignatureType,
83
84 InvalidCertificateSignature,
86
87 InvalidCertificateData(String),
89
90 InvalidSct(sct::Error),
92
93 General(String),
95
96 FailedToGetCurrentTime,
98
99 FailedToGetRandomBytes,
101
102 HandshakeNotComplete,
105
106 PeerSentOversizedRecord,
108
109 NoApplicationProtocol,
111
112 BadMaxFragmentSize,
115}
116
117impl Error {
118 #[track_caller]
119 pub fn corrupt_message(kind: ContentType) -> Self {
120 Self::CorruptMessagePayload(CorruptMessagePayload {
121 location: core::panic::Location::caller(),
122 kind,
123 })
124 }
125}
126
127fn join<T: fmt::Debug>(items: &[T]) -> String {
128 items
129 .iter()
130 .map(|x| format!("{:?}", x))
131 .collect::<Vec<String>>()
132 .join(" or ")
133}
134
135impl fmt::Display for Error {
136 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
137 match *self {
138 Self::InappropriateMessage {
139 ref expect_types,
140 ref got_type,
141 } => write!(
142 f,
143 "received unexpected message: got {:?} when expecting {}",
144 got_type,
145 join::<ContentType>(expect_types)
146 ),
147 Self::InappropriateHandshakeMessage {
148 ref expect_types,
149 ref got_type,
150 } => write!(
151 f,
152 "received unexpected handshake message: got {:?} when expecting {}",
153 got_type,
154 join::<HandshakeType>(expect_types)
155 ),
156 Self::CorruptMessagePayload(ref typ) => {
157 write!(f, "received corrupt message of type {:?}", typ)
158 }
159 Self::PeerIncompatibleError(ref why) => write!(f, "peer is incompatible: {}", why),
160 Self::PeerMisbehavedError(ref why) => write!(f, "peer misbehaved: {}", why),
161 Self::AlertReceived(ref alert) => write!(f, "received fatal alert: {:?}", alert),
162 Self::InvalidCertificateEncoding => {
163 write!(f, "invalid peer certificate encoding")
164 }
165 Self::InvalidCertificateSignatureType => {
166 write!(f, "invalid peer certificate signature type")
167 }
168 Self::InvalidCertificateSignature => {
169 write!(f, "invalid peer certificate signature")
170 }
171 Self::InvalidCertificateData(ref reason) => {
172 write!(f, "invalid peer certificate contents: {}", reason)
173 }
174 Self::CorruptMessage => write!(f, "received corrupt message"),
175 Self::NoCertificatesPresented => write!(f, "peer sent no certificates"),
176 Self::UnsupportedNameType => write!(f, "presented server name type wasn't supported"),
177 Self::DecryptError => write!(f, "cannot decrypt peer's message"),
178 Self::EncryptError => write!(f, "cannot encrypt message"),
179 Self::PeerSentOversizedRecord => write!(f, "peer sent excess record size"),
180 Self::HandshakeNotComplete => write!(f, "handshake not complete"),
181 Self::NoApplicationProtocol => write!(f, "peer doesn't support any known protocol"),
182 Self::InvalidSct(ref err) => write!(f, "invalid certificate timestamp: {:?}", err),
183 Self::FailedToGetCurrentTime => write!(f, "failed to get current time"),
184 Self::FailedToGetRandomBytes => write!(f, "failed to get random bytes"),
185 Self::BadMaxFragmentSize => {
186 write!(f, "the supplied max_fragment_size was too small or large")
187 }
188 Self::General(ref err) => write!(f, "unexpected error: {}", err),
189 }
190 }
191}
192
193impl From<SystemTimeError> for Error {
194 #[inline]
195 fn from(_: SystemTimeError) -> Self {
196 Self::FailedToGetCurrentTime
197 }
198}
199
200impl StdError for Error {}
201
202impl From<rand::GetRandomFailed> for Error {
203 fn from(_: rand::GetRandomFailed) -> Self {
204 Self::FailedToGetRandomBytes
205 }
206}
207
208#[cfg(test)]
209mod tests {
210 use super::{CorruptMessagePayload, Error};
211
212 #[test_log::test]
213 fn smoke() {
214 use sct;
215
216 use crate::tls::rustls::msgs::enums::{AlertDescription, ContentType, HandshakeType};
217
218 let _all = vec![
219 Error::InappropriateMessage {
220 expect_types: vec![ContentType::Alert],
221 got_type: ContentType::Handshake,
222 },
223 Error::InappropriateHandshakeMessage {
224 expect_types: vec![HandshakeType::ClientHello, HandshakeType::Finished],
225 got_type: HandshakeType::ServerHello,
226 },
227 Error::CorruptMessage,
228 Error::CorruptMessagePayload(CorruptMessagePayload {
229 location: core::panic::Location::caller(),
230 kind: ContentType::Alert,
231 }),
232 Error::NoCertificatesPresented,
233 Error::DecryptError,
234 Error::PeerIncompatibleError("no tls1.2".to_string()),
235 Error::PeerMisbehavedError("inconsistent something".to_string()),
236 Error::AlertReceived(AlertDescription::ExportRestriction),
237 Error::InvalidCertificateEncoding,
238 Error::InvalidCertificateSignatureType,
239 Error::InvalidCertificateSignature,
240 Error::InvalidCertificateData("Data".into()),
241 Error::InvalidSct(sct::Error::MalformedSct),
242 Error::General("undocumented error".to_string()),
243 Error::FailedToGetCurrentTime,
244 Error::FailedToGetRandomBytes,
245 Error::HandshakeNotComplete,
246 Error::PeerSentOversizedRecord,
247 Error::NoApplicationProtocol,
248 Error::BadMaxFragmentSize,
249 ];
250
251 }
256
257 #[test_log::test]
258 fn rand_error_mapping() {
259 use super::rand;
260 let err: Error = rand::GetRandomFailed.into();
261 assert_eq!(err, Error::FailedToGetRandomBytes);
262 }
263
264 #[test_log::test]
265 fn time_error_mapping() {
266 use std::time::SystemTime;
267
268 let time_error = SystemTime::UNIX_EPOCH
269 .duration_since(SystemTime::now())
270 .unwrap_err();
271 let err: Error = time_error.into();
272 assert_eq!(err, Error::FailedToGetCurrentTime);
273 }
274}