1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
use super::*;
use http::Header;
use std::{fmt::Display, sync::Arc};
use tokio::{
io::BufReader,
net::{TcpStream, ToSocketAddrs},
};
use tokio_rustls::{
client::TlsStream,
rustls::{ClientConfig, OwnedTrustAnchor, RootCertStore},
TlsConnector,
};
pub type WS = WebSocket<CLIENT, BufReader<TcpStream>>;
pub type WSS = WebSocket<CLIENT, BufReader<TlsStream<TcpStream>>>;
impl WS {
pub async fn connect<A>(addr: A, path: impl AsRef<str>) -> Result<Self>
where
A: ToSocketAddrs + Display,
{
Self::connect_with_headers(addr, path, [("", ""); 0]).await
}
pub async fn connect_with_headers(
addr: impl ToSocketAddrs + Display,
path: impl AsRef<str>,
headers: impl IntoIterator<Item = impl Header>,
) -> Result<Self> {
let host = addr.to_string();
let mut ws = Self::from(BufReader::new(TcpStream::connect(addr).await?));
ws.handshake(&host, path.as_ref(), headers).await?;
Ok(ws)
}
}
impl WSS {
pub async fn connect<A>(addr: A, path: impl AsRef<str>) -> Result<Self>
where
A: ToSocketAddrs + Display,
{
Self::connect_with_headers(addr, path, [("", ""); 0]).await
}
pub async fn connect_with_headers(
addr: impl ToSocketAddrs + Display,
path: impl AsRef<str>,
headers: impl IntoIterator<Item = impl Header>,
) -> Result<Self> {
let host = addr.to_string();
let tcp_stream = TcpStream::connect(addr).await?;
let mut root_store = RootCertStore::empty();
root_store.add_server_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.iter().map(|ta| {
OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
ta.name_constraints,
)
}));
let config = ClientConfig::builder()
.with_safe_defaults()
.with_root_certificates(root_store)
.with_no_client_auth();
let domain = match host.rsplit_once(':').unwrap().0.try_into() {
Ok(server_name) => server_name,
Err(dns_name_err) => err!(dns_name_err),
};
let connector = TlsConnector::from(Arc::new(config));
let stream = BufReader::new(connector.connect(domain, tcp_stream).await?);
let mut wss = Self::from(stream);
wss.handshake(&host, path.as_ref(), headers).await?;
Ok(wss)
}
}
impl<IO: Unpin + AsyncBufRead + AsyncWrite> WebSocket<CLIENT, IO> {
async fn handshake<I, H>(&mut self, host: &str, path: &str, headers: I) -> Result<()>
where
I: IntoIterator<Item = H>,
H: Header,
{
let (request, sec_key) = handshake::request(host, path, headers);
self.stream.write_all(request.as_bytes()).await?;
let mut bytes = self.stream.fill_buf().await?;
let mut amt = bytes.len();
pub fn http_err(msg: &str) -> std::io::Error {
std::io::Error::new(std::io::ErrorKind::Other, msg)
}
let header = http::Http::parse(&mut bytes).map_err(http_err)?;
if header.schema != b"HTTP/1.1 101 Switching Protocols" {
err!("invalid http response");
}
if header
.get_sec_ws_accept()
.ok_or_else(|| http_err("couldn't get `Accept-Key` from http response"))?
!= handshake::accept_key_from(sec_key).as_bytes()
{
err!("invalid websocket accept key");
}
amt -= bytes.len();
self.stream.consume(amt);
Ok(())
}
}
impl<RW: Unpin + AsyncBufRead + AsyncWrite> WebSocket<CLIENT, RW> {
#[inline]
pub async fn recv(&mut self) -> Result<Data<RW>> {
let ty = cls_if_err!(self, self.read_data_frame_header().await)?;
Ok(client::Data { ty, ws: self })
}
}
pub struct Data<'a, Stream> {
pub ty: DataType,
pub(crate) ws: &'a mut WebSocket<CLIENT, Stream>,
}
impl<RW: Unpin + AsyncBufRead + AsyncWrite> Data<'_, RW> {
#[inline]
async fn _read_next_frag(&mut self) -> Result<()> {
self.ws.read_fragmented_header().await
}
#[inline]
async fn _read(&mut self, buf: &mut [u8]) -> Result<usize> {
let mut len = buf.len().min(self.ws.len);
if len > 0 {
len = read_bytes(&mut self.ws.stream, len, |bytes| unsafe {
std::ptr::copy_nonoverlapping(bytes.as_ptr(), buf.as_mut_ptr(), bytes.len());
})
.await?;
self.ws.len -= len;
}
Ok(len)
}
}
default_impl_for_data!();