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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

use crate::{
    application, connection, crypto::packet_protection, endpoint, frame::ConnectionClose, transport,
};
use core::{fmt, panic, time::Duration};

/// Errors that a connection can encounter.
#[derive(Debug, Copy, Clone)]
#[non_exhaustive]
pub enum Error {
    /// The connection was closed without an error
    #[non_exhaustive]
    Closed {
        initiator: endpoint::Location,
        source: &'static panic::Location<'static>,
    },

    /// The connection was closed on the transport level
    ///
    /// This can occur either locally or by the peer. The argument contains
    /// the error code which the transport provided in order to close the
    /// connection.
    #[non_exhaustive]
    Transport {
        code: transport::error::Code,
        frame_type: u64,
        reason: &'static str,
        initiator: endpoint::Location,
        source: &'static panic::Location<'static>,
    },

    /// The connection was closed on the application level
    ///
    /// This can occur either locally or by the peer. The argument contains
    /// the error code which the application/ supplied in order to close the
    /// connection.
    #[non_exhaustive]
    Application {
        error: application::Error,
        initiator: endpoint::Location,
        source: &'static panic::Location<'static>,
    },

    /// The connection was reset by a stateless reset from the peer
    #[non_exhaustive]
    StatelessReset {
        source: &'static panic::Location<'static>,
    },

    /// The connection was closed because the local connection's idle timer expired
    #[non_exhaustive]
    IdleTimerExpired {
        source: &'static panic::Location<'static>,
    },

    /// The connection was closed because there are no valid paths
    #[non_exhaustive]
    NoValidPath {
        source: &'static panic::Location<'static>,
    },

    /// All Stream IDs for Streams on the given connection had been exhausted
    #[non_exhaustive]
    StreamIdExhausted {
        source: &'static panic::Location<'static>,
    },

    /// The handshake has taken longer to complete than the configured max handshake duration
    #[non_exhaustive]
    MaxHandshakeDurationExceeded {
        max_handshake_duration: Duration,
        source: &'static panic::Location<'static>,
    },

    /// The connection should be closed immediately without notifying the peer
    #[non_exhaustive]
    ImmediateClose {
        reason: &'static str,
        source: &'static panic::Location<'static>,
    },

    /// The connection attempt was rejected because the endpoint is closing
    #[non_exhaustive]
    EndpointClosing {
        source: &'static panic::Location<'static>,
    },

    /// The connection was closed due to an unspecified reason
    #[non_exhaustive]
    Unspecified {
        source: &'static panic::Location<'static>,
    },
}

#[cfg(feature = "std")]
impl std::error::Error for Error {}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Closed { initiator, .. } => write!(
                f,
                "The connection was closed without an error by {initiator}"
            ),
            Self::Transport { code, frame_type, reason, initiator, .. } => {
                let error = transport::Error {
                    code: *code,
                    frame_type: (*frame_type).try_into().ok().unwrap_or_default(),
                    reason,
                };
                write!(
                    f,
                    "The connection was closed on the transport level with error {error} by {initiator}"
                )
            },
            Self::Application { error, initiator, .. } => write!(
                f,
                "The connection was closed on the application level with error {error:?} by {initiator}"
            ),
            Self::StatelessReset { .. } => write!(
                f,
                "The connection was reset by a stateless reset by {}",
                endpoint::Location::Remote
            ),
            Self::IdleTimerExpired {.. } => write!(
                f,
                "The connection was closed because the connection's idle timer expired by {}",
                endpoint::Location::Local
            ),
            Self::NoValidPath { .. } => write!(
                f,
                "The connection was closed because there are no valid paths"
            ),
            Self::StreamIdExhausted { .. } => write!(
                f,
                "All Stream IDs for Streams on the given connection had been exhausted"
            ),
            Self::MaxHandshakeDurationExceeded { max_handshake_duration, .. } => write!(
              f,
                "The connection was closed because the handshake took longer than the max handshake \
                duration of {max_handshake_duration:?}"
            ),
            Self::ImmediateClose { reason, .. } => write!(
                f,
                "The connection was closed due to: {reason}"
            ),
            Self::EndpointClosing { .. } => {
                write!(f, "The connection attempt was rejected because the endpoint is closing")
            }
            Self::Unspecified { .. } => {
                write!(f, "The connection was closed due to an unspecified reason")
            }
        }
    }
}

