|
| 1 | +// Copyright 2022 Parity Technologies (UK) Ltd. |
| 2 | +// |
| 3 | +// Permission is hereby granted, free of charge, to any person obtaining a |
| 4 | +// copy of this software and associated documentation files (the "Software"), |
| 5 | +// to deal in the Software without restriction, including without limitation |
| 6 | +// the rights to use, copy, modify, merge, publish, distribute, sublicense, |
| 7 | +// and/or sell copies of the Software, and to permit persons to whom the |
| 8 | +// Software is furnished to do so, subject to the following conditions: |
| 9 | +// |
| 10 | +// The above copyright notice and this permission notice shall be included in |
| 11 | +// all copies or substantial portions of the Software. |
| 12 | +// |
| 13 | +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS |
| 14 | +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 15 | +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 16 | +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 17 | +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
| 18 | +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER |
| 19 | +// DEALINGS IN THE SOFTWARE. |
| 20 | + |
| 21 | +use futures::stream::FuturesUnordered; |
| 22 | +use futures::{ |
| 23 | + channel::{ |
| 24 | + mpsc, |
| 25 | + oneshot::{self, Sender}, |
| 26 | + }, |
| 27 | + lock::Mutex as FutMutex, |
| 28 | + StreamExt, |
| 29 | + {future::BoxFuture, ready}, |
| 30 | +}; |
| 31 | +use libp2p_core::muxing::{StreamMuxer, StreamMuxerEvent}; |
| 32 | +use webrtc::data::data_channel::DataChannel as DetachedDataChannel; |
| 33 | +use webrtc::data_channel::RTCDataChannel; |
| 34 | +use webrtc::peer_connection::RTCPeerConnection; |
| 35 | + |
| 36 | +use std::task::Waker; |
| 37 | +use std::{ |
| 38 | + pin::Pin, |
| 39 | + sync::Arc, |
| 40 | + task::{Context, Poll}, |
| 41 | +}; |
| 42 | + |
| 43 | +use crate::tokio::{error::Error, substream, substream::Substream}; |
| 44 | + |
| 45 | +/// Maximum number of unprocessed data channels. |
| 46 | +/// See [`Connection::poll_inbound`]. |
| 47 | +const MAX_DATA_CHANNELS_IN_FLIGHT: usize = 10; |
| 48 | + |
| 49 | +/// A WebRTC connection, wrapping [`RTCPeerConnection`] and implementing [`StreamMuxer`] trait. |
| 50 | +pub struct Connection { |
| 51 | + /// [`RTCPeerConnection`] to the remote peer. |
| 52 | + /// |
| 53 | + /// Uses futures mutex because used in async code (see poll_outbound and poll_close). |
| 54 | + peer_conn: Arc<FutMutex<RTCPeerConnection>>, |
| 55 | + |
| 56 | + /// Channel onto which incoming data channels are put. |
| 57 | + incoming_data_channels_rx: mpsc::Receiver<Arc<DetachedDataChannel>>, |
| 58 | + |
| 59 | + /// Future, which, once polled, will result in an outbound substream. |
| 60 | + outbound_fut: Option<BoxFuture<'static, Result<Arc<DetachedDataChannel>, Error>>>, |
| 61 | + |
| 62 | + /// Future, which, once polled, will result in closing the entire connection. |
| 63 | + close_fut: Option<BoxFuture<'static, Result<(), Error>>>, |
| 64 | + |
| 65 | + /// A list of futures, which, once completed, signal that a [`Substream`] has been dropped. |
| 66 | + drop_listeners: FuturesUnordered<substream::DropListener>, |
| 67 | + no_drop_listeners_waker: Option<Waker>, |
| 68 | +} |
| 69 | + |
| 70 | +impl Unpin for Connection {} |
| 71 | + |
| 72 | +impl Connection { |
| 73 | + /// Creates a new connection. |
| 74 | + pub(crate) async fn new(rtc_conn: RTCPeerConnection) -> Self { |
| 75 | + let (data_channel_tx, data_channel_rx) = mpsc::channel(MAX_DATA_CHANNELS_IN_FLIGHT); |
| 76 | + |
| 77 | + Connection::register_incoming_data_channels_handler( |
| 78 | + &rtc_conn, |
| 79 | + Arc::new(FutMutex::new(data_channel_tx)), |
| 80 | + ) |
| 81 | + .await; |
| 82 | + |
| 83 | + Self { |
| 84 | + peer_conn: Arc::new(FutMutex::new(rtc_conn)), |
| 85 | + incoming_data_channels_rx: data_channel_rx, |
| 86 | + outbound_fut: None, |
| 87 | + close_fut: None, |
| 88 | + drop_listeners: FuturesUnordered::default(), |
| 89 | + no_drop_listeners_waker: None, |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + /// Registers a handler for incoming data channels. |
| 94 | + /// |
| 95 | + /// NOTE: `mpsc::Sender` is wrapped in `Arc` because cloning a raw sender would make the channel |
| 96 | + /// unbounded. "The channel’s capacity is equal to buffer + num-senders. In other words, each |
| 97 | + /// sender gets a guaranteed slot in the channel capacity..." |
| 98 | + /// See <https://docs.rs/futures/latest/futures/channel/mpsc/fn.channel.html> |
| 99 | + async fn register_incoming_data_channels_handler( |
| 100 | + rtc_conn: &RTCPeerConnection, |
| 101 | + tx: Arc<FutMutex<mpsc::Sender<Arc<DetachedDataChannel>>>>, |
| 102 | + ) { |
| 103 | + rtc_conn.on_data_channel(Box::new(move |data_channel: Arc<RTCDataChannel>| { |
| 104 | + log::debug!("Incoming data channel {}", data_channel.id()); |
| 105 | + |
| 106 | + let tx = tx.clone(); |
| 107 | + |
| 108 | + Box::pin(async move { |
| 109 | + data_channel.on_open({ |
| 110 | + let data_channel = data_channel.clone(); |
| 111 | + Box::new(move || { |
| 112 | + log::debug!("Data channel {} open", data_channel.id()); |
| 113 | + |
| 114 | + Box::pin(async move { |
| 115 | + let data_channel = data_channel.clone(); |
| 116 | + let id = data_channel.id(); |
| 117 | + match data_channel.detach().await { |
| 118 | + Ok(detached) => { |
| 119 | + let mut tx = tx.lock().await; |
| 120 | + if let Err(e) = tx.try_send(detached.clone()) { |
| 121 | + log::error!("Can't send data channel {}: {}", id, e); |
| 122 | + // We're not accepting data channels fast enough => |
| 123 | + // close this channel. |
| 124 | + // |
| 125 | + // Ideally we'd refuse to accept a data channel |
| 126 | + // during the negotiation process, but it's not |
| 127 | + // possible with the current API. |
| 128 | + if let Err(e) = detached.close().await { |
| 129 | + log::error!( |
| 130 | + "Failed to close data channel {}: {}", |
| 131 | + id, |
| 132 | + e |
| 133 | + ); |
| 134 | + } |
| 135 | + } |
| 136 | + } |
| 137 | + Err(e) => { |
| 138 | + log::error!("Can't detach data channel {}: {}", id, e); |
| 139 | + } |
| 140 | + }; |
| 141 | + }) |
| 142 | + }) |
| 143 | + }); |
| 144 | + }) |
| 145 | + })); |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +impl StreamMuxer for Connection { |
| 150 | + type Substream = Substream; |
| 151 | + type Error = Error; |
| 152 | + |
| 153 | + fn poll_inbound( |
| 154 | + mut self: Pin<&mut Self>, |
| 155 | + cx: &mut Context<'_>, |
| 156 | + ) -> Poll<Result<Self::Substream, Self::Error>> { |
| 157 | + match ready!(self.incoming_data_channels_rx.poll_next_unpin(cx)) { |
| 158 | + Some(detached) => { |
| 159 | + log::trace!("Incoming substream {}", detached.stream_identifier()); |
| 160 | + |
| 161 | + let (substream, drop_listener) = Substream::new(detached); |
| 162 | + self.drop_listeners.push(drop_listener); |
| 163 | + if let Some(waker) = self.no_drop_listeners_waker.take() { |
| 164 | + waker.wake() |
| 165 | + } |
| 166 | + |
| 167 | + Poll::Ready(Ok(substream)) |
| 168 | + } |
| 169 | + None => { |
| 170 | + debug_assert!( |
| 171 | + false, |
| 172 | + "Sender-end of channel should be owned by `RTCPeerConnection`" |
| 173 | + ); |
| 174 | + |
| 175 | + Poll::Pending // Return `Pending` without registering a waker: If the channel is closed, we don't need to be called anymore. |
| 176 | + } |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | + fn poll( |
| 181 | + mut self: Pin<&mut Self>, |
| 182 | + cx: &mut Context<'_>, |
| 183 | + ) -> Poll<Result<StreamMuxerEvent, Self::Error>> { |
| 184 | + loop { |
| 185 | + match ready!(self.drop_listeners.poll_next_unpin(cx)) { |
| 186 | + Some(Ok(())) => {} |
| 187 | + Some(Err(e)) => { |
| 188 | + log::debug!("a DropListener failed: {e}") |
| 189 | + } |
| 190 | + None => { |
| 191 | + self.no_drop_listeners_waker = Some(cx.waker().clone()); |
| 192 | + return Poll::Pending; |
| 193 | + } |
| 194 | + } |
| 195 | + } |
| 196 | + } |
| 197 | + |
| 198 | + fn poll_outbound( |
| 199 | + mut self: Pin<&mut Self>, |
| 200 | + cx: &mut Context<'_>, |
| 201 | + ) -> Poll<Result<Self::Substream, Self::Error>> { |
| 202 | + let peer_conn = self.peer_conn.clone(); |
| 203 | + let fut = self.outbound_fut.get_or_insert(Box::pin(async move { |
| 204 | + let peer_conn = peer_conn.lock().await; |
| 205 | + |
| 206 | + let data_channel = peer_conn.create_data_channel("", None).await?; |
| 207 | + |
| 208 | + // No need to hold the lock during the DTLS handshake. |
| 209 | + drop(peer_conn); |
| 210 | + |
| 211 | + log::trace!("Opening data channel {}", data_channel.id()); |
| 212 | + |
| 213 | + let (tx, rx) = oneshot::channel::<Arc<DetachedDataChannel>>(); |
| 214 | + |
| 215 | + // Wait until the data channel is opened and detach it. |
| 216 | + register_data_channel_open_handler(data_channel, tx).await; |
| 217 | + |
| 218 | + // Wait until data channel is opened and ready to use |
| 219 | + match rx.await { |
| 220 | + Ok(detached) => Ok(detached), |
| 221 | + Err(e) => Err(Error::Internal(e.to_string())), |
| 222 | + } |
| 223 | + })); |
| 224 | + |
| 225 | + match ready!(fut.as_mut().poll(cx)) { |
| 226 | + Ok(detached) => { |
| 227 | + self.outbound_fut = None; |
| 228 | + |
| 229 | + log::trace!("Outbound substream {}", detached.stream_identifier()); |
| 230 | + |
| 231 | + let (substream, drop_listener) = Substream::new(detached); |
| 232 | + self.drop_listeners.push(drop_listener); |
| 233 | + if let Some(waker) = self.no_drop_listeners_waker.take() { |
| 234 | + waker.wake() |
| 235 | + } |
| 236 | + |
| 237 | + Poll::Ready(Ok(substream)) |
| 238 | + } |
| 239 | + Err(e) => { |
| 240 | + self.outbound_fut = None; |
| 241 | + Poll::Ready(Err(e)) |
| 242 | + } |
| 243 | + } |
| 244 | + } |
| 245 | + |
| 246 | + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { |
| 247 | + log::debug!("Closing connection"); |
| 248 | + |
| 249 | + let peer_conn = self.peer_conn.clone(); |
| 250 | + let fut = self.close_fut.get_or_insert(Box::pin(async move { |
| 251 | + let peer_conn = peer_conn.lock().await; |
| 252 | + peer_conn.close().await?; |
| 253 | + |
| 254 | + Ok(()) |
| 255 | + })); |
| 256 | + |
| 257 | + match ready!(fut.as_mut().poll(cx)) { |
| 258 | + Ok(()) => { |
| 259 | + self.incoming_data_channels_rx.close(); |
| 260 | + self.close_fut = None; |
| 261 | + Poll::Ready(Ok(())) |
| 262 | + } |
| 263 | + Err(e) => { |
| 264 | + self.close_fut = None; |
| 265 | + Poll::Ready(Err(e)) |
| 266 | + } |
| 267 | + } |
| 268 | + } |
| 269 | +} |
| 270 | + |
| 271 | +pub(crate) async fn register_data_channel_open_handler( |
| 272 | + data_channel: Arc<RTCDataChannel>, |
| 273 | + data_channel_tx: Sender<Arc<DetachedDataChannel>>, |
| 274 | +) { |
| 275 | + data_channel.on_open({ |
| 276 | + let data_channel = data_channel.clone(); |
| 277 | + Box::new(move || { |
| 278 | + log::debug!("Data channel {} open", data_channel.id()); |
| 279 | + |
| 280 | + Box::pin(async move { |
| 281 | + let data_channel = data_channel.clone(); |
| 282 | + let id = data_channel.id(); |
| 283 | + match data_channel.detach().await { |
| 284 | + Ok(detached) => { |
| 285 | + if let Err(e) = data_channel_tx.send(detached.clone()) { |
| 286 | + log::error!("Can't send data channel {}: {:?}", id, e); |
| 287 | + if let Err(e) = detached.close().await { |
| 288 | + log::error!("Failed to close data channel {}: {}", id, e); |
| 289 | + } |
| 290 | + } |
| 291 | + } |
| 292 | + Err(e) => { |
| 293 | + log::error!("Can't detach data channel {}: {}", id, e); |
| 294 | + } |
| 295 | + }; |
| 296 | + }) |
| 297 | + }) |
| 298 | + }); |
| 299 | +} |
0 commit comments