2019-03-28 02:53:19 +01:00
|
|
|
//! Websockets client
|
2020-09-07 13:04:54 +02:00
|
|
|
//!
|
2020-12-13 14:28:39 +01:00
|
|
|
//! Type definitions required to use [`awc::Client`](super::Client) as a WebSocket client.
|
2020-09-07 13:04:54 +02:00
|
|
|
//!
|
|
|
|
//! # Example
|
|
|
|
//!
|
2021-01-08 13:00:58 +01:00
|
|
|
//! ```no_run
|
2020-09-07 13:04:54 +02:00
|
|
|
//! use awc::{Client, ws};
|
|
|
|
//! use futures_util::{sink::SinkExt, stream::StreamExt};
|
|
|
|
//!
|
|
|
|
//! #[actix_rt::main]
|
|
|
|
//! async fn main() {
|
|
|
|
//! let (_resp, mut connection) = Client::new()
|
|
|
|
//! .ws("ws://echo.websocket.org")
|
|
|
|
//! .connect()
|
|
|
|
//! .await
|
|
|
|
//! .unwrap();
|
|
|
|
//!
|
|
|
|
//! connection
|
2021-01-04 12:27:32 +01:00
|
|
|
//! .send(ws::Message::Text("Echo".into()))
|
2020-09-07 13:04:54 +02:00
|
|
|
//! .await
|
|
|
|
//! .unwrap();
|
|
|
|
//! let response = connection.next().await.unwrap().unwrap();
|
|
|
|
//!
|
|
|
|
//! assert_eq!(response, ws::Frame::Text("Echo".as_bytes().into()));
|
|
|
|
//! }
|
|
|
|
//! ```
|
|
|
|
|
2019-12-05 18:35:43 +01:00
|
|
|
use std::convert::TryFrom;
|
2019-04-20 03:03:44 +02:00
|
|
|
use std::net::SocketAddr;
|
2019-03-28 02:53:19 +01:00
|
|
|
use std::{fmt, str};
|
|
|
|
|
2019-03-29 22:27:22 +01:00
|
|
|
use actix_codec::Framed;
|
2021-02-13 16:08:43 +01:00
|
|
|
#[cfg(feature = "cookies")]
|
2019-03-30 05:13:39 +01:00
|
|
|
use actix_http::cookie::{Cookie, CookieJar};
|
2019-03-28 02:53:19 +01:00
|
|
|
use actix_http::{ws, Payload, RequestHead};
|
2019-12-05 18:35:43 +01:00
|
|
|
use actix_rt::time::timeout;
|
2021-02-17 18:10:46 +01:00
|
|
|
use actix_service::Service;
|
2019-03-28 02:53:19 +01:00
|
|
|
|
2019-03-30 02:51:07 +01:00
|
|
|
pub use actix_http::ws::{CloseCode, CloseReason, Codec, Frame, Message};
|
2019-03-29 21:49:21 +01:00
|
|
|
|
2021-02-17 18:10:46 +01:00
|
|
|
use crate::connect::{BoxedSocket, ConnectRequest};
|
2019-03-29 06:33:41 +01:00
|
|
|
use crate::error::{InvalidUrl, SendRequestError, WsClientError};
|
2021-02-12 00:03:17 +01:00
|
|
|
use crate::http::header::{self, HeaderName, HeaderValue, IntoHeaderValue, AUTHORIZATION};
|
|
|
|
use crate::http::{ConnectionType, Error as HttpError, Method, StatusCode, Uri, Version};
|
2019-03-28 02:53:19 +01:00
|
|
|
use crate::response::ClientResponse;
|
2019-03-29 06:33:41 +01:00
|
|
|
use crate::ClientConfig;
|
2019-03-28 02:53:19 +01:00
|
|
|
|
2021-02-12 01:27:20 +01:00
|
|
|
/// WebSocket connection.
|
2019-03-28 02:53:19 +01:00
|
|
|
pub struct WebsocketsRequest {
|
2019-03-29 05:48:35 +01:00
|
|
|
pub(crate) head: RequestHead,
|
2019-03-28 02:53:19 +01:00
|
|
|
err: Option<HttpError>,
|
|
|
|
origin: Option<HeaderValue>,
|
|
|
|
protocols: Option<String>,
|
2019-04-20 03:03:44 +02:00
|
|
|
addr: Option<SocketAddr>,
|
2019-03-28 02:53:19 +01:00
|
|
|
max_size: usize,
|
|
|
|
server_mode: bool,
|
2021-03-18 18:53:22 +01:00
|
|
|
config: ClientConfig,
|
2021-02-13 16:08:43 +01:00
|
|
|
|
|
|
|
#[cfg(feature = "cookies")]
|
|
|
|
cookies: Option<CookieJar>,
|
2019-03-28 02:53:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl WebsocketsRequest {
|
2021-02-12 01:27:20 +01:00
|
|
|
/// Create new WebSocket connection
|
2021-03-18 18:53:22 +01:00
|
|
|
pub(crate) fn new<U>(uri: U, config: ClientConfig) -> Self
|
2019-03-28 02:53:19 +01:00
|
|
|
where
|
2019-12-05 18:35:43 +01:00
|
|
|
Uri: TryFrom<U>,
|
|
|
|
<Uri as TryFrom<U>>::Error: Into<HttpError>,
|
2019-03-28 02:53:19 +01:00
|
|
|
{
|
|
|
|
let mut err = None;
|
2020-12-09 12:22:19 +01:00
|
|
|
|
|
|
|
#[allow(clippy::field_reassign_with_default)]
|
|
|
|
let mut head = {
|
|
|
|
let mut head = RequestHead::default();
|
|
|
|
head.method = Method::GET;
|
|
|
|
head.version = Version::HTTP_11;
|
|
|
|
head
|
|
|
|
};
|
2019-03-28 02:53:19 +01:00
|
|
|
|
|
|
|
match Uri::try_from(uri) {
|
|
|
|
Ok(uri) => head.uri = uri,
|
|
|
|
Err(e) => err = Some(e.into()),
|
|
|
|
}
|
|
|
|
|
|
|
|
WebsocketsRequest {
|
|
|
|
head,
|
|
|
|
err,
|
2019-03-29 06:33:41 +01:00
|
|
|
config,
|
2019-04-20 03:03:44 +02:00
|
|
|
addr: None,
|
2019-03-28 02:53:19 +01:00
|
|
|
origin: None,
|
|
|
|
protocols: None,
|
|
|
|
max_size: 65_536,
|
|
|
|
server_mode: false,
|
2021-02-13 16:08:43 +01:00
|
|
|
#[cfg(feature = "cookies")]
|
2019-03-28 02:53:19 +01:00
|
|
|
cookies: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-20 03:03:44 +02:00
|
|
|
/// Set socket address of the server.
|
|
|
|
///
|
|
|
|
/// This address is used for connection. If address is not
|
|
|
|
/// provided url's host name get resolved.
|
|
|
|
pub fn address(mut self, addr: SocketAddr) -> Self {
|
|
|
|
self.addr = Some(addr);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2021-02-12 01:27:20 +01:00
|
|
|
/// Set supported WebSocket protocols
|
2019-03-28 02:53:19 +01:00
|
|
|
pub fn protocols<U, V>(mut self, protos: U) -> Self
|
|
|
|
where
|
2019-04-04 19:59:34 +02:00
|
|
|
U: IntoIterator<Item = V>,
|
2019-03-28 02:53:19 +01:00
|
|
|
V: AsRef<str>,
|
|
|
|
{
|
|
|
|
let mut protos = protos
|
|
|
|
.into_iter()
|
|
|
|
.fold(String::new(), |acc, s| acc + s.as_ref() + ",");
|
|
|
|
protos.pop();
|
|
|
|
self.protocols = Some(protos);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set a cookie
|
2021-02-13 16:08:43 +01:00
|
|
|
#[cfg(feature = "cookies")]
|
2019-07-17 11:08:30 +02:00
|
|
|
pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
|
2019-03-28 02:53:19 +01:00
|
|
|
if self.cookies.is_none() {
|
|
|
|
let mut jar = CookieJar::new();
|
|
|
|
jar.add(cookie.into_owned());
|
|
|
|
self.cookies = Some(jar)
|
|
|
|
} else {
|
|
|
|
self.cookies.as_mut().unwrap().add(cookie.into_owned());
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set request Origin
|
2019-12-05 18:35:43 +01:00
|
|
|
pub fn origin<V, E>(mut self, origin: V) -> Self
|
2019-03-28 02:53:19 +01:00
|
|
|
where
|
2019-12-05 18:35:43 +01:00
|
|
|
HeaderValue: TryFrom<V, Error = E>,
|
|
|
|
HttpError: From<E>,
|
2019-03-28 02:53:19 +01:00
|
|
|
{
|
|
|
|
match HeaderValue::try_from(origin) {
|
|
|
|
Ok(value) => self.origin = Some(value),
|
|
|
|
Err(e) => self.err = Some(e.into()),
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set max frame size
|
|
|
|
///
|
2021-01-09 14:17:19 +01:00
|
|
|
/// By default max size is set to 64kB
|
2019-03-28 02:53:19 +01:00
|
|
|
pub fn max_frame_size(mut self, size: usize) -> Self {
|
|
|
|
self.max_size = size;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Disable payload masking. By default ws client masks frame payload.
|
|
|
|
pub fn server_mode(mut self) -> Self {
|
|
|
|
self.server_mode = true;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Append a header.
|
|
|
|
///
|
|
|
|
/// Header gets appended to existing header.
|
|
|
|
/// To override header use `set_header()` method.
|
|
|
|
pub fn header<K, V>(mut self, key: K, value: V) -> Self
|
|
|
|
where
|
2019-12-05 18:35:43 +01:00
|
|
|
HeaderName: TryFrom<K>,
|
|
|
|
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
|
2019-03-28 02:53:19 +01:00
|
|
|
V: IntoHeaderValue,
|
|
|
|
{
|
|
|
|
match HeaderName::try_from(key) {
|
2021-01-15 03:11:10 +01:00
|
|
|
Ok(key) => match value.try_into_value() {
|
2019-03-28 02:53:19 +01:00
|
|
|
Ok(value) => {
|
|
|
|
self.head.headers.append(key, value);
|
|
|
|
}
|
|
|
|
Err(e) => self.err = Some(e.into()),
|
|
|
|
},
|
|
|
|
Err(e) => self.err = Some(e.into()),
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Insert a header, replaces existing header.
|
|
|
|
pub fn set_header<K, V>(mut self, key: K, value: V) -> Self
|
|
|
|
where
|
2019-12-05 18:35:43 +01:00
|
|
|
HeaderName: TryFrom<K>,
|
|
|
|
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
|
2019-03-28 02:53:19 +01:00
|
|
|
V: IntoHeaderValue,
|
|
|
|
{
|
|
|
|
match HeaderName::try_from(key) {
|
2021-01-15 03:11:10 +01:00
|
|
|
Ok(key) => match value.try_into_value() {
|
2019-03-28 02:53:19 +01:00
|
|
|
Ok(value) => {
|
|
|
|
self.head.headers.insert(key, value);
|
|
|
|
}
|
|
|
|
Err(e) => self.err = Some(e.into()),
|
|
|
|
},
|
|
|
|
Err(e) => self.err = Some(e.into()),
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Insert a header only if it is not yet set.
|
|
|
|
pub fn set_header_if_none<K, V>(mut self, key: K, value: V) -> Self
|
|
|
|
where
|
2019-12-05 18:35:43 +01:00
|
|
|
HeaderName: TryFrom<K>,
|
|
|
|
<HeaderName as TryFrom<K>>::Error: Into<HttpError>,
|
2019-03-28 02:53:19 +01:00
|
|
|
V: IntoHeaderValue,
|
|
|
|
{
|
|
|
|
match HeaderName::try_from(key) {
|
|
|
|
Ok(key) => {
|
|
|
|
if !self.head.headers.contains_key(&key) {
|
2021-01-15 03:11:10 +01:00
|
|
|
match value.try_into_value() {
|
2019-03-28 02:53:19 +01:00
|
|
|
Ok(value) => {
|
|
|
|
self.head.headers.insert(key, value);
|
|
|
|
}
|
|
|
|
Err(e) => self.err = Some(e.into()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(e) => self.err = Some(e.into()),
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set HTTP basic authorization header
|
2019-04-14 16:43:53 +02:00
|
|
|
pub fn basic_auth<U>(self, username: U, password: Option<&str>) -> Self
|
2019-03-28 02:53:19 +01:00
|
|
|
where
|
|
|
|
U: fmt::Display,
|
|
|
|
{
|
|
|
|
let auth = match password {
|
|
|
|
Some(password) => format!("{}:{}", username, password),
|
2019-07-01 05:34:42 +02:00
|
|
|
None => format!("{}:", username),
|
2019-03-28 02:53:19 +01:00
|
|
|
};
|
|
|
|
self.header(AUTHORIZATION, format!("Basic {}", base64::encode(&auth)))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set HTTP bearer authentication header
|
|
|
|
pub fn bearer_auth<T>(self, token: T) -> Self
|
|
|
|
where
|
|
|
|
T: fmt::Display,
|
|
|
|
{
|
|
|
|
self.header(AUTHORIZATION, format!("Bearer {}", token))
|
|
|
|
}
|
|
|
|
|
2021-02-12 01:27:20 +01:00
|
|
|
/// Complete request construction and connect to a WebSocket server.
|
2019-11-19 04:55:17 +01:00
|
|
|
pub async fn connect(
|
2019-03-28 02:53:19 +01:00
|
|
|
mut self,
|
2019-11-19 04:55:17 +01:00
|
|
|
) -> Result<(ClientResponse, Framed<BoxedSocket, Codec>), WsClientError> {
|
2019-03-28 02:53:19 +01:00
|
|
|
if let Some(e) = self.err.take() {
|
2019-11-19 04:55:17 +01:00
|
|
|
return Err(e.into());
|
2019-03-28 02:53:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// validate uri
|
|
|
|
let uri = &self.head.uri;
|
|
|
|
if uri.host().is_none() {
|
2019-11-19 04:55:17 +01:00
|
|
|
return Err(InvalidUrl::MissingHost.into());
|
2019-12-05 18:35:43 +01:00
|
|
|
} else if uri.scheme().is_none() {
|
2019-11-19 04:55:17 +01:00
|
|
|
return Err(InvalidUrl::MissingScheme.into());
|
2019-12-05 18:35:43 +01:00
|
|
|
} else if let Some(scheme) = uri.scheme() {
|
2019-03-28 02:53:19 +01:00
|
|
|
match scheme.as_str() {
|
2021-01-04 02:01:35 +01:00
|
|
|
"http" | "ws" | "https" | "wss" => {}
|
2019-11-19 04:55:17 +01:00
|
|
|
_ => return Err(InvalidUrl::UnknownScheme.into()),
|
2019-03-28 02:53:19 +01:00
|
|
|
}
|
|
|
|
} else {
|
2019-11-19 04:55:17 +01:00
|
|
|
return Err(InvalidUrl::UnknownScheme.into());
|
2019-03-28 02:53:19 +01:00
|
|
|
}
|
|
|
|
|
2019-09-09 08:27:13 +02:00
|
|
|
if !self.head.headers.contains_key(header::HOST) {
|
2019-09-12 17:52:46 +02:00
|
|
|
self.head.headers.insert(
|
|
|
|
header::HOST,
|
|
|
|
HeaderValue::from_str(uri.host().unwrap()).unwrap(),
|
|
|
|
);
|
2019-09-09 08:27:13 +02:00
|
|
|
}
|
|
|
|
|
2019-03-30 05:13:39 +01:00
|
|
|
// set cookies
|
2021-02-13 16:08:43 +01:00
|
|
|
#[cfg(feature = "cookies")]
|
2019-04-14 16:43:53 +02:00
|
|
|
if let Some(ref mut jar) = self.cookies {
|
2020-06-19 15:34:14 +02:00
|
|
|
let cookie: String = jar
|
|
|
|
.delta()
|
|
|
|
// ensure only name=value is written to cookie header
|
|
|
|
.map(|c| Cookie::new(c.name(), c.value()).encoded().to_string())
|
|
|
|
.collect::<Vec<_>>()
|
|
|
|
.join("; ");
|
|
|
|
|
|
|
|
if !cookie.is_empty() {
|
|
|
|
self.head
|
|
|
|
.headers
|
|
|
|
.insert(header::COOKIE, HeaderValue::from_str(&cookie).unwrap());
|
2019-03-28 02:53:19 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// origin
|
2019-04-14 16:43:53 +02:00
|
|
|
if let Some(origin) = self.origin.take() {
|
|
|
|
self.head.headers.insert(header::ORIGIN, origin);
|
2019-03-28 02:53:19 +01:00
|
|
|
}
|
|
|
|
|
2019-04-14 16:43:53 +02:00
|
|
|
self.head.set_connection_type(ConnectionType::Upgrade);
|
|
|
|
self.head
|
|
|
|
.headers
|
2019-03-28 02:53:19 +01:00
|
|
|
.insert(header::UPGRADE, HeaderValue::from_static("websocket"));
|
2019-04-14 16:43:53 +02:00
|
|
|
self.head.headers.insert(
|
2019-03-28 02:53:19 +01:00
|
|
|
header::SEC_WEBSOCKET_VERSION,
|
|
|
|
HeaderValue::from_static("13"),
|
|
|
|
);
|
|
|
|
|
2019-04-14 16:43:53 +02:00
|
|
|
if let Some(protocols) = self.protocols.take() {
|
|
|
|
self.head.headers.insert(
|
2019-03-28 02:53:19 +01:00
|
|
|
header::SEC_WEBSOCKET_PROTOCOL,
|
|
|
|
HeaderValue::try_from(protocols.as_str()).unwrap(),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Generate a random key for the `Sec-WebSocket-Key` header.
|
|
|
|
// a base64-encoded (see Section 4 of [RFC4648]) value that,
|
|
|
|
// when decoded, is 16 bytes in length (RFC 6455)
|
|
|
|
let sec_key: [u8; 16] = rand::random();
|
|
|
|
let key = base64::encode(&sec_key);
|
|
|
|
|
2019-04-14 16:43:53 +02:00
|
|
|
self.head.headers.insert(
|
2019-03-28 02:53:19 +01:00
|
|
|
header::SEC_WEBSOCKET_KEY,
|
|
|
|
HeaderValue::try_from(key.as_str()).unwrap(),
|
|
|
|
);
|
|
|
|
|
2019-04-14 16:43:53 +02:00
|
|
|
let head = self.head;
|
|
|
|
let max_size = self.max_size;
|
|
|
|
let server_mode = self.server_mode;
|
2019-03-28 02:53:19 +01:00
|
|
|
|
2021-02-17 18:10:46 +01:00
|
|
|
let req = ConnectRequest::Tunnel(head, self.addr);
|
|
|
|
|
|
|
|
let fut = self.config.connector.call(req);
|
2019-03-29 06:33:41 +01:00
|
|
|
|
|
|
|
// set request timeout
|
2021-02-17 18:10:46 +01:00
|
|
|
let res = if let Some(to) = self.config.timeout {
|
2019-12-05 18:35:43 +01:00
|
|
|
timeout(to, fut)
|
2019-11-19 04:55:17 +01:00
|
|
|
.await
|
2021-02-17 18:10:46 +01:00
|
|
|
.map_err(|_| SendRequestError::Timeout)??
|
2019-11-19 04:55:17 +01:00
|
|
|
} else {
|
|
|
|
fut.await?
|
|
|
|
};
|
|
|
|
|
2021-02-17 18:10:46 +01:00
|
|
|
let (head, framed) = res.into_tunnel_response();
|
|
|
|
|
2019-11-19 04:55:17 +01:00
|
|
|
// verify response
|
|
|
|
if head.status != StatusCode::SWITCHING_PROTOCOLS {
|
|
|
|
return Err(WsClientError::InvalidResponseStatus(head.status));
|
|
|
|
}
|
|
|
|
|
2021-02-12 01:27:20 +01:00
|
|
|
// check for "UPGRADE" to WebSocket header
|
2019-11-19 04:55:17 +01:00
|
|
|
let has_hdr = if let Some(hdr) = head.headers.get(&header::UPGRADE) {
|
|
|
|
if let Ok(s) = hdr.to_str() {
|
|
|
|
s.to_ascii_lowercase().contains("websocket")
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
};
|
|
|
|
if !has_hdr {
|
|
|
|
log::trace!("Invalid upgrade header");
|
|
|
|
return Err(WsClientError::InvalidUpgradeHeader);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check for "CONNECTION" header
|
|
|
|
if let Some(conn) = head.headers.get(&header::CONNECTION) {
|
|
|
|
if let Ok(s) = conn.to_str() {
|
|
|
|
if !s.to_ascii_lowercase().contains("upgrade") {
|
|
|
|
log::trace!("Invalid connection header: {}", s);
|
|
|
|
return Err(WsClientError::InvalidConnectionHeader(conn.clone()));
|
2019-03-29 06:33:41 +01:00
|
|
|
}
|
2019-11-19 04:55:17 +01:00
|
|
|
} else {
|
|
|
|
log::trace!("Invalid connection header: {:?}", conn);
|
|
|
|
return Err(WsClientError::InvalidConnectionHeader(conn.clone()));
|
|
|
|
}
|
2019-03-29 06:33:41 +01:00
|
|
|
} else {
|
2019-11-19 04:55:17 +01:00
|
|
|
log::trace!("Missing connection header");
|
|
|
|
return Err(WsClientError::MissingConnectionHeader);
|
2019-03-29 06:33:41 +01:00
|
|
|
}
|
2019-11-19 04:55:17 +01:00
|
|
|
|
|
|
|
if let Some(hdr_key) = head.headers.get(&header::SEC_WEBSOCKET_ACCEPT) {
|
|
|
|
let encoded = ws::hash_key(key.as_ref());
|
2021-02-28 20:55:34 +01:00
|
|
|
|
2021-03-08 21:32:19 +01:00
|
|
|
if hdr_key.as_bytes() != encoded {
|
2019-11-19 04:55:17 +01:00
|
|
|
log::trace!(
|
2021-02-28 20:55:34 +01:00
|
|
|
"Invalid challenge response: expected: {:?} received: {:?}",
|
|
|
|
&encoded,
|
2019-11-19 04:55:17 +01:00
|
|
|
key
|
|
|
|
);
|
2021-02-28 20:55:34 +01:00
|
|
|
|
2019-11-19 04:55:17 +01:00
|
|
|
return Err(WsClientError::InvalidChallengeResponse(
|
|
|
|
encoded,
|
|
|
|
hdr_key.clone(),
|
|
|
|
));
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
log::trace!("Missing SEC-WEBSOCKET-ACCEPT header");
|
|
|
|
return Err(WsClientError::MissingWebSocketAcceptHeader);
|
|
|
|
};
|
|
|
|
|
|
|
|
// response and ws framed
|
|
|
|
Ok((
|
|
|
|
ClientResponse::new(head, Payload::None),
|
2020-08-24 11:13:35 +02:00
|
|
|
framed.into_map_codec(|_| {
|
2019-11-19 04:55:17 +01:00
|
|
|
if server_mode {
|
|
|
|
ws::Codec::new().max_size(max_size)
|
|
|
|
} else {
|
|
|
|
ws::Codec::new().max_size(max_size).client_mode()
|
|
|
|
}
|
|
|
|
}),
|
|
|
|
))
|
2019-03-28 02:53:19 +01:00
|
|
|
}
|
|
|
|
}
|
2019-04-14 16:43:53 +02:00
|
|
|
|
|
|
|
impl fmt::Debug for WebsocketsRequest {
|
2019-12-08 07:31:16 +01:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2019-04-14 16:43:53 +02:00
|
|
|
writeln!(
|
|
|
|
f,
|
|
|
|
"\nWebsocketsRequest {}:{}",
|
|
|
|
self.head.method, self.head.uri
|
|
|
|
)?;
|
|
|
|
writeln!(f, " headers:")?;
|
|
|
|
for (key, val) in self.head.headers.iter() {
|
|
|
|
writeln!(f, " {:?}: {:?}", key, val)?;
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
use crate::Client;
|
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_debug() {
|
2019-04-14 16:43:53 +02:00
|
|
|
let request = Client::new().ws("/").header("x-test", "111");
|
|
|
|
let repr = format!("{:?}", request);
|
|
|
|
assert!(repr.contains("WebsocketsRequest"));
|
|
|
|
assert!(repr.contains("x-test"));
|
|
|
|
}
|
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_header_override() {
|
2020-09-11 10:24:39 +02:00
|
|
|
let req = Client::builder()
|
2019-04-14 16:43:53 +02:00
|
|
|
.header(header::CONTENT_TYPE, "111")
|
|
|
|
.finish()
|
|
|
|
.ws("/")
|
|
|
|
.set_header(header::CONTENT_TYPE, "222");
|
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
req.head
|
|
|
|
.headers
|
|
|
|
.get(header::CONTENT_TYPE)
|
|
|
|
.unwrap()
|
|
|
|
.to_str()
|
|
|
|
.unwrap(),
|
|
|
|
"222"
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn basic_auth() {
|
2019-04-14 16:43:53 +02:00
|
|
|
let req = Client::new()
|
|
|
|
.ws("/")
|
|
|
|
.basic_auth("username", Some("password"));
|
|
|
|
assert_eq!(
|
|
|
|
req.head
|
|
|
|
.headers
|
|
|
|
.get(header::AUTHORIZATION)
|
|
|
|
.unwrap()
|
|
|
|
.to_str()
|
|
|
|
.unwrap(),
|
|
|
|
"Basic dXNlcm5hbWU6cGFzc3dvcmQ="
|
|
|
|
);
|
|
|
|
|
|
|
|
let req = Client::new().ws("/").basic_auth("username", None);
|
|
|
|
assert_eq!(
|
|
|
|
req.head
|
|
|
|
.headers
|
|
|
|
.get(header::AUTHORIZATION)
|
|
|
|
.unwrap()
|
|
|
|
.to_str()
|
|
|
|
.unwrap(),
|
2019-07-01 05:34:42 +02:00
|
|
|
"Basic dXNlcm5hbWU6"
|
2019-04-14 16:43:53 +02:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn bearer_auth() {
|
2019-04-14 16:43:53 +02:00
|
|
|
let req = Client::new().ws("/").bearer_auth("someS3cr3tAutht0k3n");
|
|
|
|
assert_eq!(
|
|
|
|
req.head
|
|
|
|
.headers
|
|
|
|
.get(header::AUTHORIZATION)
|
|
|
|
.unwrap()
|
|
|
|
.to_str()
|
|
|
|
.unwrap(),
|
|
|
|
"Bearer someS3cr3tAutht0k3n"
|
|
|
|
);
|
2019-04-19 06:28:23 +02:00
|
|
|
let _ = req.connect();
|
2019-04-14 16:43:53 +02:00
|
|
|
}
|
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn basics() {
|
|
|
|
let req = Client::new()
|
|
|
|
.ws("http://localhost/")
|
|
|
|
.origin("test-origin")
|
|
|
|
.max_frame_size(100)
|
|
|
|
.server_mode()
|
|
|
|
.protocols(&["v1", "v2"])
|
|
|
|
.set_header_if_none(header::CONTENT_TYPE, "json")
|
|
|
|
.set_header_if_none(header::CONTENT_TYPE, "text")
|
|
|
|
.cookie(Cookie::build("cookie1", "value1").finish());
|
|
|
|
assert_eq!(
|
|
|
|
req.origin.as_ref().unwrap().to_str().unwrap(),
|
|
|
|
"test-origin"
|
|
|
|
);
|
|
|
|
assert_eq!(req.max_size, 100);
|
|
|
|
assert_eq!(req.server_mode, true);
|
|
|
|
assert_eq!(req.protocols, Some("v1,v2".to_string()));
|
|
|
|
assert_eq!(
|
|
|
|
req.head.headers.get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
header::HeaderValue::from_static("json")
|
|
|
|
);
|
2019-05-12 17:34:51 +02:00
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
let _ = req.connect().await;
|
2019-04-19 06:28:23 +02:00
|
|
|
|
2019-11-26 06:25:50 +01:00
|
|
|
assert!(Client::new().ws("/").connect().await.is_err());
|
|
|
|
assert!(Client::new().ws("http:///test").connect().await.is_err());
|
|
|
|
assert!(Client::new().ws("hmm://test.com/").connect().await.is_err());
|
2019-04-14 16:43:53 +02:00
|
|
|
}
|
|
|
|
}
|