impl PartialEq for Error {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        // ignore the `source` attribute when considering if errors are equal
        match (self, other) {
            (Error::Closed { initiator: a, .. }, Error::Closed { initiator: b, .. }) => a.eq(b),
            (
                Error::Transport {
                    code: a_code,
                    frame_type: a_frame_type,
                    reason: a_reason,
                    initiator: a_initiator,
                    ..
                },
                Error::Transport {
                    code: b_code,
                    frame_type: b_frame_type,
                    reason: b_reason,
                    initiator: b_initiator,
                    ..
                },
            ) => {
                a_code.eq(b_code)
                    && a_frame_type.eq(b_frame_type)
                    && a_reason.eq(b_reason)
                    && a_initiator.eq(b_initiator)
            }
            (
                Error::Application {
                    error: a_error,
                    initiator: a_initiator,
                    ..
                },
                Error::Application {
                    error: b_error,
                    initiator: b_initiator,
                    ..
                },
            ) => a_error.eq(b_error) && a_initiator.eq(b_initiator),
            (Error::StatelessReset { .. }, Error::StatelessReset { .. }) => true,
            (Error::IdleTimerExpired { .. }, Error::IdleTimerExpired { .. }) => true,
            (Error::NoValidPath { .. }, Error::NoValidPath { .. }) => true,
            (Error::StreamIdExhausted { .. }, Error::StreamIdExhausted { .. }) => true,
            (
                Error::MaxHandshakeDurationExceeded {
                    max_handshake_duration: a,
                    ..
                },
                Error::MaxHandshakeDurationExceeded {
                    max_handshake_duration: b,
                    ..
                },
            ) => a.eq(b),
            (Error::ImmediateClose { reason: a, .. }, Error::ImmediateClose { reason: b, .. }) => {
                a.eq(b)
            }
            (Error::EndpointClosing { .. }, Error::EndpointClosing { .. }) => true,
            (Error::Unspecified { .. }, Error::Unspecified { .. }) => true,
            _ => false,
        }
    }
}

impl Eq for Error {}

impl Error {
    /// Returns the [`panic::Location`] for the error
    pub fn source(&self) -> &'static panic::Location<'static> {
        match self {
            Error::Closed { source, .. } => source,
            Error::Transport { source, .. } => source,
            Error::Application { source, .. } => source,
            Error::StatelessReset { source } => source,
            Error::IdleTimerExpired { source } => source,
            Error::NoValidPath { source } => source,
            Error::StreamIdExhausted { source } => source,
            Error::MaxHandshakeDurationExceeded { source, .. } => source,
            Error::ImmediateClose { source, .. } => source,
            Error::EndpointClosing { source } => source,
            Error::Unspecified { source } => source,
        }
    }

    #[track_caller]
    fn from_transport_error(error: transport::Error, initiator: endpoint::Location) -> Self {
        let source = panic::Location::caller();
        match error.code {
            // The connection closed without an error
            code if code == transport::Error::NO_ERROR.code => Self::Closed { initiator, source },
            // The connection closed without an error at the application layer
            code if code == transport::Error::APPLICATION_ERROR.code && initiator.is_remote() => {
                Self::Closed { initiator, source }
            }
            // The connection closed with an actual error
            _ => Self::Transport {
                code: error.code,
                frame_type: error.frame_type.into(),
                reason: error.reason,
                initiator,
                source,
            },
        }
    }

    #[inline]
    #[track_caller]
    #[doc(hidden)]
    pub fn closed(initiator: endpoint::Location) -> Error {
        let source = panic::Location::caller();
        Error::Closed { initiator, source }
    }

    #[inline]
    #[track_caller]
    #[doc(hidden)]
    pub fn immediate_close(reason: &'static str) -> Error {
        let source = panic::Location::caller();
        Error::ImmediateClose { reason, source }
    }

