Skip to main content

jmap_websocket/server/
close.rs

1//! Closing a running connection from the deployment: [`CloseHandle`] and
2//! [`CloseCode`].
3//!
4//! RFC 8887 §4.2: "If the authentication credentials for the user expire,
5//! the server can either treat subsequent requests as if they are
6//! unauthenticated or close the WebSocket connection. In the latter case,
7//! the server MAY send a Close frame with a status code of 1008 (Policy
8//! Violation)". The JMAP Chat, VTC and Scene WebSocket drafts make 1008 a
9//! SHOULD (draft-atwood-jmap-chat-wss-00 §Authentication and the matching
10//! sections of the VTC and Scene drafts).
11
12use std::fmt;
13use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
14
15use tokio::sync::Notify;
16
17/// The longest Close reason, in bytes: a control frame payload is at most
18/// 125 bytes (RFC 6455 §5.5), two of them the status code.
19pub const MAX_CLOSE_REASON_LEN: usize = 123;
20
21/// A WebSocket Close status code an endpoint may send (RFC 6455 §7.4).
22///
23/// Only codes a peer accepts can be made: 1000 to 1003 and 1007 to 1013
24/// (RFC 6455 §7.4.1 and the IANA WebSocket Close Code Number Registry),
25/// and 3000 to 4999 (§7.4.2: registered libraries and frameworks, and
26/// private use). 1004, 1005, 1006 and 1015 must not be sent; 1014 and
27/// 1016 to 2999 are rejected by common client libraries (tungstenite
28/// treats them as a protocol error).
29///
30/// ```
31/// use jmap_websocket::server::CloseCode;
32///
33/// assert_eq!(CloseCode::POLICY_VIOLATION.as_u16(), 1008);
34/// assert_eq!(CloseCode::new(4001).map(u16::from), Some(4001));
35/// assert_eq!(CloseCode::new(1006), None);
36/// ```
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub struct CloseCode(u16);
39
40impl CloseCode {
41    /// 1000 Normal Closure.
42    pub const NORMAL: Self = Self(1000);
43    /// 1001 Going Away, for example a server shutting down.
44    pub const GOING_AWAY: Self = Self(1001);
45    /// 1008 Policy Violation: the code RFC 8887 §4.2 names for expired
46    /// credentials.
47    pub const POLICY_VIOLATION: Self = Self(1008);
48
49    /// The close code `code`, or `None` when an endpoint may not send it
50    /// (see the [type docs](Self)).
51    pub const fn new(code: u16) -> Option<Self> {
52        match code {
53            1000..=1003 | 1007..=1013 | 3000..=4999 => Some(Self(code)),
54            _ => None,
55        }
56    }
57
58    /// The numeric status code.
59    pub const fn as_u16(self) -> u16 {
60        self.0
61    }
62}
63
64impl From<CloseCode> for u16 {
65    fn from(code: CloseCode) -> u16 {
66        code.0
67    }
68}
69
70impl fmt::Display for CloseCode {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        self.0.fmt(f)
73    }
74}
75
76/// Where a [`Connection`](super::Connection) is in its life, as its
77/// [`CloseHandle`]s see it.
78#[derive(Debug)]
79enum State {
80    /// Not closed yet (`run` may not have started).
81    Open,
82    /// [`CloseHandle::close`] asked for this Close.
83    Requested(CloseCode, String),
84    /// `run` returned.
85    Ended,
86}
87
88/// The state one connection shares with its [`CloseHandle`]s.
89#[derive(Debug)]
90pub(super) struct Shared {
91    state: Mutex<State>,
92    changed: Notify,
93}
94
95impl Shared {
96    pub(super) fn new() -> Arc<Self> {
97        Arc::new(Self {
98            state: Mutex::new(State::Open),
99            changed: Notify::new(),
100        })
101    }
102
103    // No code path panics while holding the lock, so a poisoned lock
104    // still holds a consistent state.
105    fn lock(&self) -> MutexGuard<'_, State> {
106        self.state.lock().unwrap_or_else(PoisonError::into_inner)
107    }
108
109    /// The Close requested so far, if any.
110    pub(super) fn requested_now(&self) -> Option<(CloseCode, String)> {
111        match &*self.lock() {
112            State::Requested(code, reason) => Some((*code, reason.clone())),
113            State::Open | State::Ended => None,
114        }
115    }
116
117    /// The Close to send, once one is requested; pending until then.
118    pub(super) async fn requested(&self) -> (CloseCode, String) {
119        loop {
120            // Made before the check, so a `close` between the check and
121            // the await still wakes it (`notify_waiters` reaches every
122            // `Notified` that exists).
123            let changed = self.changed.notified();
124            if let Some(requested) = self.requested_now() {
125                return requested;
126            }
127            changed.await;
128        }
129    }
130
131    /// `run` returned: later [`CloseHandle::close`] calls do nothing.
132    pub(super) fn end(&self) {
133        *self.lock() = State::Ended;
134    }
135}
136
137/// Closes a running [`Connection`](super::Connection) from outside it,
138/// for example when the credentials of the opening handshake expire (RFC
139/// 8887 §4.2). Get one with
140/// [`Connection::close_handle`](super::Connection::close_handle) before
141/// calling [`run`](super::Connection::run); clone it freely and send it
142/// to another task.
143///
144/// [`close`](Self::close) makes `run` send a Close frame with the given
145/// code and reason, run the same shutdown as any other end (push
146/// subscription dropped, extension queue closed,
147/// [`ExtensionHandler::close`](super::ExtensionHandler::close) called),
148/// and return `Ok(())`. `run` does not wait for the client's answering
149/// Close; the transport (for example
150/// `tungstenite::serve`) drops the socket.
151///
152/// Nothing queued is sent ahead of the Close: Responses of Requests still
153/// running, queued extension messages and push notifications not yet
154/// written are dropped. A message `run` is writing when `close` is called
155/// is finished first. After credentials expire this is what the drafts
156/// ask: "A server that does not close the connection when credentials
157/// expire SHOULD NOT deliver further ephemeral events on that connection"
158/// (draft-atwood-jmap-chat-wss-00).
159///
160/// ```
161/// use std::sync::Arc;
162/// use std::time::Duration;
163/// use jmap_websocket::jmap_server::Dispatcher;
164/// use jmap_websocket::jmap_types::State;
165/// use jmap_websocket::server::{CloseCode, Connection, DispatcherHandler};
166///
167/// # async fn serve(ws: jmap_websocket::tokio_tungstenite::WebSocketStream<tokio::net::TcpStream>,
168/// #     dispatcher: Arc<Dispatcher<()>>, expires_in: Duration)
169/// #     -> Result<(), jmap_websocket::server::ConnectionError> {
170/// let handler = Arc::new(DispatcherHandler::new(dispatcher, (), || State::from("s0")));
171/// let connection = Connection::new(handler);
172/// let close = connection.close_handle();
173/// // The credentials of the opening handshake expire after `expires_in`.
174/// tokio::spawn(async move {
175///     tokio::time::sleep(expires_in).await;
176///     close.close(CloseCode::POLICY_VIOLATION, "credentials expired");
177/// });
178/// jmap_websocket::tungstenite::serve(connection, ws).await
179/// # }
180/// ```
181#[derive(Debug, Clone)]
182pub struct CloseHandle {
183    shared: Arc<Shared>,
184}
185
186impl CloseHandle {
187    pub(super) fn new(shared: Arc<Shared>) -> Self {
188        Self { shared }
189    }
190
191    /// Ask the connection to close with `code` and `reason`.
192    ///
193    /// `reason` longer than [`MAX_CLOSE_REASON_LEN`] bytes is cut to the
194    /// longest prefix within it that ends on a character boundary, so the
195    /// Close frame stays a valid control frame (RFC 6455 §5.5).
196    ///
197    /// Returns `true` when this call is the request that `run` acts on.
198    /// Returns `false`, and does nothing, when an earlier `close` (through
199    /// any clone) asked already (the first request wins), or `run` has
200    /// returned (the client closed, the stream ended, or it failed).
201    /// Called before `run` starts, the Close is the first thing `run`
202    /// sends. `true` is not a promise of delivery: the client may close,
203    /// or the socket fail, at the same moment.
204    pub fn close(&self, code: CloseCode, reason: impl Into<String>) -> bool {
205        let mut state = self.shared.lock();
206        if !matches!(*state, State::Open) {
207            return false;
208        }
209        *state = State::Requested(code, truncate_reason(reason.into()));
210        drop(state);
211        self.shared.changed.notify_waiters();
212        true
213    }
214}
215
216/// `reason` cut to at most [`MAX_CLOSE_REASON_LEN`] bytes, on a character
217/// boundary.
218fn truncate_reason(mut reason: String) -> String {
219    if reason.len() > MAX_CLOSE_REASON_LEN {
220        let mut end = MAX_CLOSE_REASON_LEN;
221        while !reason.is_char_boundary(end) {
222            end -= 1;
223        }
224        reason.truncate(end);
225    }
226    reason
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    /// RFC 6455 §7.4.1 defines 1000-1003 and 1007-1011, and says 1004 is
234    /// reserved and 1005, 1006, 1015 "MUST NOT be set as a status code in
235    /// a Close control frame by an endpoint"; §7.4.2 gives 0-999 no use
236    /// and 3000-4999 to libraries and applications.
237    #[test]
238    fn only_sendable_codes_are_made() {
239        for ok in [
240            1000, 1001, 1002, 1003, 1007, 1008, 1011, 1012, 1013, 3000, 4999,
241        ] {
242            assert_eq!(CloseCode::new(ok).map(CloseCode::as_u16), Some(ok), "{ok}");
243        }
244        for bad in [
245            0,
246            999,
247            1004,
248            1005,
249            1006,
250            1014,
251            1015,
252            1016,
253            2999,
254            5000,
255            u16::MAX,
256        ] {
257            assert_eq!(CloseCode::new(bad), None, "{bad}");
258        }
259        assert_eq!(CloseCode::POLICY_VIOLATION.as_u16(), 1008);
260        assert_eq!(CloseCode::GOING_AWAY.as_u16(), 1001);
261        assert_eq!(CloseCode::NORMAL.as_u16(), 1000);
262        assert_eq!(CloseCode::POLICY_VIOLATION.to_string(), "1008");
263    }
264
265    /// RFC 6455 §5.5: "All control frames MUST have a payload length of
266    /// 125 bytes or less"; §5.5.1: the body is a 2-byte code then the
267    /// reason, so the reason has 123 bytes.
268    #[test]
269    fn reason_is_cut_to_123_bytes_on_a_char_boundary() {
270        assert_eq!(MAX_CLOSE_REASON_LEN, 125 - 2);
271        let fits = "a".repeat(123);
272        assert_eq!(truncate_reason(fits.clone()), fits);
273        assert_eq!(truncate_reason("a".repeat(124)), fits);
274        // 122 one-byte characters, then a 2-byte one straddling byte 123.
275        let straddles = format!("{}é", "a".repeat(122));
276        assert_eq!(straddles.len(), 124);
277        assert_eq!(truncate_reason(straddles), "a".repeat(122));
278        // 4-byte characters: 30 of them are 120 bytes, a 31st would be 124.
279        let wide = "\u{1F512}".repeat(40);
280        assert_eq!(truncate_reason(wide), "\u{1F512}".repeat(30));
281    }
282
283    #[test]
284    fn first_close_wins_and_none_after_the_end() {
285        let shared = Shared::new();
286        let a = CloseHandle::new(Arc::clone(&shared));
287        let b = a.clone();
288        assert!(a.close(CloseCode::POLICY_VIOLATION, "expired"));
289        assert!(!b.close(CloseCode::GOING_AWAY, "shutdown"));
290        assert!(matches!(
291            &*shared.lock(),
292            State::Requested(CloseCode::POLICY_VIOLATION, r) if r == "expired"
293        ));
294        shared.end();
295        assert!(!a.close(CloseCode::NORMAL, ""));
296
297        let ended = Shared::new();
298        ended.end();
299        assert!(!CloseHandle::new(ended).close(CloseCode::NORMAL, ""));
300    }
301
302    /// A `requested` that is already waiting wakes up on `close`.
303    #[tokio::test]
304    async fn requested_wakes_on_close() {
305        let shared = Shared::new();
306        let handle = CloseHandle::new(Arc::clone(&shared));
307        let waiter = tokio::spawn({
308            let shared = Arc::clone(&shared);
309            async move { shared.requested().await }
310        });
311        tokio::task::yield_now().await;
312        assert!(handle.close(CloseCode::POLICY_VIOLATION, "bye"));
313        let got = tokio::time::timeout(std::time::Duration::from_secs(5), waiter)
314            .await
315            .expect("woken")
316            .unwrap();
317        assert_eq!(got, (CloseCode::POLICY_VIOLATION, "bye".to_owned()));
318    }
319}