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
use futures::future::Future;
use futures::future::FutureExt;
use futures::io::{AsyncBufRead, BufReader};
use futures::io::{AsyncRead, AsyncWrite};
use futures::ready;
use futures_timer::Delay;
use std::convert::TryInto;
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
pub struct CopyFuture<S, D> {
src: BufReader<S>,
dst: BufReader<D>,
max_circuit_duration: Delay,
max_circuit_bytes: u64,
bytes_sent: u64,
}
impl<S: AsyncRead, D: AsyncRead> CopyFuture<S, D> {
pub fn new(src: S, dst: D, max_circuit_duration: Duration, max_circuit_bytes: u64) -> Self {
CopyFuture {
src: BufReader::new(src),
dst: BufReader::new(dst),
max_circuit_duration: Delay::new(max_circuit_duration),
max_circuit_bytes,
bytes_sent: Default::default(),
}
}
}
impl<S, D> Future for CopyFuture<S, D>
where
S: AsyncRead + AsyncWrite + Unpin,
D: AsyncRead + AsyncWrite + Unpin,
{
type Output = io::Result<()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
loop {
if this.bytes_sent > this.max_circuit_bytes {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::Other,
"Max circuit bytes reached.",
)));
}
enum Status {
Pending,
Done,
Progressed,
}
let src_status = match forward_data(&mut this.src, &mut this.dst, cx) {
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Ready(Ok(0)) => Status::Done,
Poll::Ready(Ok(i)) => {
this.bytes_sent += i;
Status::Progressed
}
Poll::Pending => Status::Pending,
};
let dst_status = match forward_data(&mut this.dst, &mut this.src, cx) {
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Ready(Ok(0)) => Status::Done,
Poll::Ready(Ok(i)) => {
this.bytes_sent += i;
Status::Progressed
}
Poll::Pending => Status::Pending,
};
match (src_status, dst_status) {
(Status::Done, Status::Done) => return Poll::Ready(Ok(())),
(Status::Progressed, _) | (_, Status::Progressed) => {}
(Status::Pending, Status::Pending) => break,
(Status::Pending, Status::Done) | (Status::Done, Status::Pending) => break,
}
}
if let Poll::Ready(()) = this.max_circuit_duration.poll_unpin(cx) {
return Poll::Ready(Err(io::ErrorKind::TimedOut.into()));
}
Poll::Pending
}
}
fn forward_data<S: AsyncBufRead + Unpin, D: AsyncWrite + Unpin>(
mut src: &mut S,
mut dst: &mut D,
cx: &mut Context<'_>,
) -> Poll<io::Result<u64>> {
let buffer = ready!(Pin::new(&mut src).poll_fill_buf(cx))?;
if buffer.is_empty() {
ready!(Pin::new(&mut dst).poll_flush(cx))?;
ready!(Pin::new(&mut dst).poll_close(cx))?;
return Poll::Ready(Ok(0));
}
let i = ready!(Pin::new(dst).poll_write(cx, buffer))?;
if i == 0 {
return Poll::Ready(Err(io::ErrorKind::WriteZero.into()));
}
Pin::new(src).consume(i);
Poll::Ready(Ok(i.try_into().expect("usize to fit into u64.")))
}
#[cfg(test)]
mod tests {
use super::CopyFuture;
use futures::executor::block_on;
use futures::io::{AsyncRead, AsyncWrite};
use quickcheck::QuickCheck;
use std::io::ErrorKind;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
struct Connection {
read: Vec<u8>,
write: Vec<u8>,
}
impl AsyncWrite for Connection {
fn poll_write(
mut self: std::pin::Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut self.write).poll_write(cx, buf)
}
fn poll_flush(
mut self: std::pin::Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.write).poll_flush(cx)
}
fn poll_close(
mut self: std::pin::Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.write).poll_close(cx)
}
}
impl AsyncRead for Connection {
fn poll_read(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
let n = std::cmp::min(self.read.len(), buf.len());
buf[0..n].copy_from_slice(&self.read[0..n]);
self.read = self.read.split_off(n);
return Poll::Ready(Ok(n));
}
}
struct PendingConnection {}
impl AsyncWrite for PendingConnection {
fn poll_write(
self: std::pin::Pin<&mut Self>,
_cx: &mut Context<'_>,
_buf: &[u8],
) -> Poll<std::io::Result<usize>> {
Poll::Pending
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<std::io::Result<()>> {
Poll::Pending
}
fn poll_close(
self: std::pin::Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<std::io::Result<()>> {
Poll::Pending
}
}
impl AsyncRead for PendingConnection {
fn poll_read(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
_buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
Poll::Pending
}
}
#[test]
fn quickcheck() {
fn prop(a: Vec<u8>, b: Vec<u8>, max_circuit_bytes: u64) {
let connection_a = Connection {
read: a.clone(),
write: Vec::new(),
};
let connection_b = Connection {
read: b.clone(),
write: Vec::new(),
};
let mut copy_future = CopyFuture::new(
connection_a,
connection_b,
Duration::from_secs(60),
max_circuit_bytes,
);
match block_on(&mut copy_future) {
Ok(()) => {
assert_eq!(copy_future.src.into_inner().write, b);
assert_eq!(copy_future.dst.into_inner().write, a);
}
Err(error) => {
assert_eq!(error.kind(), ErrorKind::Other);
assert_eq!(error.to_string(), "Max circuit bytes reached.");
assert!(a.len() + b.len() > max_circuit_bytes as usize);
}
}
}
QuickCheck::new().quickcheck(prop as fn(_, _, _))
}
#[test]
fn max_circuit_duration() {
let copy_future = CopyFuture::new(
PendingConnection {},
PendingConnection {},
Duration::from_millis(1),
u64::MAX,
);
std::thread::sleep(Duration::from_millis(2));
let error =
block_on(copy_future).expect_err("Expect maximum circuit duration to be reached.");
assert_eq!(error.kind(), ErrorKind::TimedOut);
}
}