    #[inline]
    #[track_caller]
    #[doc(hidden)]
    pub fn idle_timer_expired() -> Error {
        let source = panic::Location::caller();
        Error::IdleTimerExpired { source }
    }

    #[inline]
    #[track_caller]
    #[doc(hidden)]
    pub fn stream_id_exhausted() -> Error {
        let source = panic::Location::caller();
        Error::StreamIdExhausted { source }
    }

    #[inline]
    #[track_caller]
    #[doc(hidden)]
    pub fn no_valid_path() -> Error {
        let source = panic::Location::caller();
        Error::NoValidPath { source }
    }

    #[inline]
    #[track_caller]
    #[doc(hidden)]
    pub fn stateless_reset() -> Error {
        let source = panic::Location::caller();
        Error::StatelessReset { source }
    }

    #[inline]
    #[track_caller]
    #[doc(hidden)]
    pub fn max_handshake_duration_exceeded(max_handshake_duration: Duration) -> Error {
        let source = panic::Location::caller();
        Error::MaxHandshakeDurationExceeded {
            max_handshake_duration,
            source,
        }
    }

    #[inline]
    #[track_caller]
    #[doc(hidden)]
    pub fn application(error: application::Error) -> Error {
        let source = panic::Location::caller();
        Error::Application {
            error,
            initiator: endpoint::Location::Local,
            source,
        }
    }

    #[inline]
    #[track_caller]
    #[doc(hidden)]
    pub fn endpoint_closing() -> Error {
        let source = panic::Location::caller();
        Error::EndpointClosing { source }
    }

    #[inline]
    #[track_caller]
    #[doc(hidden)]
    pub fn unspecified() -> Error {
        let source = panic::Location::caller();
        Error::Unspecified { source }
    }

    #[inline]
    #[doc(hidden)]
    pub fn into_accept_error(error: connection::Error) -> Result<(), connection::Error> {
        match error {
            // The connection closed without an error
            connection::Error::Closed { .. } => Ok(()),
            // The application closed the connection
            connection::Error::Transport { code, .. }
                if code == transport::Error::APPLICATION_ERROR.code =>
            {
                Ok(())
            }
            // The local connection's idle timer expired
            connection::Error::IdleTimerExpired { .. } => Ok(()),
            // Otherwise return the real error to the user
            _ => Err(error),
        }
    }
}

/// Returns a CONNECTION_CLOSE frame for the given connection Error, if any
///
/// The first item will be a close frame for an early (initial, handshake) packet.
/// The second item will be a close frame for a 1-RTT (application data) packet.
pub fn as_frame<'a, F: connection::close::Formatter>(
    error: Error,
    formatter: &'a F,
    context: &'a connection::close::Context<'a>,
) -> Option<(ConnectionClose<'a>, ConnectionClose<'a>)> {
    match error {
        Error::Closed { initiator, .. } => {
            // don't send CONNECTION_CLOSE frames on remote-initiated errors
            if initiator.is_remote() {
                return None;
            }

            let error = transport::Error::NO_ERROR;
            let early = formatter.format_early_transport_error(context, error);
            let one_rtt = formatter.format_transport_error(context, error);

            Some((early, one_rtt))
        }
        Error::Transport {
            code,
            frame_type,
            reason,
            initiator,
            ..
        } => {
            // don't send CONNECTION_CLOSE frames on remote-initiated errors
            if initiator.is_remote() {
                return None;
            }

            let error = transport::Error {
                code,
                frame_type: frame_type.try_into().unwrap_or_default(),
                reason,
            };

            let early = formatter.format_early_transport_error(context, error);
            let one_rtt = formatter.format_transport_error(context, error);
            Some((early, one_rtt))
        }
        Error::Application {
            error, initiator, ..
        } => {
            // don't send CONNECTION_CLOSE frames on remote-initiated errors
            if initiator.is_remote() {
                return None;
            }

            let early = formatter.format_early_application_error(context, error);
            let one_rtt = formatter.format_application_error(context, error);
            Some((early, one_rtt))
        }
        // This error comes from the peer so we don't respond with a CONNECTION_CLOSE
        Error::StatelessReset { .. } => None,
        // Nothing gets sent on idle timeouts
        Error::IdleTimerExpired { .. } => None,
        Error::NoValidPath { .. } => None,
        Error::StreamIdExhausted { .. } => {
            let error =
                transport::Error::PROTOCOL_VIOLATION.with_reason("stream IDs have been exhausted");

            let early = formatter.format_early_transport_error(context, error);
            let one_rtt = formatter.format_transport_error(context, error);

            Some((early, one_rtt))
        }
        Error::MaxHandshakeDurationExceeded { .. } => None,
        Error::ImmediateClose { .. } => None,
        Error::EndpointClosing { .. } => None,
        Error::Unspecified { .. } => {
            let error =
                transport::Error::INTERNAL_ERROR.with_reason("an unspecified error occurred");

            let early = formatter.format_early_transport_error(context, error);
            let one_rtt = formatter.format_transport_error(context, error);

            Some((early, one_rtt))
        }
    }
}

