Skip to main content

ng_tungstenite/
error.rs

1//! Error handling.
2
3use std::{io, result, str, string};
4
5use crate::protocol::{frame::coding::Data, Message};
6#[cfg(feature = "handshake")]
7use http::{header::HeaderName, Response};
8use thiserror::Error;
9
10/// Result type of all Tungstenite library calls.
11pub type Result<T, E = Error> = result::Result<T, E>;
12
13/// Possible WebSocket errors.
14#[derive(Error, Debug)]
15pub enum Error {
16    /// WebSocket connection closed normally. This informs you of the close.
17    /// It's not an error as such and nothing wrong happened.
18    ///
19    /// This is returned as soon as the close handshake is finished (we have both sent and
20    /// received a close frame) on the server end and as soon as the server has closed the
21    /// underlying connection if this endpoint is a client.
22    ///
23    /// Thus when you receive this, it is safe to drop the underlying connection.
24    ///
25    /// Receiving this error means that the WebSocket object is not usable anymore and the
26    /// only meaningful action with it is dropping it.
27    #[error("Connection closed normally")]
28    ConnectionClosed,
29    /// Trying to work with already closed connection.
30    ///
31    /// Trying to read or write after receiving `ConnectionClosed` causes this.
32    ///
33    /// As opposed to `ConnectionClosed`, this indicates your code tries to operate on the
34    /// connection when it really shouldn't anymore, so this really indicates a programmer
35    /// error on your part.
36    #[error("Trying to work with closed connection")]
37    AlreadyClosed,
38    /// Input-output error. Apart from WouldBlock, these are generally errors with the
39    /// underlying connection and you should probably consider them fatal.
40    #[error("IO error: {0}")]
41    Io(#[from] io::Error),
42    /// TLS error.
43    ///
44    /// Note that this error variant is enabled unconditionally even if no TLS feature is enabled,
45    /// to provide a feature-agnostic API surface.
46    #[error("TLS error: {0}")]
47    Tls(#[from] TlsError),
48    /// - When reading: buffer capacity exhausted.
49    /// - When writing: your message is bigger than the configured max message size
50    ///   (64MB by default).
51    #[error("Space limit exceeded: {0}")]
52    Capacity(#[from] CapacityError),
53    /// Protocol violation.
54    #[error("WebSocket protocol error: {0}")]
55    Protocol(#[from] ProtocolError),
56    /// Message send queue full.
57    #[error("Send queue is full")]
58    SendQueueFull(Message),
59    /// UTF coding error.
60    #[error("UTF-8 encoding error")]
61    Utf8,
62    /// Invalid URL.
63    #[error("URL error: {0}")]
64    Url(#[from] UrlError),
65    /// HTTP error.
66    #[error("HTTP error: {}", .0.status())]
67    #[cfg(feature = "handshake")]
68    Http(Response<Option<Vec<u8>>>),
69    /// HTTP format error.
70    #[error("HTTP format error: {0}")]
71    #[cfg(feature = "handshake")]
72    HttpFormat(#[from] http::Error),
73}
74
75impl From<str::Utf8Error> for Error {
76    fn from(_: str::Utf8Error) -> Self {
77        Error::Utf8
78    }
79}
80
81impl From<string::FromUtf8Error> for Error {
82    fn from(_: string::FromUtf8Error) -> Self {
83        Error::Utf8
84    }
85}
86
87#[cfg(feature = "handshake")]
88impl From<http::header::InvalidHeaderValue> for Error {
89    fn from(err: http::header::InvalidHeaderValue) -> Self {
90        Error::HttpFormat(err.into())
91    }
92}
93
94#[cfg(feature = "handshake")]
95impl From<http::header::InvalidHeaderName> for Error {
96    fn from(err: http::header::InvalidHeaderName) -> Self {
97        Error::HttpFormat(err.into())
98    }
99}
100
101#[cfg(feature = "handshake")]
102impl From<http::header::ToStrError> for Error {
103    fn from(_: http::header::ToStrError) -> Self {
104        Error::Utf8
105    }
106}
107
108#[cfg(feature = "handshake")]
109impl From<http::uri::InvalidUri> for Error {
110    fn from(err: http::uri::InvalidUri) -> Self {
111        Error::HttpFormat(err.into())
112    }
113}
114
115#[cfg(feature = "handshake")]
116impl From<http::status::InvalidStatusCode> for Error {
117    fn from(err: http::status::InvalidStatusCode) -> Self {
118        Error::HttpFormat(err.into())
119    }
120}
121
122#[cfg(feature = "handshake")]
123impl From<httparse::Error> for Error {
124    fn from(err: httparse::Error) -> Self {
125        match err {
126            httparse::Error::TooManyHeaders => Error::Capacity(CapacityError::TooManyHeaders),
127            e => Error::Protocol(ProtocolError::HttparseError(e)),
128        }
129    }
130}
131
132/// Indicates the specific type/cause of a capacity error.
133#[derive(Error, Debug, PartialEq, Eq, Clone, Copy)]
134pub enum CapacityError {
135    /// Too many headers provided (see [`httparse::Error::TooManyHeaders`]).
136    #[error("Too many headers")]
137    TooManyHeaders,
138    /// Received header is too long.
139    /// Message is bigger than the maximum allowed size.
140    #[error("Message too long: {size} > {max_size}")]
141    MessageTooLong {
142        /// The size of the message.
143        size: usize,
144        /// The maximum allowed message size.
145        max_size: usize,
146    },
147}
148
149/// Indicates the specific type/cause of a protocol error.
150#[allow(missing_copy_implementations)]
151#[derive(Error, Debug, PartialEq, Eq, Clone)]
152pub enum ProtocolError {
153    /// Use of the wrong HTTP method (the WebSocket protocol requires the GET method be used).
154    #[error("Unsupported HTTP method used - only GET is allowed")]
155    WrongHttpMethod,
156    /// Wrong HTTP version used (the WebSocket protocol requires version 1.1 or higher).
157    #[error("HTTP version must be 1.1 or higher")]
158    WrongHttpVersion,
159    /// Missing `Connection: upgrade` HTTP header.
160    #[error("No \"Connection: upgrade\" header")]
161    MissingConnectionUpgradeHeader,
162    /// Missing `Upgrade: websocket` HTTP header.
163    #[error("No \"Upgrade: websocket\" header")]
164    MissingUpgradeWebSocketHeader,
165    /// Missing `Sec-WebSocket-Version: 13` HTTP header.
166    #[error("No \"Sec-WebSocket-Version: 13\" header")]
167    MissingSecWebSocketVersionHeader,
168    /// Missing `Sec-WebSocket-Key` HTTP header.
169    #[error("No \"Sec-WebSocket-Key\" header")]
170    MissingSecWebSocketKey,
171    /// The `Sec-WebSocket-Accept` header is either not present or does not specify the correct key value.
172    #[error("Key mismatch in \"Sec-WebSocket-Accept\" header")]
173    SecWebSocketAcceptKeyMismatch,
174    /// Garbage data encountered after client request.
175    #[error("Junk after client request")]
176    JunkAfterRequest,
177    /// Custom responses must be unsuccessful.
178    #[error("Custom response must not be successful")]
179    CustomResponseSuccessful,
180    /// Invalid header is passed. Or the header is missing in the request. Or not present at all. Check the request that you pass.
181    #[error("Missing, duplicated or incorrect header {0}")]
182    #[cfg(feature = "handshake")]
183    InvalidHeader(HeaderName),
184    /// No more data while still performing handshake.
185    #[error("Handshake not finished")]
186    HandshakeIncomplete,
187    /// Wrapper around a [`httparse::Error`] value.
188    #[error("httparse error: {0}")]
189    #[cfg(feature = "handshake")]
190    HttparseError(#[from] httparse::Error),
191    /// Not allowed to send after having sent a closing frame.
192    #[error("Sending after closing is not allowed")]
193    SendAfterClosing,
194    /// Remote sent data after sending a closing frame.
195    #[error("Remote sent after having closed")]
196    ReceivedAfterClosing,
197    /// Reserved bits in frame header are non-zero.
198    #[error("Reserved bits are non-zero")]
199    NonZeroReservedBits,
200    /// The server must close the connection when an unmasked frame is received.
201    #[error("Received an unmasked frame from client")]
202    UnmaskedFrameFromClient,
203    /// The client must close the connection when a masked frame is received.
204    #[error("Received a masked frame from server")]
205    MaskedFrameFromServer,
206    /// Control frames must not be fragmented.
207    #[error("Fragmented control frame")]
208    FragmentedControlFrame,
209    /// Control frames must have a payload of 125 bytes or less.
210    #[error("Control frame too big (payload must be 125 bytes or less)")]
211    ControlFrameTooBig,
212    /// Type of control frame not recognised.
213    #[error("Unknown control frame type: {0}")]
214    UnknownControlFrameType(u8),
215    /// Type of data frame not recognised.
216    #[error("Unknown data frame type: {0}")]
217    UnknownDataFrameType(u8),
218    /// Received a continue frame despite there being nothing to continue.
219    #[error("Continue frame but nothing to continue")]
220    UnexpectedContinueFrame,
221    /// Received data while waiting for more fragments.
222    #[error("While waiting for more fragments received: {0}")]
223    ExpectedFragment(Data),
224    /// Connection closed without performing the closing handshake.
225    #[error("Connection reset without closing handshake")]
226    ResetWithoutClosingHandshake,
227    /// Encountered an invalid opcode.
228    #[error("Encountered invalid opcode: {0}")]
229    InvalidOpcode(u8),
230    /// The payload for the closing frame is invalid.
231    #[error("Invalid close sequence")]
232    InvalidCloseSequence,
233}
234
235/// Indicates the specific type/cause of URL error.
236#[derive(Error, Debug, PartialEq, Eq)]
237pub enum UrlError {
238    /// TLS is used despite not being compiled with the TLS feature enabled.
239    #[error("TLS support not compiled in")]
240    TlsFeatureNotEnabled,
241    /// The URL does not include a host name.
242    #[error("No host name in the URL")]
243    NoHostName,
244    /// Failed to connect with this URL.
245    #[error("Unable to connect to {0}")]
246    UnableToConnect(String),
247    /// Unsupported URL scheme used (only `ws://` or `wss://` may be used).
248    #[error("URL scheme not supported")]
249    UnsupportedUrlScheme,
250    /// The URL host name, though included, is empty.
251    #[error("URL contains empty host name")]
252    EmptyHostName,
253    /// The URL does not include a path/query.
254    #[error("No path/query in URL")]
255    NoPathOrQuery,
256}
257
258/// TLS errors.
259///
260/// Note that even if you enable only the rustls-based TLS support, the error at runtime could still
261/// be `Native`, as another crate in the dependency graph may enable native TLS support.
262#[allow(missing_copy_implementations)]
263#[derive(Error, Debug)]
264#[non_exhaustive]
265pub enum TlsError {
266    /// Native TLS error.
267    #[cfg(feature = "native-tls")]
268    #[error("native-tls error: {0}")]
269    Native(#[from] native_tls_crate::Error),
270    /// Rustls error.
271    #[cfg(feature = "__rustls-tls")]
272    #[error("rustls error: {0}")]
273    Rustls(#[from] rustls::Error),
274    /// Webpki error.
275    #[cfg(feature = "__rustls-tls")]
276    #[error("webpki error: {0}")]
277    Webpki(#[from] webpki::Error),
278    /// DNS name resolution error.
279    #[cfg(feature = "__rustls-tls")]
280    #[error("Invalid DNS name")]
281    InvalidDnsName,
282}