Skip to main content

rtci_turn/client/
error.rs

1use std::fmt;
2use std::net::SocketAddr;
3
4use shared::error::Error;
5use stun::addr::MappedAddress;
6use stun::alternate::TryAlternate;
7use stun::attributes::{ATTR_ALTERNATE_SERVER, AttrType};
8use stun::error_code::{ErrorCode, ErrorCodeAttribute};
9use stun::message::Getter;
10use stun::uattrs::UnknownAttributes;
11use stun::validated::ValidatedMessage;
12
13/// An error response from the server: its code and what a client acts on with it.
14#[derive(Clone, PartialEq, Eq)]
15#[non_exhaustive]
16pub struct ErrorResponse {
17    /// The STUN error code, for example 437 (`stun::error_code::CODE_ALLOC_MISMATCH`).
18    pub code: ErrorCode,
19    /// The reason phrase the server sent. For people; nothing depends on its text.
20    pub reason: String,
21    /// The ALTERNATE-SERVER of a 300 (Try Alternate): the server to use instead
22    /// (RFC 8489 §10, RFC 8656 §7.4). It is reported whether or not the response was
23    /// authenticated; see `try_alternate`.
24    pub alternate_server: Option<SocketAddr>,
25    /// The redirection of a 300 (Try Alternate) that was authenticated with the request's
26    /// credential: every ALTERNATE-SERVER and the ALTERNATE-DOMAIN. RFC 8489 §14.8 has a
27    /// client validate the response before it redirects itself, so this is `None` for a 300
28    /// that was not signed, such as one to the first Allocate, which carries no credential.
29    /// [`Client::follow_alternate`](super::Client::follow_alternate) takes it.
30    pub try_alternate: Option<TryAlternate>,
31    /// The attributes a 420 (Unknown Attribute) says the server did not understand.
32    pub unknown_attributes: Vec<AttrType>,
33}
34
35impl fmt::Debug for ErrorResponse {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        f.debug_struct("ErrorResponse")
38            .field("code", &self.code.0)
39            .field("reason", &self.reason)
40            .field("alternate_server", &self.alternate_server)
41            .field("try_alternate", &self.try_alternate)
42            .field("unknown_attributes", &self.unknown_attributes)
43            .finish()
44    }
45}
46
47impl fmt::Display for ErrorResponse {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        write!(f, "error {}: {}", self.code.0, self.reason)
50    }
51}
52
53/// Why a TURN request did not do what it asked.
54#[derive(Debug, PartialEq)]
55#[non_exhaustive]
56pub enum RequestError {
57    /// The server answered with this error response.
58    Rejected(ErrorResponse),
59    /// There is no usable answer: the response was malformed, the request timed out or could
60    /// not be made, or the state it was about is gone.
61    Failed(Error),
62}
63
64impl RequestError {
65    /// The server's error code, when the server answered with one.
66    #[must_use]
67    pub fn code(&self) -> Option<ErrorCode> {
68        match self {
69            Self::Rejected(response) => Some(response.code),
70            Self::Failed(_) => None,
71        }
72    }
73
74    /// Whether the server answered with `code`.
75    #[must_use]
76    pub fn is(&self, code: ErrorCode) -> bool {
77        self.code() == Some(code)
78    }
79
80    /// The error of the error response `res`, from the attributes its checks cover.
81    pub(crate) fn of(res: &ValidatedMessage) -> Self {
82        let mut code = ErrorCodeAttribute::default();
83        if let Err(err) = code.get_from(res) {
84            return Self::Failed(Error::Other(format!(
85                "{} without ERROR-CODE: {err}",
86                res.typ
87            )));
88        }
89        let mut alternate = MappedAddress::default();
90        let alternate_server = alternate
91            .get_from_as(res, ATTR_ALTERNATE_SERVER)
92            .ok()
93            .map(|()| SocketAddr::new(alternate.ip, alternate.port));
94        let mut unknown = UnknownAttributes(vec![]);
95        let unknown_attributes = if unknown.get_from(res).is_ok() {
96            unknown.0
97        } else {
98            vec![]
99        };
100        Self::Rejected(ErrorResponse {
101            code: code.code,
102            reason: String::from_utf8_lossy(&code.reason).into_owned(),
103            alternate_server,
104            try_alternate: TryAlternate::from_response(res).ok().flatten(),
105            unknown_attributes,
106        })
107    }
108}
109
110impl fmt::Display for RequestError {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        match self {
113            Self::Rejected(response) => response.fmt(f),
114            Self::Failed(err) => err.fmt(f),
115        }
116    }
117}
118
119impl std::error::Error for RequestError {}
120
121impl From<RequestError> for Error {
122    /// The error itself when there is one, the server's code and reason as text otherwise.
123    fn from(err: RequestError) -> Self {
124        match err {
125            RequestError::Failed(err) => err,
126            RequestError::Rejected(response) => Error::Other(response.to_string()),
127        }
128    }
129}
130
131impl From<Error> for RequestError {
132    fn from(err: Error) -> Self {
133        Self::Failed(err)
134    }
135}