1#![deny(missing_docs, unused_must_use, unused_mut, unused_imports, unused_import_braces)]
12
13pub use tungstenite;
14
15mod compat;
16#[cfg(feature = "connect")]
17mod connect;
18mod handshake;
19#[cfg(feature = "stream")]
20mod stream;
21#[cfg(any(feature = "native-tls", feature = "__rustls-tls", feature = "connect"))]
22mod tls;
23
24use std::io::{Read, Write};
25
26use compat::{cvt, AllowStd, ContextWaker};
27use futures_util::{
28 sink::{Sink, SinkExt},
29 stream::{FusedStream, Stream},
30};
31use log::*;
32use std::{
33 pin::Pin,
34 task::{Context, Poll},
35};
36use tokio::io::{AsyncRead, AsyncWrite};
37
38#[cfg(feature = "handshake")]
39use tungstenite::{
40 client::IntoClientRequest,
41 handshake::{
42 client::{ClientHandshake, Response},
43 server::{Callback, NoCallback},
44 HandshakeError,
45 },
46};
47use tungstenite::{
48 error::Error as WsError,
49 protocol::{Message, Role, WebSocket, WebSocketConfig},
50};
51
52#[cfg(any(feature = "native-tls", feature = "__rustls-tls", feature = "connect"))]
53pub use tls::Connector;
54#[cfg(any(feature = "native-tls", feature = "__rustls-tls"))]
55pub use tls::{client_async_tls, client_async_tls_with_config};
56
57#[cfg(feature = "connect")]
58pub use connect::{connect_async, connect_async_with_config};
59
60#[cfg(all(any(feature = "native-tls", feature = "__rustls-tls"), feature = "connect"))]
61pub use connect::connect_async_tls_with_config;
62
63#[cfg(feature = "stream")]
64pub use stream::MaybeTlsStream;
65
66use tungstenite::protocol::CloseFrame;
67
68#[cfg(feature = "handshake")]
81pub async fn client_async<'a, R, S>(
82 request: R,
83 stream: S,
84) -> Result<(WebSocketStream<S>, Response), WsError>
85where
86 R: IntoClientRequest + Unpin,
87 S: AsyncRead + AsyncWrite + Unpin,
88{
89 client_async_with_config(request, stream, None).await
90}
91
92#[cfg(feature = "handshake")]
95pub async fn client_async_with_config<'a, R, S>(
96 request: R,
97 stream: S,
98 config: Option<WebSocketConfig>,
99) -> Result<(WebSocketStream<S>, Response), WsError>
100where
101 R: IntoClientRequest + Unpin,
102 S: AsyncRead + AsyncWrite + Unpin,
103{
104 let f = handshake::client_handshake(stream, move |allow_std| {
105 let request = request.into_client_request()?;
106 let cli_handshake = ClientHandshake::start(allow_std, request, config)?;
107 cli_handshake.handshake()
108 });
109 f.await.map_err(|e| match e {
110 HandshakeError::Failure(e) => e,
111 e => WsError::Io(std::io::Error::new(std::io::ErrorKind::Other, e.to_string())),
112 })
113}
114
115#[cfg(feature = "handshake")]
127pub async fn accept_async<S>(stream: S) -> Result<WebSocketStream<S>, WsError>
128where
129 S: AsyncRead + AsyncWrite + Unpin,
130{
131 accept_hdr_async(stream, NoCallback).await
132}
133
134#[cfg(feature = "handshake")]
137pub async fn accept_async_with_config<S>(
138 stream: S,
139 config: Option<WebSocketConfig>,
140) -> Result<WebSocketStream<S>, WsError>
141where
142 S: AsyncRead + AsyncWrite + Unpin,
143{
144 accept_hdr_async_with_config(stream, NoCallback, config).await
145}
146
147#[cfg(feature = "handshake")]
153pub async fn accept_hdr_async<S, C>(stream: S, callback: C) -> Result<WebSocketStream<S>, WsError>
154where
155 S: AsyncRead + AsyncWrite + Unpin,
156 C: Callback + Unpin,
157{
158 accept_hdr_async_with_config(stream, callback, None).await
159}
160
161#[cfg(feature = "handshake")]
164pub async fn accept_hdr_async_with_config<S, C>(
165 stream: S,
166 callback: C,
167 config: Option<WebSocketConfig>,
168) -> Result<WebSocketStream<S>, WsError>
169where
170 S: AsyncRead + AsyncWrite + Unpin,
171 C: Callback + Unpin,
172{
173 let f = handshake::server_handshake(stream, move |allow_std| {
174 tungstenite::accept_hdr_with_config(allow_std, callback, config)
175 });
176 f.await.map_err(|e| match e {
177 HandshakeError::Failure(e) => e,
178 e => WsError::Io(std::io::Error::new(std::io::ErrorKind::Other, e.to_string())),
179 })
180}
181
182#[derive(Debug)]
204pub struct WebSocketStream<S> {
205 inner: WebSocket<AllowStd<S>>,
206 closing: bool,
207 ended: bool,
208 ready: bool,
213}
214
215impl<S> WebSocketStream<S> {
216 pub async fn from_raw_socket(stream: S, role: Role, config: Option<WebSocketConfig>) -> Self
219 where
220 S: AsyncRead + AsyncWrite + Unpin,
221 {
222 handshake::without_handshake(stream, move |allow_std| {
223 WebSocket::from_raw_socket(allow_std, role, config)
224 })
225 .await
226 }
227
228 pub async fn from_partially_read(
231 stream: S,
232 part: Vec<u8>,
233 role: Role,
234 config: Option<WebSocketConfig>,
235 ) -> Self
236 where
237 S: AsyncRead + AsyncWrite + Unpin,
238 {
239 handshake::without_handshake(stream, move |allow_std| {
240 WebSocket::from_partially_read(allow_std, part, role, config)
241 })
242 .await
243 }
244
245 pub(crate) fn new(ws: WebSocket<AllowStd<S>>) -> Self {
246 Self { inner: ws, closing: false, ended: false, ready: true }
247 }
248
249 fn with_context<F, R>(&mut self, ctx: Option<(ContextWaker, &mut Context<'_>)>, f: F) -> R
250 where
251 S: Unpin,
252 F: FnOnce(&mut WebSocket<AllowStd<S>>) -> R,
253 AllowStd<S>: Read + Write,
254 {
255 trace!("{}:{} WebSocketStream.with_context", file!(), line!());
256 if let Some((kind, ctx)) = ctx {
257 self.inner.get_mut().set_waker(kind, ctx.waker());
258 }
259 f(&mut self.inner)
260 }
261
262 pub fn into_inner(self) -> S {
264 self.inner.into_inner().into_inner()
265 }
266
267 pub fn get_ref(&self) -> &S
269 where
270 S: AsyncRead + AsyncWrite + Unpin,
271 {
272 self.inner.get_ref().get_ref()
273 }
274
275 pub fn get_mut(&mut self) -> &mut S
277 where
278 S: AsyncRead + AsyncWrite + Unpin,
279 {
280 self.inner.get_mut().get_mut()
281 }
282
283 pub fn get_config(&self) -> &WebSocketConfig {
285 self.inner.get_config()
286 }
287
288 pub async fn close(&mut self, msg: Option<CloseFrame>) -> Result<(), WsError>
290 where
291 S: AsyncRead + AsyncWrite + Unpin,
292 {
293 self.send(Message::Close(msg)).await
294 }
295}
296
297impl<T> Stream for WebSocketStream<T>
298where
299 T: AsyncRead + AsyncWrite + Unpin,
300{
301 type Item = Result<Message, WsError>;
302
303 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
304 trace!("{}:{} Stream.poll_next", file!(), line!());
305
306 if self.ended {
310 return Poll::Ready(None);
311 }
312
313 match futures_util::ready!(self.with_context(Some((ContextWaker::Read, cx)), |s| {
314 trace!("{}:{} Stream.with_context poll_next -> read()", file!(), line!());
315 cvt(s.read())
316 })) {
317 Ok(v) => Poll::Ready(Some(Ok(v))),
318 Err(e) => {
319 self.ended = true;
320 if matches!(e, WsError::AlreadyClosed | WsError::ConnectionClosed) {
321 Poll::Ready(None)
322 } else {
323 Poll::Ready(Some(Err(e)))
324 }
325 }
326 }
327 }
328}
329
330impl<T> FusedStream for WebSocketStream<T>
331where
332 T: AsyncRead + AsyncWrite + Unpin,
333{
334 fn is_terminated(&self) -> bool {
335 self.ended
336 }
337}
338
339impl<T> Sink<Message> for WebSocketStream<T>
340where
341 T: AsyncRead + AsyncWrite + Unpin,
342{
343 type Error = WsError;
344
345 fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
346 if self.ready {
347 Poll::Ready(Ok(()))
348 } else {
349 (*self).with_context(Some((ContextWaker::Write, cx)), |s| cvt(s.flush())).map(|r| {
351 self.ready = true;
352 r
353 })
354 }
355 }
356
357 fn start_send(mut self: Pin<&mut Self>, item: Message) -> Result<(), Self::Error> {
358 match (*self).with_context(None, |s| s.write(item)) {
359 Ok(()) => {
360 self.ready = true;
361 Ok(())
362 }
363 Err(WsError::Io(err)) if err.kind() == std::io::ErrorKind::WouldBlock => {
364 self.ready = false;
367 Ok(())
368 }
369 Err(e) => {
370 self.ready = true;
371 debug!("websocket start_send error: {}", e);
372 Err(e)
373 }
374 }
375 }
376
377 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
378 (*self).with_context(Some((ContextWaker::Write, cx)), |s| cvt(s.flush())).map(|r| {
379 self.ready = true;
380 match r {
381 Err(WsError::ConnectionClosed) => Ok(()),
383 other => other,
384 }
385 })
386 }
387
388 fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
389 self.ready = true;
390 let res = if self.closing {
391 (*self).with_context(Some((ContextWaker::Write, cx)), |s| s.flush())
393 } else {
394 (*self).with_context(Some((ContextWaker::Write, cx)), |s| s.close(None))
395 };
396
397 match res {
398 Ok(()) => Poll::Ready(Ok(())),
399 Err(WsError::ConnectionClosed) => Poll::Ready(Ok(())),
400 Err(WsError::Io(err)) if err.kind() == std::io::ErrorKind::WouldBlock => {
401 trace!("WouldBlock");
402 self.closing = true;
403 Poll::Pending
404 }
405 Err(err) => {
406 debug!("websocket close error: {}", err);
407 Poll::Ready(Err(err))
408 }
409 }
410 }
411}
412
413#[cfg(any(feature = "connect", feature = "native-tls", feature = "__rustls-tls"))]
415#[inline]
416fn domain(request: &tungstenite::handshake::client::Request) -> Result<String, WsError> {
417 match request.uri().host() {
418 #[cfg(feature = "__rustls-tls")]
420 Some(d) if d.starts_with('[') && d.ends_with(']') => Ok(d[1..d.len() - 1].to_string()),
421 Some(d) => Ok(d.to_string()),
422 None => Err(WsError::Url(tungstenite::error::UrlError::NoHostName)),
423 }
424}
425
426#[cfg(test)]
427mod tests {
428 #[cfg(feature = "connect")]
429 use crate::stream::MaybeTlsStream;
430 use crate::{compat::AllowStd, WebSocketStream};
431 use std::io::{Read, Write};
432 #[cfg(feature = "connect")]
433 use tokio::io::{AsyncReadExt, AsyncWriteExt};
434
435 fn is_read<T: Read>() {}
436 fn is_write<T: Write>() {}
437 #[cfg(feature = "connect")]
438 fn is_async_read<T: AsyncReadExt>() {}
439 #[cfg(feature = "connect")]
440 fn is_async_write<T: AsyncWriteExt>() {}
441 fn is_unpin<T: Unpin>() {}
442
443 #[test]
444 fn web_socket_stream_has_traits() {
445 is_read::<AllowStd<tokio::net::TcpStream>>();
446 is_write::<AllowStd<tokio::net::TcpStream>>();
447
448 #[cfg(feature = "connect")]
449 is_async_read::<MaybeTlsStream<tokio::net::TcpStream>>();
450 #[cfg(feature = "connect")]
451 is_async_write::<MaybeTlsStream<tokio::net::TcpStream>>();
452
453 is_unpin::<WebSocketStream<tokio::net::TcpStream>>();
454 #[cfg(feature = "connect")]
455 is_unpin::<WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>>();
456 }
457}