1use crate::error::{ErrorKind, ErrorStage};
2use crate::{NetError, Result};
3use std::fmt;
4
5#[derive(Clone)]
9pub struct CloseFrame {
10 code: u16,
12 reason: String,
14}
15
16impl fmt::Debug for CloseFrame {
17 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
18 formatter
19 .debug_struct("CloseFrame")
20 .field("code", &self.code)
21 .field("reason_len", &self.reason.len())
22 .finish()
23 }
24}
25
26impl CloseFrame {
27 pub fn new(code: u16, reason: impl Into<String>) -> Result<Self> {
29 if !matches!(code, 1000..=1003 | 1007..=1014 | 3000..=4999) {
31 return Err(NetError::input(
32 "close.code",
33 "must be an allowed WebSocket wire close code",
34 )
35 .with_stage(ErrorStage::Close));
36 }
37 let reason = reason.into();
38 if reason.len() > 123 {
39 return Err(
40 NetError::input("close.reason", "must be at most 123 UTF-8 bytes")
41 .with_stage(ErrorStage::Close),
42 );
43 }
44 Ok(Self { code, reason })
45 }
46
47 pub fn code(&self) -> u16 {
49 self.code
50 }
51
52 pub fn reason(&self) -> &str {
54 &self.reason
55 }
56
57 pub(crate) fn into_wire(self) -> tokio_tungstenite::tungstenite::protocol::CloseFrame {
58 use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
59 let code = if self.code == 1014 {
62 CloseCode::Iana(self.code)
63 } else {
64 CloseCode::from(self.code)
65 };
66 tokio_tungstenite::tungstenite::protocol::CloseFrame {
67 code,
68 reason: self.reason.into(),
69 }
70 }
71}
72
73#[derive(Clone)]
75pub struct PeerClose {
76 pub code: Option<u16>,
78 pub reason: String,
80}
81
82impl PeerClose {
83 pub(crate) fn from_frame(
87 frame: Option<&tokio_tungstenite::tungstenite::protocol::CloseFrame>,
88 ) -> Result<Self> {
89 let Some(frame) = frame else {
90 return Ok(Self {
91 code: None,
92 reason: String::new(),
93 });
94 };
95 if frame.reason.len() > 123 {
96 return Err(NetError::from(ErrorKind::Protocol).with_stage(ErrorStage::Close));
99 }
100 let mut reason = String::new();
101 reason
102 .try_reserve_exact(frame.reason.len())
103 .map_err(|error| {
104 NetError::with_source(ErrorKind::ResourceExhausted, error)
105 .with_stage(ErrorStage::Close)
106 })?;
107 reason.push_str(frame.reason.as_str());
108 Ok(Self {
109 code: Some(u16::from(frame.code)),
110 reason,
111 })
112 }
113}
114
115impl fmt::Debug for PeerClose {
116 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
117 formatter
118 .debug_struct("PeerClose")
119 .field("code", &self.code)
120 .field("reason_len", &self.reason.len())
121 .finish()
122 }
123}
124
125#[non_exhaustive]
128#[derive(Clone, Copy, Debug, Eq, PartialEq)]
129pub enum IoEndKind {
130 PeerClose,
132 UnexpectedEof,
134 ConnectionReset,
136 ProtocolError,
138 Other,
140}
141
142#[cfg(test)]
143#[path = "close_tests.rs"]
144mod tests;
145
146#[cfg(test)]
147#[path = "peer_close_tests.rs"]
148mod peer_tests;