Debian Codegraph @

crt/s2n/bindings/rust/extended/s2n-tls/src/error.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 use core::{convert::TryInto, fmt, ptr::NonNull, task::Poll};
5 use errno::{errno, Errno};
6 use s2n_tls_sys::*;
7 use std::convert::TryFrom;
8
9 use crate::utilities::cstr_to_str;
10
11 /// Corresponds to [`s2n_error_type`].
12 #[non_exhaustive]
13 #[derive(Copy, Clone, Debug, PartialEq)]
14 pub enum ErrorType {
15 UnknownErrorType,
16 NoError,
17 /// The underlying I/O operation failed, check the system errno
18 IOError,
19 /// EoF
20 ConnectionClosed,
21 /// The underlying I/O operation would block
22 Blocked,
23 /// Incoming Alert
24 Alert,
25 /// Failure in some part of the TLS protocol. E.g. CBC verification failure
26 ProtocolError,
27 /// Error internal to s2n-tls. Feel free to open an issue if you see this: https://github.com/aws/s2n-tls/issues/new/choose
28 InternalError,
29 /// User input error. E.g. Providing an invalid security policy version string
30 UsageError,
31 Application,
32 }
33
34 #[non_exhaustive]
35 #[derive(Debug, PartialEq)]
36 pub enum ErrorSource {
37 Library,
38 Bindings,
39 Application,
40 }
41
42 impl From<libc::c_int> for ErrorType {
43 fn from(input: libc::c_int) -> Self {
44 match input as s2n_error_type::Type {
45 s2n_error_type::OK => ErrorType::NoError,
46 s2n_error_type::IO => ErrorType::IOError,
47 s2n_error_type::CLOSED => ErrorType::ConnectionClosed,
48 s2n_error_type::BLOCKED => ErrorType::Blocked,
49 s2n_error_type::ALERT => ErrorType::Alert,
50 s2n_error_type::PROTO => ErrorType::ProtocolError,
51 s2n_error_type::INTERNAL => ErrorType::InternalError,
52 s2n_error_type::USAGE => ErrorType::UsageError,
53 _ => ErrorType::UnknownErrorType,
54 }
55 }
56 }
57
58 enum Context {
59 Bindings(ErrorType, &'static str, &'static str),
60 Code(s2n_status_code::Type, Errno),
61 Application(Box<dyn std::error::Error + Send + Sync + 'static>),
62 }
63
64 pub struct Error(Context);
65
66 pub trait Fallible {
67 type Output;
68
69 fn into_result(self) -> Result<Self::Output, Error>;
70 }
71
72 impl Fallible for s2n_status_code::Type {
73 type Output = s2n_status_code::Type;
74
75 fn into_result(self) -> Result<Self::Output, Error> {
76 if self >= s2n_status_code::SUCCESS {
77 Ok(self)
78 } else {
79 Err(Error::capture())
80 }
81 }
82 }
83
84 impl Fallible for isize {
85 type Output = usize;
86
87 fn into_result(self) -> Result<Self::Output, Error> {
88 // Negative values can't be converted to a real size
89 // and instead indicate an error.
90 self.try_into().map_err(|_| Error::capture())
91 }
92 }
93
94 impl Fallible for u64 {
95 type Output = Self;
96
97 /// Converts a u64 to a Result by checking for u64::MAX.
98 ///
99 /// If a method that returns an unsigned int is fallible,
100 /// then the -1 error result wraps around to u64::MAX.
101 ///
102 /// For a u64 to be Fallible, a result of u64::MAX must not be
103 /// possible without an error. For example, [`s2n_connection_get_delay`]
104 /// can't return u64::MAX as a valid result because
105 /// s2n-tls blinding delays are limited to 30s, or a return value of 3^10 ns,
106 /// which is significantly less than u64::MAX. [`s2n_connection_get_delay`]
107 /// would therefore only return u64::MAX for a -1 error result.
108 fn into_result(self) -> Result<Self::Output, Error> {
109 if self != Self::MAX {
110 Ok(self)
111 } else {
112 Err(Error::capture())
113 }
114 }
115 }
116
117 impl<T> Fallible for *mut T {
118 type Output = NonNull<T>;
119
120 fn into_result(self) -> Result<Self::Output, Error> {
121 if let Some(value) = NonNull::new(self) {
122 Ok(value)
123 } else {
124 Err(Error::capture())
125 }
126 }
127 }
128
129 impl<T> Fallible for *const T {
130 type Output = *const T;
131
132 fn into_result(self) -> Result<Self::Output, Error> {
133 if !self.is_null() {
134 Ok(self)
135 } else {
136 Err(Error::capture())
137 }
138 }
139 }
140
141 pub trait Pollable {
142 type Output;
143
144 fn into_poll(self) -> Poll<Result<Self::Output, Error>>;
145 }
146
147 impl<T: Fallible> Pollable for T {
148 type Output = T::Output;
149
150 fn into_poll(self) -> Poll<Result<Self::Output, Error>> {
151 match self.into_result() {
152 Ok(r) => Ok(r).into(),
153 Err(err) if err.is_retryable() => Poll::Pending,
154 Err(err) => Err(err).into(),
155 }
156 }
157 }
158
159 impl Error {
160 pub(crate) const INVALID_INPUT: Error = Self::bindings(
161 ErrorType::UsageError,
162 "InvalidInput",
163 "An input parameter was incorrect",
164 );
165 pub(crate) const MISSING_WAKER: Error = Self::bindings(
166 ErrorType::UsageError,
167 "MissingWaker",
168 "Tried to perform an asynchronous operation without a configured waker",
169 );
170
171 /// Converts an io::Error into an s2n-tls Error
172 pub fn io_error(err: std::io::Error) -> Error {
173 let errno = err.raw_os_error().unwrap_or(1);
174 errno::set_errno(errno::Errno(errno));
175 s2n_status_code::FAILURE.into_result().unwrap_err()
176 }
177
178 /// An error occurred while running application code.
179 ///
180 /// Can be emitted from [`crate::callbacks::ConnectionFuture::poll()`] to indicate
181 /// async task failure.
182 pub fn application(error: Box<dyn std::error::Error + Send + Sync + 'static>) -> Self {
183 Self(Context::Application(error))
184 }
185
186 /// An error occurred while running bindings code.
187 pub(crate) const fn bindings(
188 kind: ErrorType,
189 name: &'static str,
190 message: &'static str,
191 ) -> Self {
192 Self(Context::Bindings(kind, name, message))
193 }
194
195 fn capture() -> Self {
196 unsafe {
197 let s2n_errno = s2n_errno_location();
198
199 let code = *s2n_errno;
200
201 // https://github.com/aws/s2n-tls/blob/main/docs/USAGE-GUIDE.md#error-handling
202 //# To avoid possible confusion, s2n_errno should be cleared after processing
203 //# an error: s2n_errno = S2N_ERR_T_OK
204 *s2n_errno = s2n_error_type::OK as _;
205
206 Self(Context::Code(code, errno()))
207 }
208 }
209
210 /// Corresponds to [`s2n_strerror_name`] for ErrorSource::Library errors.
211 pub fn name(&self) -> &'static str {
212 match self.0 {
213 Context::Bindings(_, name, _) => name,
214 Context::Application(_) => "ApplicationError",
215 Context::Code(code, _) => unsafe {
216 // Safety: we assume the string has a valid encoding coming from s2n
217 cstr_to_str(s2n_strerror_name(code))
218 },
219 }
220 }
221
222 /// Corresponds to [`s2n_strerror`] for ErrorSource::Library errors.
223 pub fn message(&self) -> &'static str {
224 match self.0 {
225 Context::Bindings(_, _, msg) => msg,
226 Context::Application(_) => "An error occurred while executing application code",
227 Context::Code(code, _) => unsafe {
228 // Safety: we assume the string has a valid encoding coming from s2n
229 cstr_to_str(s2n_strerror(code, core::ptr::null()))
230 },
231 }
232 }
233
234 /// Corresponds to [`s2n_strerror_debug`] for ErrorSource::Library errors.
235 pub fn debug(&self) -> Option<&'static str> {
236 match self.0 {
237 Context::Bindings(_, _, _) | Context::Application(_) => None,
238 Context::Code(code, _) => unsafe {
239 let debug_info = s2n_strerror_debug(code, core::ptr::null());
240
241 // The debug string should be set to a constant static string
242 // when an error occurs, but because it starts out as NULL
243 // we should defend against mistakes.
244 if debug_info.is_null() {
245 None
246 } else {
247 // If the string is not null, then we can assume that
248 // it is constant and static.
249 Some(cstr_to_str(debug_info))
250 }
251 },
252 }
253 }
254
255 /// Corresponds to [`s2n_error_get_type`] for ErrorSource::Library errors.
256 pub fn kind(&self) -> ErrorType {
257 match self.0 {
258 Context::Bindings(error_type, _, _) => error_type,
259 Context::Application(_) => ErrorType::Application,
260 Context::Code(code, _) => unsafe { ErrorType::from(s2n_error_get_type(code)) },
261 }
262 }
263
264 pub fn source(&self) -> ErrorSource {
265 match self.0 {
266 Context::Bindings(_, _, _) => ErrorSource::Bindings,
267 Context::Application(_) => ErrorSource::Application,
268 Context::Code(_, _) => ErrorSource::Library,
269 }
270 }
271
272 #[allow(clippy::borrowed_box)]
273 /// Returns an [`std::error::Error`] if the error source was [`ErrorSource::Application`],
274 /// otherwise returns None.
275 pub fn application_error(&self) -> Option<&Box<dyn std::error::Error + Send + Sync + 'static>> {
276 if let Self(Context::Application(err)) = self {
277 Some(err)
278 } else {
279 None
280 }
281 }
282
283 pub fn is_retryable(&self) -> bool {
284 matches!(self.kind(), ErrorType::Blocked)
285 }
286 }
287
288 #[cfg(feature = "quic")]
289 impl Error {
290 /// s2n-tls does not send specific errors.
291 ///
292 /// However, we can attempt to map local errors into the alerts
293 /// that we would have sent if we sent alerts.
294 ///
295 /// This API is currently incomplete and should not be relied upon.
296 ///
297 /// Corresponds to [`s2n_error_get_alert`] for ErrorSource::Library errors.
298 pub fn alert(&self) -> Option<u8> {
299 match self.0 {
300 Context::Bindings(_, _, _) | Context::Application(_) => None,
301 Context::Code(code, _) => {
302 let mut alert = 0;
303 let r = unsafe { s2n_error_get_alert(code, &mut alert) };
304 match r.into_result() {
305 Ok(_) => Some(alert),
306 Err(_) => None,
307 }
308 }
309 }
310 }
311 }
312
313 impl TryFrom<std::io::Error> for Error {
314 type Error = Error;
315 fn try_from(value: std::io::Error) -> Result<Self, Self::Error> {
316 let io_inner = value.into_inner().ok_or(Error::INVALID_INPUT)?;
317 io_inner
318 .downcast::<Self>()
319 .map(|error| *error)
320 .map_err(|_| Error::INVALID_INPUT)
321 }
322 }
323
324 impl From<Error> for std::io::Error {
325 fn from(input: Error) -> Self {
326 let kind = match input.kind() {
327 ErrorType::IOError => {
328 if let Context::Code(_, errno) = input.0 {
329 let bare = std::io::Error::from_raw_os_error(errno.0);
330 bare.kind()
331 } else {
332 std::io::ErrorKind::Other
333 }
334 }
335 ErrorType::ConnectionClosed => std::io::ErrorKind::UnexpectedEof,
336 _ => std::io::ErrorKind::Other,
337 };
338 std::io::Error::new(kind, input)
339 }
340 }
341
342 impl fmt::Debug for Error {
343 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
344 // Application errors don't carry any interesting s2n context, so
345 // forward directly to the underyling error.
346 if let Self(Context::Application(err)) = self {
347 return err.fmt(f);
348 }
349
350 let mut s = f.debug_struct("Error");
351 if let Context::Code(code, _) = self.0 {
352 s.field("code", &code);
353 }
354
355 s.field("name", &self.name());
356 s.field("message", &self.message());
357 s.field("kind", &self.kind());
358 s.field("source", &self.source());
359
360 if let Some(debug) = self.debug() {
361 s.field("debug", &debug);
362 }
363
364 // "errno" is only known to be meaningful for IOErrors.
365 // However, it has occasionally proved useful for debugging
366 // other errors, so include it for all errors.
367 if let Context::Code(_, errno) = self.0 {
368 s.field("errno", &errno.to_string());
369 }
370
371 s.finish()
372 }
373 }
374
375 impl fmt::Display for Error {
376 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
377 if let Self(Context::Application(err)) = self {
378 err.fmt(f)
379 } else {
380 f.write_str(self.message())
381 }
382 }
383 }
384
385 impl std::error::Error for Error {
386 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
387 // implement `source` in the same way `std::io::Error` implements it:
388 // https://doc.rust-lang.org/std/io/struct.Error.html#method.source
389 if let Self(Context::Application(err)) = self {
390 err.source()
391 } else {
392 None
393 }
394 }
395 }
396
397 #[cfg(test)]
398 mod tests {
399 use super::*;
400 use crate::{enums::Version, testing::client_hello::CustomError};
401 use errno::set_errno;
402
403 const FAILURE: isize = -1;
404
405 // This relies on an implementation detail of s2n-tls errors,
406 // and could make these tests brittle. However, the alternative
407 // is a real handshake producing a real IO error, so just updating
408 // this value if the definition of an IO error changes might be easier.
409 const S2N_IO_ERROR_CODE: s2n_status_code::Type = 1 << 26;
410
411 #[test]
412 fn s2n_io_error_to_std_io_error() -> Result<(), Box<dyn std::error::Error>> {
413 set_errno(Errno(libc::ECONNRESET));
414 unsafe {
415 let s2n_errno_ptr = s2n_errno_location();
416 *s2n_errno_ptr = S2N_IO_ERROR_CODE;
417 }
418
419 let s2n_error = FAILURE.into_result().unwrap_err();
420 assert_eq!(ErrorType::IOError, s2n_error.kind());
421
422 let io_error = std::io::Error::from(s2n_error);
423 assert_eq!(std::io::ErrorKind::ConnectionReset, io_error.kind());
424 assert!(io_error.into_inner().is_some());
425 Ok(())
426 }
427
428 #[test]
429 fn s2n_error_to_std_io_error() -> Result<(), Box<dyn std::error::Error>> {
430 set_errno(Errno(libc::ECONNRESET));
431 unsafe {
432 let s2n_errno_ptr = s2n_errno_location();
433 *s2n_errno_ptr = S2N_IO_ERROR_CODE - 1;
434 }
435
436 let s2n_error = FAILURE.into_result().unwrap_err();
437 assert_ne!(ErrorType::IOError, s2n_error.kind());
438
439 let io_error = std::io::Error::from(s2n_error);
440 assert_eq!(std::io::ErrorKind::Other, io_error.kind());
441 assert!(io_error.into_inner().is_some());
442 Ok(())
443 }
444
445 #[test]
446 fn invalid_input_to_std_io_error() -> Result<(), Box<dyn std::error::Error>> {
447 let s2n_error = Version::try_from(0).unwrap_err();
448 assert_eq!(ErrorType::UsageError, s2n_error.kind());
449
450 let io_error = std::io::Error::from(s2n_error);
451 assert_eq!(std::io::ErrorKind::Other, io_error.kind());
452 assert!(io_error.into_inner().is_some());
453 Ok(())
454 }
455
456 #[test]
457 fn error_source() -> Result<(), Box<dyn std::error::Error>> {
458 let bindings_error = Version::try_from(0).unwrap_err();
459 assert_eq!(ErrorSource::Bindings, bindings_error.source());
460
461 let library_error = FAILURE.into_result().unwrap_err();
462 assert_eq!(ErrorSource::Library, library_error.source());
463
464 Ok(())
465 }
466
467 #[test]
468 fn application_error() {
469 // test single level errors
470 {
471 let error = Error::application(Box::new(CustomError));
472
473 let app_error = error.application_error().unwrap();
474 let _custom_error = app_error.downcast_ref::<CustomError>().unwrap();
475
476 let display = format!("{error}");
477 assert_eq!(display, "custom error");
478 let debug = format!("{error:?}");
479 assert_eq!(debug, "CustomError");
480 }
481
482 // make sure nested errors work
483 {
484 let io_error = std::io::Error::other(CustomError);
485 let error = Error::application(Box::new(io_error));
486
487 let app_error = error.application_error().unwrap();
488 let io_error = app_error.downcast_ref::<std::io::Error>().unwrap();
489 let _custom_error = io_error
490 .get_ref()
491 .unwrap()
492 .downcast_ref::<CustomError>()
493 .unwrap();
494 }
495 }
496
497 #[test]
498 fn bindings_error() {
499 let name = "TestError";
500 let message = "Custom error for test";
501 let kind = ErrorType::InternalError;
502 let error = Error::bindings(kind, name, message);
503 assert_eq!(error.kind(), kind);
504 assert_eq!(error.name(), name);
505 assert_eq!(error.message(), message);
506 assert_eq!(error.debug(), None);
507 assert_eq!(error.source(), ErrorSource::Bindings);
508 }
509 }