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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
use futures::channel::mpsc;
use futures::future::BoxFuture;
use futures::{prelude::*, stream::StreamExt, FutureExt, SinkExt};
use libp2prs_core::identity::{Keypair, PublicKey};
use libp2prs_core::muxing::{IReadWrite, IStreamMuxer, ReadWriteEx, StreamInfo, StreamMuxer, StreamMuxerEx};
use libp2prs_core::secure_io::SecureInfo;
use libp2prs_core::transport::{ConnectionInfo, TransportError};
use libp2prs_core::upgrade::{UpgradeInfo, Upgrader};
use libp2prs_core::{Multiaddr, PeerId};
use parking_lot::Mutex;
use std::sync::Arc;
use std::{
fmt, io,
pin::Pin,
task::{Context, Poll},
};
type YRet = Result<yamux::Stream, yamux::ConnectionError>;
#[allow(clippy::type_complexity)]
pub struct Yamux<T> {
incoming: Arc<Mutex<Option<(yamux::Connection<T>, mpsc::UnboundedSender<YRet>)>>>,
accepted: Arc<futures::lock::Mutex<mpsc::UnboundedReceiver<YRet>>>,
control: yamux::Control,
pub la: Multiaddr,
pub ra: Multiaddr,
pub local_priv_key: Keypair,
pub local_peer_id: PeerId,
pub remote_pub_key: PublicKey,
pub remote_peer_id: PeerId,
}
impl<T> Clone for Yamux<T> {
fn clone(&self) -> Self {
Yamux {
incoming: self.incoming.clone(),
accepted: self.accepted.clone(),
control: self.control.clone(),
la: self.la.clone(),
ra: self.ra.clone(),
local_priv_key: self.local_priv_key.clone(),
local_peer_id: self.local_peer_id,
remote_pub_key: self.remote_pub_key.clone(),
remote_peer_id: self.remote_peer_id,
}
}
}
impl<S> fmt::Debug for Yamux<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Yamux")
}
}
impl<T> Yamux<T>
where
T: ConnectionInfo + SecureInfo + AsyncRead + AsyncWrite + Send + Unpin + 'static,
{
fn new(io: T, mut cfg: yamux::Config, mode: yamux::Mode) -> Self {
cfg.set_read_after_close(false);
let local_priv_key = io.local_priv_key();
let remote_pub_key = io.remote_pub_key();
let local_peer_id = io.local_peer();
let remote_peer_id = io.remote_peer();
let la = io.local_multiaddr();
let ra = io.remote_multiaddr();
let conn = yamux::Connection::new(io, cfg, mode);
let (sender, accepted) = mpsc::unbounded();
let ctrl = conn.control();
Yamux {
incoming: Arc::new(Mutex::new(Some((conn, sender)))),
accepted: Arc::new(futures::lock::Mutex::new(accepted)),
control: ctrl,
la,
ra,
local_priv_key,
local_peer_id,
remote_pub_key,
remote_peer_id,
}
}
}
impl<T> SecureInfo for Yamux<T> {
fn local_peer(&self) -> PeerId {
self.local_peer_id
}
fn remote_peer(&self) -> PeerId {
self.remote_peer_id
}
fn local_priv_key(&self) -> Keypair {
self.local_priv_key.clone()
}
fn remote_pub_key(&self) -> PublicKey {
self.remote_pub_key.clone()
}
}
impl<T: Send> ConnectionInfo for Yamux<T> {
fn local_multiaddr(&self) -> Multiaddr {
self.la.clone()
}
fn remote_multiaddr(&self) -> Multiaddr {
self.ra.clone()
}
}
impl<T: AsyncRead + AsyncWrite + Send + Unpin + 'static> StreamMuxerEx for Yamux<T> {}
#[async_trait::async_trait]
impl<T: AsyncRead + AsyncWrite + Send + Unpin + 'static> StreamMuxer for Yamux<T> {
async fn open_stream(&mut self) -> Result<IReadWrite, TransportError> {
let s = self.control.open_stream().await.map_err(map_yamux_err)?;
log::trace!("a new outbound substream {:?} opened for yamux... ", s);
Ok(Box::new(Stream(s)))
}
async fn accept_stream(&mut self) -> Result<IReadWrite, TransportError> {
if let Some(s) = self.accepted.lock().await.next().await {
let stream = s.map_err(map_yamux_err)?;
log::trace!("a new inbound substream {:?} accepted for yamux...", stream);
return Ok(Box::new(Stream(stream)));
}
Err(TransportError::StreamMuxerError(Box::new(yamux::ConnectionError::Closed)))
}
async fn close(&mut self) -> Result<(), TransportError> {
self.control.close().await.map_err(map_yamux_err)
}
fn task(&mut self) -> Option<BoxFuture<'static, ()>> {
self.incoming.lock().take().map(|(mut conn, mut sender)| {
async move {
loop {
match conn.next_stream().await {
Ok(Some(s)) => {
if let Err(e) = sender.send(Ok(s)).await {
if e.is_disconnected() {
break;
}
log::warn!("{:?}", e);
}
}
Ok(None) => {
log::info!("{:?} background-task exiting...", conn);
if let Err(e) = sender.send(Err(yamux::ConnectionError::Closed)).await {
log::warn!("{:?}", e);
}
break;
}
Err(e) => {
if let Err(err) = sender.send(Err(e)).await {
log::warn!("{:?}", err);
}
break;
}
}
}
}
.boxed()
})
}
fn box_clone(&self) -> IStreamMuxer {
Box::new(Clone::clone(self))
}
}
#[pin_project::pin_project]
#[derive(Debug)]
pub struct Stream(#[pin] yamux::Stream);
#[async_trait::async_trait]
impl ReadWriteEx for Stream {
fn box_clone(&self) -> IReadWrite {
unimplemented!()
}
}
impl StreamInfo for Stream {
fn id(&self) -> usize {
self.0.id().val() as usize
}
}
impl AsyncRead for Stream {
fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<io::Result<usize>> {
match futures::ready!(self.project().0.poll_read(cx, buf)) {
Ok(n) => {
if n == 0 {
Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into()))
} else {
Poll::Ready(Ok(n))
}
}
Err(e) => Poll::Ready(Err(e)),
}
}
}
impl AsyncWrite for Stream {
fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
self.project().0.poll_write(cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.project().0.poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.project().0.poll_close(cx)
}
}
#[derive(Clone)]
pub struct Config {
inner: yamux::Config,
mode: Option<yamux::Mode>,
}
pub struct WindowUpdateMode(yamux::WindowUpdateMode);
impl WindowUpdateMode {
pub fn on_receive() -> Self {
WindowUpdateMode(yamux::WindowUpdateMode::OnReceive)
}
pub fn on_read() -> Self {
WindowUpdateMode(yamux::WindowUpdateMode::OnRead)
}
}
impl Config {
pub fn new() -> Self {
Self::default()
}
pub fn client() -> Self {
let mut cfg = Self::default();
cfg.mode = Some(yamux::Mode::Client);
cfg
}
pub fn server() -> Self {
let mut cfg = Self::default();
cfg.mode = Some(yamux::Mode::Server);
cfg
}
pub fn set_receive_window_size(&mut self, num_bytes: u32) -> &mut Self {
self.inner.set_receive_window(num_bytes);
self
}
pub fn set_max_buffer_size(&mut self, num_bytes: usize) -> &mut Self {
self.inner.set_max_buffer_size(num_bytes);
self
}
pub fn set_max_num_streams(&mut self, num_streams: usize) -> &mut Self {
self.inner.set_max_num_streams(num_streams);
self
}
pub fn set_window_update_mode(&mut self, mode: WindowUpdateMode) -> &mut Self {
self.inner.set_window_update_mode(mode.0);
self
}
}
impl Default for Config {
fn default() -> Self {
let mut inner = yamux::Config::default();
inner.set_read_after_close(false);
Config { inner, mode: None }
}
}
impl UpgradeInfo for Config {
type Info = &'static [u8];
fn protocol_info(&self) -> Vec<Self::Info> {
vec![b"/yamux/1.0.0"]
}
}
#[async_trait::async_trait]
impl<C> Upgrader<C> for Config
where
C: ConnectionInfo + SecureInfo + AsyncRead + AsyncWrite + Send + Unpin + 'static,
{
type Output = Yamux<C>;
async fn upgrade_inbound(self, socket: C, _info: <Self as UpgradeInfo>::Info) -> Result<Self::Output, TransportError> {
let mode = self.mode.unwrap_or(yamux::Mode::Server);
Ok(Yamux::new(socket, self.inner, mode))
}
async fn upgrade_outbound(self, socket: C, _info: <Self as UpgradeInfo>::Info) -> Result<Self::Output, TransportError> {
let mode = self.mode.unwrap_or(yamux::Mode::Client);
Ok(Yamux::new(socket, self.inner, mode))
}
}
fn map_yamux_err(e: yamux::ConnectionError) -> TransportError {
TransportError::StreamMuxerError(Box::new(e))
}