1#![cfg_attr(docsrs, feature(doc_cfg))]
24
25pub mod error;
26pub mod framed;
27mod quicksink;
28pub mod tls;
29
30use std::{
31 io,
32 pin::Pin,
33 task::{Context, Poll},
34};
35
36use error::Error;
37use framed::{Connection, Incoming};
38use futures::{future::BoxFuture, prelude::*, ready};
39use libp2p_core::{
40 Transport,
41 connection::ConnectedPoint,
42 multiaddr::Multiaddr,
43 transport::{DialOpts, ListenerId, TransportError, TransportEvent, map::MapFuture},
44};
45use rw_stream_sink::RwStreamSink;
46
47#[deprecated = "Use `Config` instead"]
137pub type WsConfig<Transport> = Config<Transport>;
138
139#[derive(Debug)]
140pub struct Config<T: Transport>
141where
142 T: Transport,
143 T::Output: AsyncRead + AsyncWrite + Send + Unpin + 'static,
144{
145 transport: libp2p_core::transport::map::Map<framed::Config<T>, WrapperFn<T::Output>>,
146}
147
148impl<T: Transport> Config<T>
149where
150 T: Transport + Send + Unpin + 'static,
151 T::Error: Send + 'static,
152 T::Dial: Send + 'static,
153 T::ListenerUpgrade: Send + 'static,
154 T::Output: AsyncRead + AsyncWrite + Send + Unpin + 'static,
155{
156 pub fn new(transport: T) -> Self {
165 Self {
166 transport: framed::Config::new(transport).map(wrap_connection as WrapperFn<T::Output>),
167 }
168 }
169
170 pub fn max_redirects(&self) -> u8 {
172 self.transport.inner().max_redirects()
173 }
174
175 pub fn set_max_redirects(&mut self, max: u8) -> &mut Self {
177 self.transport.inner_mut().set_max_redirects(max);
178 self
179 }
180
181 pub fn max_data_size(&self) -> usize {
183 self.transport.inner().max_data_size()
184 }
185
186 pub fn set_max_data_size(&mut self, size: usize) -> &mut Self {
191 self.transport.inner_mut().set_max_data_size(size);
192 self
193 }
194
195 pub fn set_tls_config(&mut self, c: tls::Config) -> &mut Self {
197 self.transport.inner_mut().set_tls_config(c);
198 self
199 }
200}
201
202impl<T> Transport for Config<T>
203where
204 T: Transport + Send + Unpin + 'static,
205 T::Error: Send + 'static,
206 T::Dial: Send + 'static,
207 T::ListenerUpgrade: Send + 'static,
208 T::Output: AsyncRead + AsyncWrite + Unpin + Send + 'static,
209{
210 type Output = RwStreamSink<BytesConnection<T::Output>>;
211 type Error = Error<T::Error>;
212 type ListenerUpgrade = MapFuture<InnerFuture<T::Output, T::Error>, WrapperFn<T::Output>>;
213 type Dial = MapFuture<InnerFuture<T::Output, T::Error>, WrapperFn<T::Output>>;
214
215 fn listen_on(
216 &mut self,
217 id: ListenerId,
218 addr: Multiaddr,
219 ) -> Result<(), TransportError<Self::Error>> {
220 self.transport.listen_on(id, addr)
221 }
222
223 fn remove_listener(&mut self, id: ListenerId) -> bool {
224 self.transport.remove_listener(id)
225 }
226
227 fn dial(
228 &mut self,
229 addr: Multiaddr,
230 opts: DialOpts,
231 ) -> Result<Self::Dial, TransportError<Self::Error>> {
232 self.transport.dial(addr, opts)
233 }
234
235 fn poll(
236 mut self: Pin<&mut Self>,
237 cx: &mut Context<'_>,
238 ) -> Poll<TransportEvent<Self::ListenerUpgrade, Self::Error>> {
239 Pin::new(&mut self.transport).poll(cx)
240 }
241}
242
243pub type InnerFuture<T, E> = BoxFuture<'static, Result<Connection<T>, Error<E>>>;
245
246pub type WrapperFn<T> = fn(Connection<T>, ConnectedPoint) -> RwStreamSink<BytesConnection<T>>;
248
249fn wrap_connection<T>(c: Connection<T>, _: ConnectedPoint) -> RwStreamSink<BytesConnection<T>>
252where
253 T: AsyncRead + AsyncWrite + Send + Unpin + 'static,
254{
255 RwStreamSink::new(BytesConnection(c))
256}
257
258#[derive(Debug)]
260pub struct BytesConnection<T>(Connection<T>);
261
262impl<T> Stream for BytesConnection<T>
263where
264 T: AsyncRead + AsyncWrite + Send + Unpin + 'static,
265{
266 type Item = io::Result<Vec<u8>>;
267
268 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
269 loop {
270 if let Some(item) = ready!(self.0.try_poll_next_unpin(cx)?) {
271 if let Incoming::Data(payload) = item {
272 return Poll::Ready(Some(Ok(payload.into_bytes())));
273 }
274 } else {
275 return Poll::Ready(None);
276 }
277 }
278 }
279}
280
281impl<T> Sink<Vec<u8>> for BytesConnection<T>
282where
283 T: AsyncRead + AsyncWrite + Send + Unpin + 'static,
284{
285 type Error = io::Error;
286
287 fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
288 Pin::new(&mut self.0).poll_ready(cx)
289 }
290
291 fn start_send(mut self: Pin<&mut Self>, item: Vec<u8>) -> io::Result<()> {
292 Pin::new(&mut self.0).start_send(framed::OutgoingData::Binary(item))
293 }
294
295 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
296 Pin::new(&mut self.0).poll_flush(cx)
297 }
298
299 fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
300 Pin::new(&mut self.0).poll_close(cx)
301 }
302}
303
304#[cfg(test)]
307mod tests {
308 use std::time::Duration;
309
310 use futures::prelude::*;
311 use libp2p_core::{
312 Endpoint, Multiaddr, Transport,
313 multiaddr::Protocol,
314 transport::{DialOpts, ListenerId, PortUse},
315 };
316 use libp2p_identity::PeerId;
317 use libp2p_tcp as tcp;
318 use soketto::handshake;
319
320 use super::Config;
321
322 #[tokio::test]
323 async fn dialer_connects_to_listener_ipv4() {
324 let a = "/ip4/127.0.0.1/tcp/0/ws".parse().unwrap();
325 connect(a).await
326 }
327
328 #[tokio::test]
329 async fn dialer_connects_to_listener_ipv6() {
330 let a = "/ip6/::1/tcp/0/ws".parse().unwrap();
331 connect(a).await
332 }
333
334 fn new_ws_config() -> Config<tcp::tokio::Transport> {
335 Config::new(tcp::tokio::Transport::new(tcp::Config::default()))
336 }
337
338 async fn connect(listen_addr: Multiaddr) {
339 let mut ws_config = new_ws_config().boxed();
340 ws_config
341 .listen_on(ListenerId::next(), listen_addr)
342 .expect("listener");
343
344 let addr = ws_config
345 .next()
346 .await
347 .expect("no error")
348 .into_new_address()
349 .expect("listen address");
350
351 assert_eq!(Some(Protocol::Ws("/".into())), addr.iter().nth(2));
352 assert_ne!(Some(Protocol::Tcp(0)), addr.iter().nth(1));
353
354 let inbound = async move {
355 let (conn, _addr) = ws_config
356 .select_next_some()
357 .map(|ev| ev.into_incoming())
358 .await
359 .unwrap();
360 conn.await
361 };
362
363 let outbound = new_ws_config()
364 .boxed()
365 .dial(
366 addr.with(Protocol::P2p(PeerId::random())),
367 DialOpts {
368 role: Endpoint::Dialer,
369 port_use: PortUse::New,
370 },
371 )
372 .unwrap();
373
374 let (a, b) = futures::join!(inbound, outbound);
375 a.and(b).unwrap();
376 }
377
378 const LIMIT: usize = 1024 * 1024;
379
380 #[tokio::test]
381 async fn dialer_applies_max_data_size() {
382 let mut buf = [0u8; 1];
383
384 let mut conn = dial_fake_server(LIMIT + 1).await;
387 let err = tokio::time::timeout(Duration::from_secs(10), conn.read(&mut buf))
388 .await
389 .expect("oversized frame header must be rejected without waiting for its payload")
390 .expect_err("oversized frame header must be rejected");
391 let inner = err
392 .get_ref()
393 .and_then(|e| e.downcast_ref::<soketto::connection::Error>());
394 assert!(
395 matches!(
396 inner,
397 Some(soketto::connection::Error::Codec(
398 soketto::base::Error::PayloadTooLarge { .. }
399 ))
400 ),
401 "unexpected error: {err:?}"
402 );
403
404 let mut conn = dial_fake_server(LIMIT).await;
406 assert!(
407 tokio::time::timeout(Duration::from_millis(100), conn.read(&mut buf))
408 .await
409 .is_err(),
410 "frame within the limit must wait for its payload"
411 );
412 }
413
414 async fn dial_fake_server(announced_len: usize) -> impl AsyncRead + Unpin {
418 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
419 let port = listener.local_addr().unwrap().port();
420
421 tokio::spawn(async move {
422 let (stream, _) = listener.accept().await.unwrap();
423 let mut server = handshake::Server::new(tcp::tokio::TcpStream(stream));
424 let key = server.receive_request().await.unwrap().key();
425 server
426 .send_response(&handshake::server::Response::Accept {
427 key,
428 protocol: None,
429 })
430 .await
431 .unwrap();
432
433 let mut stream = server.into_inner();
434 let mut header = vec![0x82, 0x7f];
436 header.extend_from_slice(&(announced_len as u64).to_be_bytes());
437 stream.write_all(&header).await.unwrap();
438
439 future::pending::<()>().await;
441 });
442
443 let mut config = new_ws_config();
444 config.set_max_data_size(LIMIT);
445 config
446 .dial(
447 format!("/ip4/127.0.0.1/tcp/{port}/ws").parse().unwrap(),
448 DialOpts {
449 role: Endpoint::Dialer,
450 port_use: PortUse::New,
451 },
452 )
453 .unwrap()
454 .await
455 .unwrap()
456 }
457}