-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
crypto_io.rs
455 lines (405 loc) · 12.7 KB
/
crypto_io.rs
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! IO facilities for TCP relay
use std::io::{self, BufRead, Read};
use std::mem;
use std::time::Duration;
use futures::{Async, Future, Poll};
use tokio_core::reactor::Timeout;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::io::{Copy, copy};
use bytes::{BufMut, BytesMut};
use super::BUFFER_SIZE;
use super::utils::{CopyTimeout, CopyTimeoutOpt, copy_timeout, copy_timeout_opt};
use relay::Context;
static DUMMY_BUFFER: [u8; BUFFER_SIZE] = [0u8; BUFFER_SIZE];
/// Reader to read data from ShadowSocks protocol
///
/// This trait requires `BufRead`, because obviously this reader has to contain a buffer inside,
/// which stores the decrypted data.
pub trait DecryptedRead: BufRead + AsyncRead {
/// Decrypt buffer size
fn buffer_size(&self, data: &[u8]) -> usize;
/// Copies all data to `w`
fn copy<W>(self, w: W) -> Copy<Self, W>
where
Self: Sized,
W: AsyncWrite,
{
copy(self, w)
}
/// Copies all data to `w`, return `TimedOut` if timeout reaches
fn copy_timeout<W>(self, w: W, timeout: Duration) -> CopyTimeout<Self, W>
where
Self: Sized,
W: AsyncWrite,
{
copy_timeout(self, w, timeout)
}
/// The same as `copy_timeout`, but has optional `timeout`
fn copy_timeout_opt<W>(self, w: W, timeout: Option<Duration>) -> CopyTimeoutOpt<Self, W>
where
Self: Sized,
W: AsyncWrite,
{
copy_timeout_opt(self, w, timeout)
}
}
/// Writer that encrypt data and write it as ShadowSocks protocol
///
/// The writer cannot implement `io::Write`, because you cannot ensure that you can write all the data in a batch
/// in non-blocking I/O environment.
pub trait EncryptedWrite {
/// Writes raw bytes directly to the writer
fn write_raw(&mut self, data: &[u8]) -> io::Result<usize>;
/// Flush the writer
fn flush(&mut self) -> io::Result<()>;
/// Encrypt data into buffer for writing
fn encrypt<B: BufMut>(&mut self, data: &[u8], buf: &mut B) -> io::Result<()>;
/// Encrypt buffer size
fn buffer_size(&self, data: &[u8]) -> usize;
/// Encrypt data in `buf` and write all to the writer
fn write_all<B: AsRef<[u8]>>(self, buf: B) -> EncryptedWriteAll<Self, B>
where
Self: Sized,
{
EncryptedWriteAll::new(self, buf)
}
/// Copies all data from `r`
fn copy<R: Read>(self, r: R) -> EncryptedCopy<R, Self>
where
Self: Sized,
{
EncryptedCopy::new(r, self)
}
/// Copies all data from `r` with timeout
fn copy_timeout<R: Read>(self, r: R, timeout: Duration) -> EncryptedCopyTimeout<R, Self>
where
Self: Sized,
{
EncryptedCopyTimeout::new(r, self, timeout)
}
/// Copies all data from `r` with optional timeout
fn copy_timeout_opt<R: Read>(self, r: R, timeout: Option<Duration>) -> EncryptedCopyOpt<R, Self>
where
Self: Sized,
{
match timeout {
Some(t) => EncryptedCopyOpt::CopyTimeout(self.copy_timeout(r, t)),
None => EncryptedCopyOpt::Copy(self.copy(r)),
}
}
}
/// Write all data encrypted
pub enum EncryptedWriteAll<W, B>
where
W: EncryptedWrite,
B: AsRef<[u8]>,
{
Writing {
writer: W,
buf: B,
pos: usize,
enc_buf: BytesMut,
encrypted: bool,
},
Empty,
}
impl<W, B> EncryptedWriteAll<W, B>
where
W: EncryptedWrite,
B: AsRef<[u8]>,
{
fn new(w: W, buf: B) -> EncryptedWriteAll<W, B> {
let buffer_size = w.buffer_size(&DUMMY_BUFFER);
EncryptedWriteAll::Writing {
writer: w,
buf: buf,
pos: 0,
enc_buf: BytesMut::with_capacity(buffer_size),
encrypted: false,
}
}
}
impl<W, B> Future for EncryptedWriteAll<W, B>
where
W: EncryptedWrite,
B: AsRef<[u8]>,
{
type Item = (W, B);
type Error = io::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match *self {
EncryptedWriteAll::Empty => panic!("poll after EncryptedWriteAll finished"),
EncryptedWriteAll::Writing {
ref mut writer,
ref buf,
ref mut pos,
ref mut enc_buf,
ref mut encrypted,
} => {
if !*encrypted {
*encrypted = true;
// Ensure buffer has enough space
let buffer_len = writer.buffer_size(buf.as_ref());
enc_buf.reserve(buffer_len);
writer.encrypt(buf.as_ref(), enc_buf)?;
}
while *pos < enc_buf.len() {
let n = try_nb!(writer.write_raw(&enc_buf[*pos..]));
*pos += n;
if n == 0 {
let err = io::Error::new(io::ErrorKind::Other, "zero-length write");
return Err(err);
}
}
}
}
match mem::replace(self, EncryptedWriteAll::Empty) {
EncryptedWriteAll::Writing { writer, buf, .. } => Ok((writer, buf).into()),
EncryptedWriteAll::Empty => unreachable!(),
}
}
}
/// Encrypted copy
pub struct EncryptedCopy<R, W>
where
R: Read,
W: EncryptedWrite,
{
reader: Option<R>,
writer: Option<W>,
read_done: bool,
amt: u64,
pos: usize,
cap: usize,
buf: BytesMut,
}
impl<R, W> EncryptedCopy<R, W>
where
R: Read,
W: EncryptedWrite,
{
fn new(r: R, w: W) -> EncryptedCopy<R, W> {
let buffer_size = w.buffer_size(&DUMMY_BUFFER);
EncryptedCopy {
reader: Some(r),
writer: Some(w),
read_done: false,
amt: 0,
pos: 0,
cap: 0,
buf: BytesMut::with_capacity(buffer_size),
}
}
}
impl<R, W> Future for EncryptedCopy<R, W>
where
R: Read,
W: EncryptedWrite,
{
type Item = (u64, R, W);
type Error = io::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let mut local_buf = [0u8; BUFFER_SIZE];
loop {
// If our buffer is empty, then we need to read some data to
// continue.
if self.pos == self.cap && !self.read_done {
let n = try_nb!(self.reader.as_mut().unwrap().read(&mut local_buf[..]));
self.buf.clear();
if n == 0 {
self.read_done = true;
} else {
let data = &local_buf[..n];
// Ensure we have enough space
let buffer_len = self.writer.as_mut().unwrap().buffer_size(data);
self.buf.reserve(buffer_len);
self.writer.as_mut().unwrap().encrypt(data, &mut self.buf)?;
}
self.pos = 0;
self.cap = self.buf.len();
}
// If our buffer has some data, let's write it out!
while self.pos < self.cap {
let i = try_nb!(self.writer
.as_mut()
.unwrap()
.write_raw(&self.buf[self.pos..self.cap]));
self.pos += i;
self.amt += i as u64;
}
// If we've written al the data and we've seen EOF, flush out the
// data and finish the transfer.
// done with the entire transfer.
if self.pos == self.cap && self.read_done {
try_nb!(self.writer.as_mut().unwrap().flush());
return Ok((self.amt, self.reader.take().unwrap(), self.writer.take().unwrap()).into());
}
}
}
}
/// Encrypted copy
pub struct EncryptedCopyTimeout<R, W>
where
R: Read,
W: EncryptedWrite,
{
reader: Option<R>,
writer: Option<W>,
read_done: bool,
amt: u64,
pos: usize,
cap: usize,
timeout: Duration,
timer: Option<Timeout>,
read_buf: [u8; BUFFER_SIZE],
write_buf: BytesMut,
}
impl<R, W> EncryptedCopyTimeout<R, W>
where
R: Read,
W: EncryptedWrite,
{
fn new(r: R, w: W, dur: Duration) -> EncryptedCopyTimeout<R, W> {
let buffer_size = w.buffer_size(&DUMMY_BUFFER);
EncryptedCopyTimeout {
reader: Some(r),
writer: Some(w),
read_done: false,
amt: 0,
pos: 0,
cap: 0,
timeout: dur,
timer: None,
read_buf: [0u8; BUFFER_SIZE],
write_buf: BytesMut::with_capacity(buffer_size),
}
}
fn try_poll_timeout(&mut self) -> io::Result<()> {
match self.timer.as_mut() {
None => Ok(()),
Some(t) => {
match t.poll() {
Err(err) => Err(err),
Ok(Async::Ready(..)) => Err(io::Error::new(io::ErrorKind::TimedOut, "connection timed out")),
Ok(Async::NotReady) => Ok(()),
}
}
}
}
fn clear_timer(&mut self) {
let _ = self.timer.take();
}
fn read_or_set_timeout(&mut self) -> io::Result<usize> {
// First, return if timeout
self.try_poll_timeout()?;
// Then, unset the previous timeout
self.clear_timer();
self.write_buf.clear();
match self.reader.as_mut().unwrap().read(&mut self.read_buf) {
Ok(0) => {
self.cap = 0;
self.pos = 0;
Ok(0)
}
Ok(n) => {
let data = &self.read_buf[..n];
// Ensoure we have enough space
let buffer_len = self.writer.as_mut().unwrap().buffer_size(data);
self.write_buf.reserve(buffer_len);
self.writer
.as_mut()
.unwrap()
.encrypt(data, &mut self.write_buf)?;
self.cap = self.write_buf.len();
self.pos = 0;
Ok(n)
}
Err(e) => {
if e.kind() == io::ErrorKind::WouldBlock {
Context::with(|ctx| self.timer = Some(Timeout::new(self.timeout, ctx.handle()).unwrap()));
}
Err(e)
}
}
}
fn write_or_set_timeout(&mut self) -> io::Result<usize> {
// First, return if timeout
self.try_poll_timeout()?;
// Then, unset the previous timeout
self.clear_timer();
match self.writer
.as_mut()
.unwrap()
.write_raw(&self.write_buf[self.pos..self.cap]) {
Ok(n) => {
self.pos += n;
Ok(n)
}
Err(e) => {
if e.kind() == io::ErrorKind::WouldBlock {
self.timer = Context::with(|ctx| Some(Timeout::new(self.timeout, ctx.handle()).unwrap()));
}
Err(e)
}
}
}
}
impl<R, W> Future for EncryptedCopyTimeout<R, W>
where
R: Read,
W: EncryptedWrite,
{
type Item = (u64, R, W);
type Error = io::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
loop {
// If our buffer is empty, then we need to read some data to
// continue.
if self.pos == self.cap && !self.read_done {
let n = try_nb!(self.read_or_set_timeout());
if n == 0 {
self.read_done = true;
}
}
// If our buffer has some data, let's write it out!
while self.pos < self.cap {
let i = try_nb!(self.write_or_set_timeout());
if i == 0 {
let err = io::Error::new(io::ErrorKind::UnexpectedEof, "early eof");
return Err(err);
}
self.amt += i as u64;
}
// If we've written al the data and we've seen EOF, flush out the
// data and finish the transfer.
// done with the entire transfer.
if self.pos == self.cap && self.read_done {
try_nb!(self.writer.as_mut().unwrap().flush());
return Ok((self.amt, self.reader.take().unwrap(), self.writer.take().unwrap()).into());
}
}
}
}
/// Work for both timeout or no timeout
pub enum EncryptedCopyOpt<R, W>
where
R: Read,
W: EncryptedWrite,
{
Copy(EncryptedCopy<R, W>),
CopyTimeout(EncryptedCopyTimeout<R, W>),
}
impl<R, W> Future for EncryptedCopyOpt<R, W>
where
R: Read,
W: EncryptedWrite,
{
type Item = (u64, R, W);
type Error = io::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match *self {
EncryptedCopyOpt::Copy(ref mut c) => c.poll(),
EncryptedCopyOpt::CopyTimeout(ref mut c) => c.poll(),
}
}
}