Skip to main content

actix_http/ws/
proto.rs

1use base64::prelude::*;
2
3/// Operation codes defined in [RFC 6455 §11.8].
4///
5/// [RFC 6455]: https://www.rfc-editor.org/info/rfc6455/#section-11.8
6#[derive(Debug, Eq, PartialEq, Clone, Copy)]
7pub enum OpCode {
8    /// Indicates a continuation frame of a fragmented message.
9    Continue,
10
11    /// Indicates a text data frame.
12    Text,
13
14    /// Indicates a binary data frame.
15    Binary,
16
17    /// Indicates a close control frame.
18    Close,
19
20    /// Indicates a ping control frame.
21    Ping,
22
23    /// Indicates a pong control frame.
24    Pong,
25
26    /// Indicates an invalid opcode was received.
27    Bad,
28}
29
30impl_more::impl_display_enum! {
31    OpCode:
32    Continue => "CONTINUE",
33    Text => "TEXT",
34    Binary => "BINARY",
35    Close => "CLOSE",
36    Ping => "PING",
37    Pong => "PONG",
38    Bad => "BAD",
39}
40
41impl From<OpCode> for u8 {
42    fn from(op: OpCode) -> u8 {
43        use self::OpCode::*;
44
45        match op {
46            Continue => 0,
47            Text => 1,
48            Binary => 2,
49            Close => 8,
50            Ping => 9,
51            Pong => 10,
52            Bad => {
53                tracing::error!("Attempted to convert invalid opcode to u8. This is a bug.");
54                8 // if this somehow happens, a close frame will help us tear down quickly
55            }
56        }
57    }
58}
59
60impl From<u8> for OpCode {
61    fn from(byte: u8) -> OpCode {
62        use self::OpCode::*;
63
64        match byte {
65            0 => Continue,
66            1 => Text,
67            2 => Binary,
68            8 => Close,
69            9 => Ping,
70            10 => Pong,
71            _ => Bad,
72        }
73    }
74}
75
76/// Status code used to indicate why an endpoint is closing the WebSocket connection.
77#[derive(Debug, Eq, PartialEq, Clone, Copy)]
78pub enum CloseCode {
79    /// Indicates a normal closure, meaning that the purpose for which the connection was
80    /// established has been fulfilled.
81    Normal,
82
83    /// Indicates that an endpoint is "going away", such as a server going down or a browser having
84    /// navigated away from a page.
85    Away,
86
87    /// Indicates that an endpoint is terminating the connection due to a protocol error.
88    Protocol,
89
90    /// Indicates that an endpoint is terminating the connection because it has received a type of
91    /// data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it
92    /// receives a binary message).
93    Unsupported,
94
95    /// Indicates an abnormal closure. If the abnormal closure was due to an error, this close code
96    /// will not be used. Instead, the `on_error` method of the handler will be called with
97    /// the error. However, if the connection is simply dropped, without an error, this close code
98    /// will be sent to the handler.
99    Abnormal,
100
101    /// Indicates that an endpoint is terminating the connection because it has received data within
102    /// a message that was not consistent with the type of the message (e.g., non-UTF-8 \[RFC 3629\]
103    /// data within a text message).
104    Invalid,
105
106    /// Indicates that an endpoint is terminating the connection because it has received a message
107    /// that violates its policy. This is a generic status code that can be returned when there is
108    /// no other more suitable status code (e.g., Unsupported or Size) or if there is a need to hide
109    /// specific details about the policy.
110    Policy,
111
112    /// Indicates that an endpoint is terminating the connection because it has received a message
113    /// that is too big for it to process.
114    Size,
115
116    /// Indicates that an endpoint (client) is terminating the connection because it has expected
117    /// the server to negotiate one or more extension, but the server didn't return them in the
118    /// response message of the WebSocket handshake.  The list of extensions that are needed should
119    /// be given as the reason for closing. Note that this status code is not used by the server,
120    /// because it can fail the WebSocket handshake instead.
121    Extension,
122
123    /// Indicates that a server is terminating the connection because it encountered an unexpected
124    /// condition that prevented it from fulfilling the request.
125    Error,
126
127    /// Indicates that the server is restarting. A client may choose to reconnect, and if it does,
128    /// it should use a randomized delay of 5-30 seconds between attempts.
129    Restart,
130
131    /// Indicates that the server is overloaded and the client should either connect to a different
132    /// IP (when multiple targets exist), or reconnect to the same IP when a user has performed
133    /// an action.
134    Again,
135
136    #[doc(hidden)]
137    Tls,
138
139    #[doc(hidden)]
140    Other(u16),
141}
142
143impl From<CloseCode> for u16 {
144    fn from(code: CloseCode) -> u16 {
145        use self::CloseCode::*;
146
147        match code {
148            Normal => 1000,
149            Away => 1001,
150            Protocol => 1002,
151            Unsupported => 1003,
152            Abnormal => 1006,
153            Invalid => 1007,
154            Policy => 1008,
155            Size => 1009,
156            Extension => 1010,
157            Error => 1011,
158            Restart => 1012,
159            Again => 1013,
160            Tls => 1015,
161            Other(code) => code,
162        }
163    }
164}
165
166impl From<u16> for CloseCode {
167    fn from(code: u16) -> CloseCode {
168        use self::CloseCode::*;
169
170        match code {
171            1000 => Normal,
172            1001 => Away,
173            1002 => Protocol,
174            1003 => Unsupported,
175            1006 => Abnormal,
176            1007 => Invalid,
177            1008 => Policy,
178            1009 => Size,
179            1010 => Extension,
180            1011 => Error,
181            1012 => Restart,
182            1013 => Again,
183            1015 => Tls,
184            _ => Other(code),
185        }
186    }
187}
188
189#[derive(Debug, Eq, PartialEq, Clone)]
190/// Reason for closing the connection
191pub struct CloseReason {
192    /// Exit code
193    pub code: CloseCode,
194
195    /// Optional description of the exit code
196    pub description: Option<String>,
197}
198
199impl From<CloseCode> for CloseReason {
200    fn from(code: CloseCode) -> Self {
201        CloseReason {
202            code,
203            description: None,
204        }
205    }
206}
207
208impl<T: Into<String>> From<(CloseCode, T)> for CloseReason {
209    fn from(info: (CloseCode, T)) -> Self {
210        CloseReason {
211            code: info.0,
212            description: Some(info.1.into()),
213        }
214    }
215}
216
217/// The WebSocket GUID as stated in the spec.
218/// See <https://www.rfc-editor.org/info/rfc6455/#section-1.3>.
219static WS_GUID: &[u8] = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
220
221/// Length of Base64 encoded SHA-1 hash for `Sec-WebSocket-Accept` (RFC 6455 §1.3, §4.2.2).
222const WS_ACCEPT_LEN: usize = 28;
223
224/// Hashes the `Sec-WebSocket-Key` header according to the WebSocket spec.
225///
226/// Result is a Base64 encoded byte array. `base64(sha1(input))` is always 28 bytes.
227pub fn hash_key(key: &[u8]) -> [u8; WS_ACCEPT_LEN] {
228    let hash = {
229        use sha1::Digest as _;
230
231        let mut hasher = sha1::Sha1::new();
232
233        hasher.update(key);
234        hasher.update(WS_GUID);
235
236        hasher.finalize()
237    };
238
239    let mut hash_b64 = [0; WS_ACCEPT_LEN];
240    let n = BASE64_STANDARD.encode_slice(hash, &mut hash_b64).unwrap();
241    assert_eq!(n, WS_ACCEPT_LEN);
242
243    hash_b64
244}
245
246#[cfg(test)]
247mod test {
248    #![allow(unused_imports, unused_variables, dead_code)]
249    use super::*;
250
251    macro_rules! opcode_into {
252        ($from:expr => $opcode:pat) => {
253            match OpCode::from($from) {
254                e @ $opcode => {}
255                e => unreachable!("{:?}", e),
256            }
257        };
258    }
259
260    macro_rules! opcode_from {
261        ($from:expr => $opcode:pat) => {
262            let res: u8 = $from.into();
263            match res {
264                e @ $opcode => {}
265                e => unreachable!("{:?}", e),
266            }
267        };
268    }
269
270    #[test]
271    fn test_to_opcode() {
272        opcode_into!(0 => OpCode::Continue);
273        opcode_into!(1 => OpCode::Text);
274        opcode_into!(2 => OpCode::Binary);
275        opcode_into!(8 => OpCode::Close);
276        opcode_into!(9 => OpCode::Ping);
277        opcode_into!(10 => OpCode::Pong);
278        opcode_into!(99 => OpCode::Bad);
279    }
280
281    #[test]
282    fn test_from_opcode() {
283        opcode_from!(OpCode::Continue => 0);
284        opcode_from!(OpCode::Text => 1);
285        opcode_from!(OpCode::Binary => 2);
286        opcode_from!(OpCode::Close => 8);
287        opcode_from!(OpCode::Ping => 9);
288        opcode_from!(OpCode::Pong => 10);
289    }
290
291    #[test]
292    #[should_panic]
293    fn test_from_opcode_debug() {
294        opcode_from!(OpCode::Bad => 99);
295    }
296
297    #[test]
298    fn test_from_opcode_display() {
299        assert_eq!(format!("{}", OpCode::Continue), "CONTINUE");
300        assert_eq!(format!("{}", OpCode::Text), "TEXT");
301        assert_eq!(format!("{}", OpCode::Binary), "BINARY");
302        assert_eq!(format!("{}", OpCode::Close), "CLOSE");
303        assert_eq!(format!("{}", OpCode::Ping), "PING");
304        assert_eq!(format!("{}", OpCode::Pong), "PONG");
305        assert_eq!(format!("{}", OpCode::Bad), "BAD");
306    }
307
308    #[test]
309    fn test_hash_key() {
310        let hash = hash_key(b"hello actix-web");
311        assert_eq!(&hash, b"cR1dlyUUJKp0s/Bel25u5TgvC3E=");
312    }
313
314    #[test]
315    fn close_code_from_u16() {
316        assert_eq!(CloseCode::from(1000u16), CloseCode::Normal);
317        assert_eq!(CloseCode::from(1001u16), CloseCode::Away);
318        assert_eq!(CloseCode::from(1002u16), CloseCode::Protocol);
319        assert_eq!(CloseCode::from(1003u16), CloseCode::Unsupported);
320        assert_eq!(CloseCode::from(1006u16), CloseCode::Abnormal);
321        assert_eq!(CloseCode::from(1007u16), CloseCode::Invalid);
322        assert_eq!(CloseCode::from(1008u16), CloseCode::Policy);
323        assert_eq!(CloseCode::from(1009u16), CloseCode::Size);
324        assert_eq!(CloseCode::from(1010u16), CloseCode::Extension);
325        assert_eq!(CloseCode::from(1011u16), CloseCode::Error);
326        assert_eq!(CloseCode::from(1012u16), CloseCode::Restart);
327        assert_eq!(CloseCode::from(1013u16), CloseCode::Again);
328        assert_eq!(CloseCode::from(1015u16), CloseCode::Tls);
329        assert_eq!(CloseCode::from(2000u16), CloseCode::Other(2000));
330    }
331
332    #[test]
333    fn close_code_into_u16() {
334        assert_eq!(1000u16, Into::<u16>::into(CloseCode::Normal));
335        assert_eq!(1001u16, Into::<u16>::into(CloseCode::Away));
336        assert_eq!(1002u16, Into::<u16>::into(CloseCode::Protocol));
337        assert_eq!(1003u16, Into::<u16>::into(CloseCode::Unsupported));
338        assert_eq!(1006u16, Into::<u16>::into(CloseCode::Abnormal));
339        assert_eq!(1007u16, Into::<u16>::into(CloseCode::Invalid));
340        assert_eq!(1008u16, Into::<u16>::into(CloseCode::Policy));
341        assert_eq!(1009u16, Into::<u16>::into(CloseCode::Size));
342        assert_eq!(1010u16, Into::<u16>::into(CloseCode::Extension));
343        assert_eq!(1011u16, Into::<u16>::into(CloseCode::Error));
344        assert_eq!(1012u16, Into::<u16>::into(CloseCode::Restart));
345        assert_eq!(1013u16, Into::<u16>::into(CloseCode::Again));
346        assert_eq!(1015u16, Into::<u16>::into(CloseCode::Tls));
347        assert_eq!(2000u16, Into::<u16>::into(CloseCode::Other(2000)));
348    }
349}