Skip to main content

ntex/web/
ws.rs

1//! `WebSockets` protocol support
2use std::fmt;
3
4pub use crate::ws::{CloseCode, CloseReason, Frame, Message, WsSink};
5
6use crate::http::{ConnectionType, body::BodySize, error::ResponseError, h1, header};
7use crate::io::{DispatchItem, Reason};
8use crate::service::{Ctx, IntoService, Pipeline, Service, apply_fn};
9use crate::web::HttpRequest;
10use crate::ws::{self, error::HandshakeError, error::WsError, handshake};
11use crate::{rt, time::Seconds};
12
13/// Returns an iterator over the subprotocols requested by the client
14/// in the `Sec-Websocket-Protocol` header.
15///
16/// # Example
17///
18/// ```rust
19/// use ntex::web::{self, HttpRequest, ws};
20///
21/// async fn service(frame: ws::Frame) -> Result<Option<ws::Message>, std::io::Error> {
22///     // handle incoming frames
23///     Ok(None)
24/// }
25///
26/// async fn handler(req: HttpRequest) {
27///     let chosen = ws::subprotocols(&req)
28///         .find(|p| *p == "my-subprotocol");
29///
30///     if let Err(err) = ws::start(&req, chosen, service).await {
31///         eprintln!("WebSocket error: {err:?}");
32///     }
33/// }
34///
35/// let app = web::App::default().route("/ws", web::get().to(handler));
36/// ```
37pub fn subprotocols(req: &HttpRequest) -> impl Iterator<Item = &str> {
38    req.headers()
39        .get_all(header::SEC_WEBSOCKET_PROTOCOL)
40        .flat_map(|val| {
41            val.to_str()
42                .ok()
43                .into_iter()
44                .flat_map(|s| s.split(',').map(str::trim).filter(|s| !s.is_empty()))
45        })
46}
47
48/// Start websocket service handling Frame messages, including the chosen
49/// subprotocol in the response.
50///
51/// If `subprotocol` is `Some`, the `Sec-Websocket-Protocol` header will be included
52/// in the response with the chosen protocol. The protocol must be a valid HTTP
53/// token offered by the client. If `None`, the header is omitted.
54///
55/// If the handshake fails for an upgrade request, the handshake error response
56/// is sent and the connection is closed.
57///
58/// With the `compress` feature, the `permessage-deflate` extension is accepted
59/// if it is enabled with
60/// [`HttpServiceConfig::set_ws_deflate()`](crate::http::HttpServiceConfig::set_ws_deflate).
61///
62/// Control frames are passed to the service too. If it returns `None` for
63/// a ping and hasn't sent a pong through a sink meanwhile, a pong with the
64/// same payload is sent. If it returns `None` for the peer's close frame,
65/// a close echoing the peer's code is sent. No automatic reply is sent once
66/// a close message has been sent through a sink. After the peer's close frame
67/// is handled, the connection is closed. Dispatcher control and stop events
68/// are handled by `start()`, a service error sends a close frame with
69/// [`CloseCode::Away`].
70///
71/// # Example
72///
73/// ```rust
74/// use ntex::web::{self, HttpRequest, ws};
75///
76/// async fn service(frame: ws::Frame) -> Result<Option<ws::Message>, std::io::Error> {
77///     // handle incoming frames
78///     Ok(None)
79/// }
80///
81/// async fn handler(req: HttpRequest) {
82///     let chosen = ws::subprotocols(&req)
83///         .find(|p| *p == "graphql-ws" || *p == "graphql-transport-ws");
84///
85///     if let Err(err) = ws::start(&req, chosen, service).await {
86///         eprintln!("WebSocket error: {err:?}");
87///     }
88/// }
89///
90/// let app = web::App::default().route("/ws", web::get().to(handler));
91/// ```
92pub async fn start<S>(
93    req: &HttpRequest,
94    subprotocol: Option<&str>,
95    f: impl IntoService<S, WsSink, Frame>,
96) -> Result<(), WsError<S::Error>>
97where
98    S: Service<WsSink, Frame, Res = Option<Message>> + 'static,
99    S::Error: fmt::Debug,
100{
101    start_with(
102        req,
103        subprotocol,
104        DispatchService {
105            svc: f.into_service(),
106        },
107    )
108    .await
109}
110
111/// Start websocket service handling raw `DispatchItem` messages requiring manual control/stop logic,
112/// including the chosen subprotocol in the response.
113///
114/// Unlike [`start()`], pings and close frames are not answered automatically.
115///
116/// If `subprotocol` is `Some`, the `Sec-Websocket-Protocol` header will be included
117/// in the response with the chosen protocol. The protocol must be a valid HTTP
118/// token offered by the client. If `None`, the header is omitted.
119///
120/// If the handshake fails for an upgrade request, the handshake error response
121/// is sent and the connection is closed.
122///
123/// With the `compress` feature, the `permessage-deflate` extension is accepted
124/// if it is enabled with
125/// [`HttpServiceConfig::set_ws_deflate()`](crate::http::HttpServiceConfig::set_ws_deflate).
126pub async fn start_with<S, Err>(
127    req: &HttpRequest,
128    subprotocol: Option<&str>,
129    f: impl IntoService<S, WsSink, DispatchItem<WsSink>>,
130) -> Result<(), WsError<Err>>
131where
132    S: Service<WsSink, DispatchItem<WsSink>, Res = Option<Message>, Error = WsError<Err>> + 'static,
133    S::Error: fmt::Debug,
134    Err: 'static,
135{
136    log::trace!("Start ws handshake verification for {:?}", req.path());
137
138    // ws handshake
139    #[allow(unused_mut)]
140    let mut res = match handshake_response(req, subprotocol) {
141        Ok(res) => res,
142        Err(err) => {
143            reject(req, err).await;
144            return Err(err.into());
145        }
146    };
147
148    // extract io
149    let item = req
150        .head()
151        .take_io()
152        .ok_or(HandshakeError::NoWebsocketUpgrade)?;
153    let io = item.0;
154    let codec = item.1;
155
156    #[allow(unused_mut)]
157    let mut ws_codec = ws::Codec::new();
158    #[cfg(feature = "compress")]
159    if let Some((agreed, value)) = io
160        .shared()
161        .get::<crate::http::HttpServiceConfig>()
162        .ws_deflate
163        .as_ref()
164        .and_then(|deflate| deflate.negotiate(req.headers()))
165    {
166        log::trace!("Ws permessage-deflate is accepted {agreed:?}");
167        res.headers_mut()
168            .insert(header::SEC_WEBSOCKET_EXTENSIONS, value);
169        ws_codec = ws_codec.set_deflate(agreed);
170    }
171
172    io.encode(h1::Message::Item((res, BodySize::Empty)), &codec)
173        .map_err(|_| HandshakeError::NoWebsocketUpgrade)?;
174    log::trace!("Ws handshake verification completed for {:?}", req.path());
175
176    // create sink, it is also the dispatcher's codec
177    let sink = WsSink::new(io.get_ref(), ws_codec, io.shared().get());
178
179    // start websockets service dispatcher
180    let timeout_sink = sink.clone();
181    let service = apply_fn(f.into_service(), async move |req, svc| {
182        let result = svc.call(req).await;
183        if matches!(&result, Ok(Some(Message::Close(_)))) {
184            timeout_sink.start_close_timeout();
185        }
186        result
187    });
188    // the connection keeps its transport configuration; it has no keep-alive
189    // and the peer may stay silent until it starts the first frame
190    let result = crate::io::Dispatcher::new(io, sink.clone(), Pipeline::new(sink, service))
191        .keepalive_timeout(Seconds::ZERO)
192        .skip_first_frame_timeout()
193        .await;
194    log::trace!("Ws handler is terminated: {result:?}");
195
196    result
197}
198
199fn handshake_response(
200    req: &HttpRequest,
201    subprotocol: Option<&str>,
202) -> Result<crate::http::Response<()>, HandshakeError> {
203    let mut res = handshake(req.head())?;
204    if let Some(protocol) = subprotocol {
205        if !ws::is_token(protocol) || !subprotocols(req).any(|offered| offered == protocol) {
206            return Err(HandshakeError::BadWebsocketProtocol);
207        }
208        res.set_header(header::SEC_WEBSOCKET_PROTOCOL, protocol);
209    }
210    Ok(res.build().into_parts().0)
211}
212
213/// Sends the handshake error response and closes the connection.
214///
215/// The I/O stream of an upgrade request belongs to the handler, a response
216/// returned by the handler is not sent.
217async fn reject(req: &HttpRequest, err: HandshakeError) {
218    if let Some((io, codec)) = req.head().take_io() {
219        let mut res = err.error_response().into_parts().0;
220        res.head_mut().set_connection_type(ConnectionType::Close);
221        if io
222            .encode(h1::Message::Item((res, BodySize::Empty)), &codec)
223            .is_ok()
224        {
225            let _ = io.shutdown().await;
226        }
227    }
228}
229
230/// Just a wrapper over a service handling WebSocket messages and propagating shutdown
231struct DispatchService<S> {
232    svc: S,
233}
234
235impl<S, E> Service<WsSink, DispatchItem<WsSink>> for DispatchService<S>
236where
237    S: Service<WsSink, Frame, Res = Option<Message>, Error = E>,
238    E: fmt::Debug,
239{
240    type Res = Option<Message>;
241    type Error = WsError<E>;
242
243    crate::forward!(WsSink, svc, map_err = WsError::Service);
244
245    async fn call(
246        &self,
247        req: DispatchItem<WsSink>,
248        ctx: Ctx<'_, Self, WsSink>,
249    ) -> Result<Self::Res, Self::Error> {
250        match req {
251            DispatchItem::Item(item) => {
252                let sink = ctx.st();
253                let close = matches!(item, Frame::Close(_));
254                let reply = sink.codec().auto_reply(&item);
255                let result = ctx
256                    .call(&self.svc, item)
257                    .await
258                    .map(|res| sink.codec().unanswered(res, reply))
259                    .map_err(WsError::Service);
260                if close {
261                    let s = sink.clone();
262                    rt::spawn_detached(async move { s.io().close() });
263                }
264                result
265            }
266            // a clean disconnect is not an error
267            DispatchItem::Control(_) | DispatchItem::Stop(Reason::Io(None)) => Ok(None),
268            DispatchItem::Stop(Reason::Service) => {
269                Ok(Some(Message::Close(Some(ws::CloseReason {
270                    code: ws::CloseCode::Away,
271                    description: None,
272                }))))
273            }
274            DispatchItem::Stop(Reason::KeepAlive) => Err(WsError::KeepAlive),
275            DispatchItem::Stop(Reason::ReadTimeout) => Err(WsError::ReadTimeout),
276            DispatchItem::Stop(Reason::WriteTimeout) => Err(WsError::WriteTimeout),
277            DispatchItem::Stop(Reason::Decoder(e)) => {
278                let sink = ctx.st();
279                if !sink.is_closed() {
280                    let reason = ws::CloseReason::from(ws::CloseCode::Protocol);
281                    let _ = sink.send(Message::Close(Some(reason))).await;
282                }
283                Err(WsError::Protocol(e))
284            }
285            DispatchItem::Stop(Reason::Encoder(e)) => Err(WsError::Protocol(e)),
286            DispatchItem::Stop(Reason::Io(e)) => Err(WsError::Disconnected(e)),
287        }
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use std::io;
294
295    use super::*;
296    use crate::io::{Control, Io, testing::IoTest};
297    use crate::service::fn_service;
298    use crate::ws::error::ProtocolError;
299
300    /// STATEMENT: WebSocket dispatch maps frames, controls, and stop reasons to responses and errors.
301    ///
302    /// HOW:
303    /// - Dispatch ping/text frames and backpressure control, checking service results and no-op handling.
304    /// - Assert stop reasons yield the expected close message, timeout, protocol, or disconnect outcome.
305    /// - Trigger decoder errors twice and assert the sink closes; dispatch close and await I/O closure.
306    #[crate::rt_test]
307    async fn dispatch_service() {
308        let (client, server) = IoTest::create();
309        client.remote_buffer_cap(1 << 20);
310        let io = Io::from(server);
311        let sink = WsSink::new(io.get_ref(), ws::Codec::new(), crate::Cfg::default());
312        let svc = Pipeline::new(
313            sink.clone(),
314            DispatchService {
315                svc: fn_service(async |frame: Frame| match frame {
316                    Frame::Text(_) => Err(io::Error::other("text")),
317                    _ => Ok(Some(Message::Pong("pong".into()))),
318                }),
319            },
320        );
321
322        let res = svc.call(DispatchItem::Item(Frame::Ping("p".into()))).await;
323        assert!(matches!(res, Ok(Some(Message::Pong(_)))));
324        let res = svc.call(DispatchItem::Item(Frame::Text("t".into()))).await;
325        assert!(matches!(res, Err(WsError::Service(_))));
326        let res = svc
327            .call(DispatchItem::Control(Control::WBackPressureEnabled))
328            .await;
329        assert!(matches!(res, Ok(None)));
330        let res = svc.call(DispatchItem::Stop(Reason::Io(None))).await;
331        assert!(matches!(res, Ok(None)));
332        let res = svc.call(DispatchItem::Stop(Reason::Service)).await;
333        assert!(matches!(
334            res,
335            Ok(Some(Message::Close(Some(ws::CloseReason {
336                code: ws::CloseCode::Away,
337                ..
338            }))))
339        ));
340        let res = svc.call(DispatchItem::Stop(Reason::KeepAlive)).await;
341        assert!(matches!(res, Err(WsError::KeepAlive)));
342        let res = svc.call(DispatchItem::Stop(Reason::ReadTimeout)).await;
343        assert!(matches!(res, Err(WsError::ReadTimeout)));
344        let res = svc.call(DispatchItem::Stop(Reason::WriteTimeout)).await;
345        assert!(matches!(res, Err(WsError::WriteTimeout)));
346        let res = svc
347            .call(DispatchItem::Stop(Reason::Encoder(
348                ProtocolError::UnmaskedFrame,
349            )))
350            .await;
351        assert!(matches!(
352            res,
353            Err(WsError::Protocol(ProtocolError::UnmaskedFrame))
354        ));
355        let res = svc
356            .call(DispatchItem::Stop(Reason::Io(Some(io::Error::other("io")))))
357            .await;
358        assert!(matches!(res, Err(WsError::Disconnected(Some(_)))));
359
360        // decoder error sends close frame
361        assert!(!sink.is_closed());
362        let res = svc
363            .call(DispatchItem::Stop(Reason::Decoder(
364                ProtocolError::MaskedFrame,
365            )))
366            .await;
367        assert!(matches!(
368            res,
369            Err(WsError::Protocol(ProtocolError::MaskedFrame))
370        ));
371        assert!(sink.is_closed());
372        let res = svc
373            .call(DispatchItem::Stop(Reason::Decoder(
374                ProtocolError::MaskedFrame,
375            )))
376            .await;
377        assert!(matches!(res, Err(WsError::Protocol(_))));
378
379        // close frame closes io
380        let res = svc.call(DispatchItem::Item(Frame::Close(None))).await;
381        assert!(matches!(res, Ok(Some(Message::Pong(_)))));
382        io.on_disconnect().await;
383        assert!(io.is_closed());
384    }
385
386    /// STATEMENT: `start()` answers pings and the peer's close when the frame service returns `None`, without duplicating replies.
387    ///
388    /// HOW:
389    /// - Dispatch frames to a service that returns `None`, or a text reply for ping `"own"`, or sends a pong through the sink for ping `"sink"`.
390    /// - Expect a pong with the ping payload, the service's own reply, no reply after the sink pong but a pong for the next ping; text gets no reply.
391    /// - Expect the peer's close code to be echoed, an extension close to be answered with a normal close, and no reply once a close has been sent.
392    #[crate::rt_test]
393    async fn dispatch_service_auto_replies() {
394        let (client, server) = IoTest::create();
395        client.remote_buffer_cap(1 << 20);
396        let io = Io::from(server);
397        let sink = WsSink::new(io.get_ref(), ws::Codec::new(), crate::Cfg::default());
398        let sink2 = sink.clone();
399        let svc = Pipeline::new(
400            sink.clone(),
401            DispatchService {
402                svc: fn_service(async move |frame: Frame| match frame {
403                    Frame::Ping(p) if p == "own" => Ok(Some(Message::Text("own".into()))),
404                    Frame::Ping(p) if p == "sink" => {
405                        sink2.send(Message::Pong(p)).await.unwrap();
406                        Ok(None)
407                    }
408                    _ => Ok::<_, io::Error>(None),
409                }),
410            },
411        );
412
413        let res = svc.call(DispatchItem::Item(Frame::Ping("p".into()))).await;
414        assert_eq!(res.unwrap(), Some(Message::Pong("p".into())));
415        let res = svc
416            .call(DispatchItem::Item(Frame::Ping("own".into())))
417            .await;
418        assert_eq!(res.unwrap(), Some(Message::Text("own".into())));
419        let res = svc
420            .call(DispatchItem::Item(Frame::Ping("sink".into())))
421            .await;
422        assert_eq!(res.unwrap(), None);
423        let res = svc.call(DispatchItem::Item(Frame::Ping("p2".into()))).await;
424        assert_eq!(res.unwrap(), Some(Message::Pong("p2".into())));
425        let res = svc.call(DispatchItem::Item(Frame::Text("t".into()))).await;
426        assert_eq!(res.unwrap(), None);
427
428        // the peer's close code is echoed, servers cannot send the extension code
429        let close = Frame::Close(Some(ws::CloseCode::Away.into()));
430        let res = svc.call(DispatchItem::Item(close)).await;
431        assert_eq!(
432            res.unwrap(),
433            Some(Message::Close(Some(ws::CloseCode::Away.into())))
434        );
435        let close = Frame::Close(Some(ws::CloseCode::Extension.into()));
436        let res = svc.call(DispatchItem::Item(close)).await;
437        assert_eq!(
438            res.unwrap(),
439            Some(Message::Close(Some(ws::CloseCode::Normal.into())))
440        );
441
442        // nothing is sent after a close
443        sink.send(Message::Close(None)).await.unwrap();
444        let res = svc.call(DispatchItem::Item(Frame::Ping("p".into()))).await;
445        assert_eq!(res.unwrap(), None);
446        let close = Frame::Close(Some(ws::CloseCode::Away.into()));
447        let res = svc.call(DispatchItem::Item(close)).await;
448        assert_eq!(res.unwrap(), None);
449    }
450}