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#[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 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 pub fn set_address(mut self, addr: net::SocketAddr) -> Self {
87 self.addr = Some(addr);
88 self
89 }
90
91 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 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 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 pub fn set_max_frame_size(mut self, size: usize) -> Self {
160 self.max_size = size;
161 self
162 }
163
164 #[must_use]
165 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 pub fn set_validate_utf8(mut self, enabled: bool) -> Self {
180 self.validate_utf8 = enabled;
181 self
182 }
183
184 #[must_use]
185 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 pub fn set_deflate(mut self, cfg: super::DeflateConfig) -> Self {
213 self.deflate = Some(cfg);
214 self
215 }
216
217 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 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 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 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 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 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}