impl application::error::TryInto for Error {
    fn application_error(&self) -> Option<application::Error> {
        if let Self::Application { error, .. } = self {
            Some(*error)
        } else {
            None
        }
    }
}

impl From<transport::Error> for Error {
    #[track_caller]
    fn from(error: transport::Error) -> Self {
        Self::from_transport_error(error, endpoint::Location::Local)
    }
}

impl<'a> From<ConnectionClose<'a>> for Error {
    #[track_caller]
    fn from(error: ConnectionClose) -> Self {
        if let Some(frame_type) = error.frame_type {
            let error = transport::Error {
                code: transport::error::Code::new(error.error_code),
                // we use an empty `&'static str` so we don't allocate anything
                // in the event of an error
                reason: "",
                frame_type,
            };
            Self::from_transport_error(error, endpoint::Location::Remote)
        } else {
            let source = panic::Location::caller();
            Self::Application {
                error: error.error_code.into(),
                initiator: endpoint::Location::Remote,
                source,
            }
        }
    }
}

#[cfg(feature = "std")]
impl From<Error> for std::io::Error {
    fn from(error: Error) -> Self {
        let kind = error.into();
        std::io::Error::new(kind, error)
    }
}

#[cfg(feature = "std")]
impl From<Error> for std::io::ErrorKind {
    fn from(error: Error) -> Self {
        use std::io::ErrorKind;
        match error {
            Error::Closed { .. } => ErrorKind::ConnectionAborted,
            Error::Transport { code, .. } if code == transport::Error::CONNECTION_REFUSED.code => {
                ErrorKind::ConnectionRefused
            }
            Error::Transport { .. } => ErrorKind::ConnectionReset,
            Error::Application { .. } => ErrorKind::ConnectionReset,
            Error::StatelessReset { .. } => ErrorKind::ConnectionReset,
            Error::IdleTimerExpired { .. } => ErrorKind::TimedOut,
            Error::NoValidPath { .. } => ErrorKind::Other,
            Error::StreamIdExhausted { .. } => ErrorKind::Other,
            Error::MaxHandshakeDurationExceeded { .. } => ErrorKind::TimedOut,
            Error::ImmediateClose { .. } => ErrorKind::Other,
            Error::EndpointClosing { .. } => ErrorKind::Other,
            Error::Unspecified { .. } => ErrorKind::Other,
        }
    }
}

/// Some connection methods may need to indicate both `ConnectionError`s and `DecryptError`s. This
/// enum is used to allow for either error type to be returned as appropriate.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ProcessingError {
    ConnectionError(Error),
    DecryptError,
    Other,
}

impl From<Error> for ProcessingError {
    fn from(inner_error: Error) -> Self {
        ProcessingError::ConnectionError(inner_error)
    }
}

impl From<crate::transport::Error> for ProcessingError {
    #[track_caller]
    fn from(inner_error: crate::transport::Error) -> Self {
        Self::ConnectionError(inner_error.into())
    }
}

impl From<packet_protection::Error> for ProcessingError {
    fn from(_: packet_protection::Error) -> Self {
        Self::DecryptError
    }
}