Skip to main content

ntex/ws/
cfg.rs

1use std::{fmt, net};
2
3use base64::{Engine, engine::general_purpose::STANDARD as base64};
4#[cfg(feature = "cookie")]
5use coo_kie::{Cookie, CookieJar};
6
7use crate::http::error::HttpError;
8use crate::http::header::{
9    self, AUTHORIZATION, HeaderMap, HeaderName, HeaderValue, InvalidHeaderValue,
10};
11use crate::service::cfg::{CfgContext, Configuration};
12use crate::time::Millis;
13
14/// Configuration for a WebSocket client connection.
15///
16/// Store this value in [`SharedCfg`](crate::SharedCfg) and pass the resulting
17/// configuration to [`WsClient::new`](super::WsClient::new).
18#[derive(Debug)]
19pub struct WsClientConfig {
20    pub(super) addr: Option<net::SocketAddr>,
21    pub(super) max_size: usize,
22    pub(super) max_message_size: usize,
23    pub(super) validate_utf8: bool,
24    pub(super) timeout: Millis,
25    pub(super) close_timeout: Millis,
26    pub(super) headers: HeaderMap,
27    pub(super) server_mode: bool,
28    #[cfg(feature = "compress")]
29    pub(super) deflate: Option<super::DeflateConfig>,
30    #[cfg(feature = "cookie")]
31    pub(super) cookies: Option<CookieJar>,
32
33    config: CfgContext,
34}
35
36impl Default for WsClientConfig {
37    fn default() -> Self {
38        Self::new()
39    }
40}
41
42impl Configuration for WsClientConfig {
43    const NAME: &str = "WebSocket client configuration";
44
45    fn ctx(&self) -> &CfgContext {
46        &self.config
47    }
48
49    fn set_ctx(&mut self, ctx: CfgContext) {
50        self.config = ctx;
51    }
52}
53
54impl WsClientConfig {
55    #[must_use]
56    /// Creates a WebSocket client configuration with default values.
57    pub fn new() -> WsClientConfig {
58        let mut headers = HeaderMap::new();
59        headers.insert(header::UPGRADE, HeaderValue::from_static("websocket"));
60        headers.insert(
61            header::SEC_WEBSOCKET_VERSION,
62            HeaderValue::from_static("13"),
63        );
64
65        WsClientConfig {
66            headers,
67            addr: None,
68            max_size: 65_536,
69            max_message_size: 4 * 1024 * 1024,
70            validate_utf8: true,
71            server_mode: false,
72            timeout: Millis(5_000),
73            close_timeout: Millis(5_000),
74            #[cfg(feature = "compress")]
75            deflate: None,
76            #[cfg(feature = "cookie")]
77            cookies: None,
78            config: CfgContext::default(),
79        }
80    }
81
82    #[must_use]
83    /// Sets the server socket address.
84    ///
85    /// This address is used instead of resolving the URI host name.
86    pub fn set_address(mut self, addr: net::SocketAddr) -> Self {
87        self.addr = Some(addr);
88        self
89    }
90
91    /// Sets the WebSocket subprotocols offered to the server.
92    ///
93    /// This replaces the current `Sec-WebSocket-Protocol` header. An empty
94    /// iterator removes the header.
95    ///
96    /// # Errors
97    ///
98    /// Returns [`HttpError`] if a protocol is not a valid HTTP token or the
99    /// resulting list is not a valid HTTP header value.
100    pub fn set_protocols<U, V>(mut self, protos: U) -> Result<Self, HttpError>
101    where
102        U: IntoIterator<Item = V>,
103        V: AsRef<str>,
104    {
105        let mut values = Vec::new();
106        for proto in protos {
107            let proto = proto.as_ref();
108            if !is_token(proto) {
109                return Err(InvalidHeaderValue::default().into());
110            }
111            values.push(proto.to_owned());
112        }
113        let protos = values.join(",");
114
115        if protos.is_empty() {
116            self.headers.remove(header::SEC_WEBSOCKET_PROTOCOL);
117        } else {
118            self.headers.insert(
119                header::SEC_WEBSOCKET_PROTOCOL,
120                HeaderValue::try_from(protos.as_str())?,
121            );
122        }
123        Ok(self)
124    }
125
126    #[must_use]
127    #[cfg(feature = "cookie")]
128    /// Adds a cookie to the opening handshake.
129    pub fn set_cookie<C>(mut self, cookie: C) -> Self
130    where
131        C: Into<Cookie<'static>>,
132    {
133        if let Some(cookies) = &mut self.cookies {
134            cookies.add(cookie.into());
135        } else {
136            let mut jar = CookieJar::new();
137            jar.add(cookie.into());
138            self.cookies = Some(jar);
139        }
140        self
141    }
142
143    /// Sets the `Origin` header for the opening handshake.
144    pub fn set_origin<V, E>(mut self, origin: V) -> Result<Self, HttpError>
145    where
146        HeaderValue: TryFrom<V, Error = E>,
147        HttpError: From<E>,
148    {
149        self.headers
150            .insert(header::ORIGIN, HeaderValue::try_from(origin)?);
151        Ok(self)
152    }
153
154    #[must_use]
155    /// Sets the maximum accepted frame payload size.
156    ///
157    /// The default is 64 KiB. The total size of a fragmented message is
158    /// limited separately, see [`WsClientConfig::set_max_message_size()`].
159    pub fn set_max_frame_size(mut self, size: usize) -> Self {
160        self.max_size = size;
161        self
162    }
163
164    #[must_use]
165    /// Sets the maximum accepted payload size of an incoming message.
166    ///
167    /// The limit applies to the total payload of all frames of a message.
168    /// The default is 4 MiB, see [`Codec::max_message_size()`](super::Codec::max_message_size).
169    pub fn set_max_message_size(mut self, size: usize) -> Self {
170        self.max_message_size = size;
171        self
172    }
173
174    #[must_use]
175    /// Enables or disables UTF-8 validation of incoming text messages.
176    ///
177    /// Validation is enabled by default, see
178    /// [`Codec::validate_utf8()`](super::Codec::validate_utf8).
179    pub fn set_validate_utf8(mut self, enabled: bool) -> Self {
180        self.validate_utf8 = enabled;
181        self
182    }
183
184    #[must_use]
185    /// Configures the connection to use server-side masking rules.
186    ///
187    /// By default, the client masks outgoing frames and expects unmasked
188    /// incoming frames. Server mode reverses those rules.
189    pub fn set_server_mode(mut self) -> Self {
190        self.server_mode = true;
191        self
192    }
193
194    #[must_use]
195    #[cfg(feature = "compress")]
196    /// Offers the `permessage-deflate` extension (RFC 7692) to the server.
197    ///
198    /// If the server accepts the offer, text and binary messages are
199    /// compressed in both directions. The server may decline it, then the
200    /// messages are not compressed. The opening handshake fails if the server
201    /// accepts the offer with parameters the client did not allow.
202    ///
203    /// The extension is not offered by default.
204    ///
205    /// ```rust
206    /// use ntex::ws::{DeflateConfig, WsClientConfig};
207    ///
208    /// let cfg = WsClientConfig::new().set_deflate(
209    ///     DeflateConfig::new().set_client_no_context_takeover(true)
210    /// );
211    /// ```
212    pub fn set_deflate(mut self, cfg: super::DeflateConfig) -> Self {
213        self.deflate = Some(cfg);
214        self
215    }
216
217    /// Sets a header for the opening handshake.
218    ///
219    /// This replaces any existing value with the same name.
220    pub fn set_header<K, V>(mut self, key: K, value: V) -> Result<Self, HttpError>
221    where
222        HeaderName: TryFrom<K>,
223        HeaderValue: TryFrom<V>,
224        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
225        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
226    {
227        let key = HeaderName::try_from(key).map_err(Into::into)?;
228        let value = HeaderValue::try_from(value).map_err(Into::into)?;
229        self.headers.insert(key, value);
230        Ok(self)
231    }
232
233    /// Sets a handshake header if it is not already present.
234    pub fn set_header_if_none<K, V>(mut self, key: K, value: V) -> Result<Self, HttpError>
235    where
236        HeaderName: TryFrom<K>,
237        HeaderValue: TryFrom<V>,
238        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
239        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
240    {
241        let key = HeaderName::try_from(key).map_err(Into::into)?;
242        if !self.headers.contains_key(&key) {
243            self.headers
244                .insert(key, HeaderValue::try_from(value).map_err(Into::into)?);
245        }
246        Ok(self)
247    }
248
249    /// Sets the HTTP Basic authentication header.
250    pub fn set_basic_auth(
251        self,
252        username: impl fmt::Display,
253        password: Option<&str>,
254    ) -> Result<Self, HttpError> {
255        let auth = match password {
256            Some(password) => format!("{username}:{password}"),
257            None => format!("{username}:"),
258        };
259        self.set_header(AUTHORIZATION, format!("Basic {}", base64.encode(auth)))
260    }
261
262    /// Sets the HTTP bearer authentication header.
263    pub fn set_bearer_auth(self, token: impl fmt::Display) -> Result<Self, HttpError> {
264        self.set_header(AUTHORIZATION, format!("Bearer {token}"))
265    }
266
267    #[must_use]
268    /// Sets the opening-handshake timeout.
269    ///
270    /// The timeout covers sending the upgrade request and receiving the
271    /// response after a connection has been established. The default is
272    /// 5 seconds. A zero duration disables the timeout.
273    pub fn set_handshake_timeout(mut self, timeout: impl Into<Millis>) -> Self {
274        self.timeout = timeout.into();
275        self
276    }
277
278    #[must_use]
279    /// Sets the closing-handshake timeout.
280    ///
281    /// After sending a close frame, the client waits this long for the peer's
282    /// close response before shutting down the connection. The default is
283    /// 5 seconds. A zero duration disables the timeout.
284    pub fn set_close_timeout(mut self, timeout: impl Into<Millis>) -> Self {
285        self.close_timeout = timeout.into();
286        self
287    }
288}
289
290pub(crate) fn is_token(value: &str) -> bool {
291    !value.is_empty()
292        && value.bytes().all(|byte| {
293            byte.is_ascii_alphanumeric()
294                || matches!(
295                    byte,
296                    b'!' | b'#'
297                        | b'$'
298                        | b'%'
299                        | b'&'
300                        | b'\''
301                        | b'*'
302                        | b'+'
303                        | b'-'
304                        | b'.'
305                        | b'^'
306                        | b'_'
307                        | b'`'
308                        | b'|'
309                        | b'~'
310                )
311        })
312}