Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 // Copyright (c) 2019 Parity Technologies (UK) Ltd.
2 // Copyright (c) 2016 twist developers
3 //
4 // Licensed under the Apache License, Version 2.0
5 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
6 // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. All files in the project carrying such notice may not be copied,
8 // modified, or distributed except according to those terms.
9
10 //! An implementation of the [RFC 6455][rfc6455] websocket protocol.
11 //!
12 //! To begin a websocket connection one first needs to perform a [handshake],
13 //! either as [client] or [server], in order to upgrade from HTTP.
14 //! Once successful, the client or server can transition to a connection,
15 //! i.e. a [Sender]/[Receiver] pair and send and receive textual or
16 //! binary data.
17 //!
18 //! **Note**: While it is possible to only receive websocket messages it is
19 //! not possible to only send websocket messages. Receiving data is required
20 //! in order to react to control frames such as PING or CLOSE. While those will be
21 //! answered transparently they have to be received in the first place, so
22 //! calling [`connection::Receiver::receive`] is imperative.
23 //!
24 //! **Note**: None of the `async` methods are safe to cancel so their `Future`s
25 //! must not be dropped unless they return `Poll::Ready`.
26 //!
27 //! # Client example
28 //!
29 //! ```no_run
30 //! # use tokio_util::compat::TokioAsyncReadCompatExt;
31 //! # async fn doc() -> Result<(), soketto::BoxedError> {
32 //! use soketto::handshake::{Client, ServerResponse};
33 //!
34 //! // First, we need to establish a TCP connection.
35 //! let socket = tokio::net::TcpStream::connect("...").await?;
36 //!
37 //! // Then we configure the client handshake.
38 //! let mut client = Client::new(socket.compat(), "...", "/");
39 //!
40 //! // And finally we perform the handshake and handle the result.
41 //! let (mut sender, mut receiver) = match client.handshake().await? {
42 //! ServerResponse::Accepted { .. } => client.into_builder().finish(),
43 //! ServerResponse::Redirect { status_code, location } => unimplemented!("follow location URL"),
44 //! ServerResponse::Rejected { status_code } => unimplemented!("handle failure")
45 //! };
46 //!
47 //! // Over the established websocket connection we can send
48 //! sender.send_text("some text").await?;
49 //! sender.send_text("some more text").await?;
50 //! sender.flush().await?;
51 //!
52 //! // ... and receive data.
53 //! let mut data = Vec::new();
54 //! receiver.receive_data(&mut data).await?;
55 //!
56 //! # Ok(())
57 //! # }
58 //!
59 //! ```
60 //!
61 //! # Server example
62 //!
63 //! ```no_run
64 //! # use tokio_util::compat::TokioAsyncReadCompatExt;
65 //! # use tokio_stream::{wrappers::TcpListenerStream, StreamExt};
66 //! # async fn doc() -> Result<(), soketto::BoxedError> {
67 //! use soketto::{handshake::{Server, ClientRequest, server::Response}};
68 //!
69 //! // First, we listen for incoming connections.
70 //! let listener = tokio::net::TcpListener::bind("...").await?;
71 //! let mut incoming = TcpListenerStream::new(listener);
72 //!
73 //! while let Some(socket) = incoming.next().await {
74 //! // For each incoming connection we perform a handshake.
75 //! let mut server = Server::new(socket?.compat());
76 //!
77 //! let websocket_key = {
78 //! let req = server.receive_request().await?;
79 //! req.key()
80 //! };
81 //!
82 //! // Here we accept the client unconditionally.
83 //! let accept = Response::Accept { key: websocket_key, protocol: None };
84 //! server.send_response(&accept).await?;
85 //!
86 //! // And we can finally transition to a websocket connection.
87 //! let (mut sender, mut receiver) = server.into_builder().finish();
88 //!
89 //! let mut data = Vec::new();
90 //! let data_type = receiver.receive_data(&mut data).await?;
91 //!
92 //! if data_type.is_text() {
93 //! sender.send_text(std::str::from_utf8(&data)?).await?
94 //! } else {
95 //! sender.send_binary(&data).await?
96 //! }
97 //!
98 //! sender.close().await?
99 //! }
100 //!
101 //! # Ok(())
102 //! # }
103 //!
104 //! ```
105 //!
106 //! See `examples/hyper_server.rs` from this crate's repository for an example of
107 //! starting up a WebSocket server alongside an Hyper HTTP server.
108 //!
109 //! [client]: handshake::Client
110 //! [server]: handshake::Server
111 //! [Sender]: connection::Sender
112 //! [Receiver]: connection::Receiver
113 //! [rfc6455]: https://tools.ietf.org/html/rfc6455
114 //! [handshake]: https://tools.ietf.org/html/rfc6455#section-4
115
116 #![forbid(unsafe_code)]
117
118 pub mod baserust-analyzer cargo soketto 0.8.1 base/;
119 pub mod connectionrust-analyzer cargo soketto 0.8.1 connection/;
120 pub mod datarust-analyzer cargo soketto 0.8.1 data/;
121 pub mod extensionrust-analyzer cargo soketto 0.8.1 extension/;
122 pub mod handshakerust-analyzer cargo soketto 0.8.1 handshake/;
123
124 use bytesrust-analyzer cargo bytes 1.12.1 crate/::BytesMutrust-analyzer cargo bytes 1.12.1 bytes_mut/BytesMut#;
125 use futuresrust-analyzer cargo futures 0.3.34 crate/::iorust-analyzer cargo futures-util 0.3.34 io/::{AsyncReadrust-analyzer cargo futures-io 0.3.34 if_std/AsyncRead#, AsyncReadExtrust-analyzer cargo futures-util 0.3.34 io/AsyncReadExt#};
126 use stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::iorust-analyzer cargo std https://github.com/rust-lang/rust/library/std io/;
127
128 pub use connectionrust-analyzer cargo soketto 0.8.1 connection/::{Moderust-analyzer cargo soketto 0.8.1 connection/Mode#, Receiverrust-analyzer cargo soketto 0.8.1 connection/Receiver#, Senderrust-analyzer cargo soketto 0.8.1 connection/Sender#};
129 pub use datarust-analyzer cargo soketto 0.8.1 data/::{Datarust-analyzer cargo soketto 0.8.1 data/Data#, Incomingrust-analyzer cargo soketto 0.8.1 data/Incoming#};
130
131 pub type BoxedErrorrust-analyzer cargo soketto 0.8.1 BoxedError# = Boxrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc boxed/Box#<dyn stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::errorrust-analyzer cargo std https://github.com/rust-lang/rust/library/std error/::Errorrust-analyzer cargo core https://github.com/rust-lang/rust/library/core error/Error# + Sendrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Send# + Syncrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Sync#>;
132
133 /// A parsing result.
134 #[deriverust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/derive:(Debugrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/macros/Debug:, Clonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core clone/Clone:)]
135 pub enum Parsingrust-analyzer cargo soketto 0.8.1 Parsing#<T, N = ()> {
136 /// Parsing completed.
137 Donerust-analyzer cargo soketto 0.8.1 Parsing#Done# {
138 /// The parsed value.
139 valuerust-analyzer cargo soketto 0.8.1 Parsing#Done#value.: T,
140 /// The offset into the byte slice that has been consumed.
141 offsetrust-analyzer cargo soketto 0.8.1 Parsing#Done#offset.: usize,
142 },
143 /// Parsing is incomplete and needs more data.
144 NeedMorerust-analyzer cargo soketto 0.8.1 Parsing#NeedMore#(N),
145 }
146
147 /// A buffer type used for implementing `Extension`s.
148 #[deriverust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/derive:(Debugrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/macros/Debug:)]
149 pub enum Storagerust-analyzer cargo soketto 0.8.1 Storage#<'a> {
150 /// A read-only shared byte slice.
151 Sharedrust-analyzer cargo soketto 0.8.1 Storage#Shared#(&'a [u8]),
152 /// A mutable byte slice.
153 Uniquerust-analyzer cargo soketto 0.8.1 Storage#Unique#(&'a mut [u8]),
154 /// An owned byte buffer.
155 Ownedrust-analyzer cargo soketto 0.8.1 Storage#Owned#(Vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/Vec#<u8>),
156 }
157
158 impl AsRefrust-analyzer cargo core https://github.com/rust-lang/rust/library/core convert/AsRef#<[u8]> for Storagerust-analyzer cargo soketto 0.8.1 Storage#<'_> {
159 fn as_refrust-analyzer cargo soketto 0.8.1 impl#[`Storage<'_>`][`AsRef<[u8]>`]as_ref().(&self) -> &[u8] {
160 match self {
161 Storagerust-analyzer cargo soketto 0.8.1 Storage#::Sharedrust-analyzer cargo soketto 0.8.1 Storage#Shared#(d) => d,
162 Storagerust-analyzer cargo soketto 0.8.1 Storage#::Uniquerust-analyzer cargo soketto 0.8.1 Storage#Unique#(d) => d,
163 Storagerust-analyzer cargo soketto 0.8.1 Storage#::Ownedrust-analyzer cargo soketto 0.8.1 Storage#Owned#(b) => b.as_refrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`][`AsRef<[T]>`]as_ref().(),
164 }
165 }
166 }
167
168 /// Helper function to allow casts from `usize` to `u64` only on platforms
169 /// where the sizes are guaranteed to fit.
170 #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
171 const fn as_u64rust-analyzer cargo soketto 0.8.1 as_u64().(a: usize) -> u64 {
172 a as u64
173 }
174
175 /// Fill the buffer from the given `AsyncRead` impl with up to `max` bytes.
176 async fn readrust-analyzer cargo soketto 0.8.1 read().<R>(reader: &mut R, dest: &mut BytesMutrust-analyzer cargo bytes 1.12.1 bytes_mut/BytesMut#, max: usize) -> iorust-analyzer cargo std https://github.com/rust-lang/rust/library/std io/::Resultrust-analyzer cargo std https://github.com/rust-lang/rust/library/std io/error/Result#<()>
177 where
178 R: AsyncReadrust-analyzer cargo futures-io 0.3.34 if_std/AsyncRead# + Unpinrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Unpin#,
179 {
180 let i = dest.lenrust-analyzer cargo bytes 1.12.1 bytes_mut/impl#[BytesMut]len().();
181 dest.resizerust-analyzer cargo bytes 1.12.1 bytes_mut/impl#[BytesMut]resize().(i rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Add<Self>`]add().+rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Add<Self>`]add(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Add<Self>`]add().max, 0u8);
182 let n = reader.readrust-analyzer cargo futures-util 0.3.34 io/AsyncReadExt#read().(&mut dest[rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/index/IndexMut#index_mut().i..rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/range/RangeFrom#]rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/index/IndexMut#index_mut().).rust-analyzer cargo futures-util 0.3.34 io/read/impl#[`Read<'_, R>`][Future]poll().awaitrust-analyzer cargo futures-util 0.3.34 io/read/impl#[`Read<'_, R>`][Future]poll().?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().;
183 dest.truncaterust-analyzer cargo bytes 1.12.1 bytes_mut/impl#[BytesMut]truncate().(i rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Add<Self>`]add().+rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Add<Self>`]add(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Add<Self>`]add().n);
184 if n rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialEq<Self>`]eq().==rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialEq<Self>`]eq(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialEq<Self>`]eq().0 {
185 return Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(iorust-analyzer cargo std https://github.com/rust-lang/rust/library/std io/::ErrorKindrust-analyzer cargo std https://github.com/rust-lang/rust/library/std io/error/ErrorKind#::UnexpectedEofrust-analyzer cargo std https://github.com/rust-lang/rust/library/std io/error/ErrorKind#UnexpectedEof#.intorust-analyzer cargo core https://github.com/rust-lang/rust/library/core convert/impl#[T][`Into<U>`]into().());
186 }
187 logrust-analyzer cargo log 0.4.34 crate/::tracerust-analyzer cargo log 0.4.34 macros/trace!!("read {} bytes", n);
188 Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(())
189 }