diff --git a/src/relay/tcprelay/crypto_io.rs b/src/relay/tcprelay/crypto_io.rs index b02aaa17..4001bdb5 100644 --- a/src/relay/tcprelay/crypto_io.rs +++ b/src/relay/tcprelay/crypto_io.rs @@ -1,16 +1,42 @@ //! IO facilities for TCP relay -use std::io::{self, Read, BufRead}; +use std::io::{self, Read, Write, BufRead}; use std::mem; use std::time::Duration; use futures::{Future, Poll, Async}; use tokio_core::reactor::{Handle, Timeout}; +use tokio_core::io::{copy, Copy}; use super::BUFFER_SIZE; +use super::utils::{copy_timeout, copy_timeout_opt, CopyTimeout, CopyTimeoutOpt}; -pub trait DecryptedRead: BufRead {} +pub trait DecryptedRead: BufRead { + /// Copies all data to `w` + fn copy(self, w: W) -> Copy + where Self: Sized, + W: Write + { + copy(self, w) + } + + /// Copies all data to `w`, return `TimedOut` if timeout reaches + fn copy_timeout(self, w: W, timeout: Duration, handle: Handle) -> CopyTimeout + where Self: Sized, + W: Write + { + copy_timeout(self, w, timeout, handle) + } + + /// The same as `copy_timeout`, but has optional `timeout` + fn copy_timeout_opt(self, w: W, timeout: Option, handle: Handle) -> CopyTimeoutOpt + where Self: Sized, + W: Write + { + copy_timeout_opt(self, w, timeout, handle) + } +} pub trait EncryptedWrite { /// Writes raw bytes directly to the writer directly diff --git a/src/relay/tcprelay/mod.rs b/src/relay/tcprelay/mod.rs index 9616b5e9..8097260f 100644 --- a/src/relay/tcprelay/mod.rs +++ b/src/relay/tcprelay/mod.rs @@ -21,7 +21,7 @@ //! Relay for TCP implementation -use std::io::{self, Read, Write, BufRead}; +use std::io::{self, Read, BufRead}; use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6}; use std::rc::Rc; use std::mem; @@ -36,11 +36,11 @@ use config::{ServerConfig, ServerAddr}; use tokio_core::net::TcpStream; use tokio_core::reactor::{Handle, Timeout}; -use tokio_core::io::{read_exact, write_all, copy}; +use tokio_core::io::{read_exact, write_all}; use tokio_core::io::{ReadHalf, WriteHalf}; use tokio_core::io::Io; -use futures::{self, Future, Poll, Async}; +use futures::{self, Future, Poll}; use net2::TcpBuilder; @@ -58,6 +58,7 @@ mod stream; pub mod client; mod crypto_io; mod aead; +mod utils; const BUFFER_SIZE: usize = 8 * 1024; // 8K buffer @@ -413,142 +414,4 @@ fn io_timeout(fut: F, dur: Duration, handle: &Handle) -> BoxIoFuture } }); boxed_future(fut) -} - -pub struct CopyTimeout - where R: Read, - W: Write -{ - r: R, - w: W, - timeout: Duration, - handle: Handle, - amt: u64, - timer: Option, - buf: [u8; BUFFER_SIZE], - pos: usize, - cap: usize, -} - -impl CopyTimeout - where R: Read, - W: Write -{ - fn new(r: R, w: W, timeout: Duration, handle: Handle) -> CopyTimeout { - CopyTimeout { - r: r, - w: w, - timeout: timeout, - handle: handle, - amt: 0, - timer: None, - buf: [0u8; BUFFER_SIZE], - pos: 0, - cap: 0, - } - } - - 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, "timeout")), - Ok(Async::NotReady) => Ok(()), - } - } - } - } - - fn clear_timer(&mut self) { - let _ = self.timer.take(); - } - - fn read_or_set_timeout(&mut self) -> io::Result { - // First, return if timeout - try!(self.try_poll_timeout()); - - // Then, unset the previous timeout - self.clear_timer(); - - match self.r.read(&mut self.buf) { - Ok(n) => Ok(n), - Err(e) => { - if e.kind() == io::ErrorKind::WouldBlock { - self.timer = Some(Timeout::new(self.timeout, &self.handle).unwrap()); - } - Err(e) - } - } - } - - fn write_or_set_timeout(&mut self, beg: usize, end: usize) -> io::Result { - // First, return if timeout - try!(self.try_poll_timeout()); - - // Then, unset the previous timeout - self.clear_timer(); - - match self.w.write(&self.buf[beg..end]) { - Ok(n) => Ok(n), - Err(e) => { - if e.kind() == io::ErrorKind::WouldBlock { - self.timer = Some(Timeout::new(self.timeout, &self.handle).unwrap()); - } - Err(e) - } - } - } -} - -impl Future for CopyTimeout - where R: Read, - W: Write -{ - type Item = u64; - type Error = io::Error; - - fn poll(&mut self) -> Poll { - loop { - if self.pos == self.cap { - let n = try_nb!(self.read_or_set_timeout()); - - if n == 0 { - // 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. - try_nb!(self.w.flush()); - return Ok(self.amt.into()); - } - - self.pos = 0; - self.cap = n; - - // Clear it before write - self.clear_timer(); - } - - // If our buffer has some data, let's write it out! - while self.pos < self.cap { - let (pos, cap) = (self.pos, self.cap); - let i = try_nb!(self.write_or_set_timeout(pos, cap)); - self.pos += i; - self.amt += i as u64; - } - - // Clear it before read - self.clear_timer(); - } - } -} - -fn copy_timeout(r: R, w: W, timeout: Option, handle: Handle) -> BoxIoFuture - where R: Read + 'static, - W: Write + 'static -{ - match timeout { - None => boxed_future(copy(r, w)), - Some(timeout) => boxed_future(CopyTimeout::new(r, w, timeout, handle)), - } } \ No newline at end of file diff --git a/src/relay/tcprelay/server.rs b/src/relay/tcprelay/server.rs index e94fbfc0..a60d2f5f 100644 --- a/src/relay/tcprelay/server.rs +++ b/src/relay/tcprelay/server.rs @@ -32,7 +32,7 @@ use config::{Config, ServerConfig}; use relay::socks5::Address; use relay::{BoxIoFuture, boxed_future}; use relay::dns_resolver::DnsResolver; -use relay::tcprelay::crypto_io::EncryptedWrite; +use relay::tcprelay::crypto_io::{EncryptedWrite, DecryptedRead}; use futures::{self, Future}; use futures::stream::Stream; @@ -45,7 +45,7 @@ use net2::TcpBuilder; use ip::IpAddr; -use super::{tunnel, proxy_handshake, DecryptedHalf, EncryptedHalfFut, try_timeout, copy_timeout}; +use super::{tunnel, proxy_handshake, DecryptedHalf, EncryptedHalfFut, try_timeout}; /// Context for doing handshake with client pub struct TcpRelayClientHandshake { @@ -187,7 +187,7 @@ impl TcpRelayClientConnected { let timeout = self.timeout; let handle = self.handle.clone(); tunnel(self.addr, - copy_timeout(r, svr_w, self.timeout, self.handle), + r.copy_timeout_opt(svr_w, self.timeout, self.handle), w_fut.and_then(move |w| w.copy_timeout_opt(svr_r, timeout, handle))) } } diff --git a/src/relay/tcprelay/socks5_local.rs b/src/relay/tcprelay/socks5_local.rs index d02a936c..b63be2ea 100644 --- a/src/relay/tcprelay/socks5_local.rs +++ b/src/relay/tcprelay/socks5_local.rs @@ -43,7 +43,7 @@ use relay::socks5::{TcpRequestHeader, TcpResponseHeader}; use relay::loadbalancing::server::RoundRobin; use relay::loadbalancing::server::LoadBalancer; use relay::{BoxIoFuture, boxed_future}; -use relay::tcprelay::crypto_io::EncryptedWrite; +use relay::tcprelay::crypto_io::{EncryptedWrite, DecryptedRead}; use super::{tunnel, ignore_until_end, try_timeout}; @@ -108,7 +108,7 @@ fn handle_socks5_connect(handle: &Handle, let cloned_handle = handle.clone(); let cloned_timeout = timeout; - let rhalf = svr_r.and_then(move |svr_r| super::copy_timeout(svr_r, w, timeout, handle)); + let rhalf = svr_r.and_then(move |svr_r| svr_r.copy_timeout_opt(w, timeout, handle)); let whalf = svr_w.and_then(move |svr_w| svr_w.copy_timeout_opt(r, cloned_timeout, cloned_handle)); tunnel(cloned_addr, whalf, rhalf) diff --git a/src/relay/tcprelay/utils.rs b/src/relay/tcprelay/utils.rs new file mode 100644 index 00000000..5f2b27df --- /dev/null +++ b/src/relay/tcprelay/utils.rs @@ -0,0 +1,176 @@ +//! Utility functions + +use std::io::{self, Read, Write}; +use std::time::Duration; + +use tokio_core::reactor::{Handle, Timeout}; +use tokio_core::io::{Copy, copy}; + +use futures::{Future, Poll, Async}; + +use super::BUFFER_SIZE; + +/// Copies all data from `r` to `w`, abort if timeout reaches +pub fn copy_timeout(r: R, w: W, dur: Duration, handle: Handle) -> CopyTimeout + where R: Read, + W: Write +{ + CopyTimeout::new(r, w, dur, handle) +} + +pub struct CopyTimeout + where R: Read, + W: Write +{ + r: R, + w: W, + timeout: Duration, + handle: Handle, + amt: u64, + timer: Option, + buf: [u8; BUFFER_SIZE], + pos: usize, + cap: usize, +} + +impl CopyTimeout + where R: Read, + W: Write +{ + fn new(r: R, w: W, timeout: Duration, handle: Handle) -> CopyTimeout { + CopyTimeout { + r: r, + w: w, + timeout: timeout, + handle: handle, + amt: 0, + timer: None, + buf: [0u8; BUFFER_SIZE], + pos: 0, + cap: 0, + } + } + + 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, "timeout")), + Ok(Async::NotReady) => Ok(()), + } + } + } + } + + fn clear_timer(&mut self) { + let _ = self.timer.take(); + } + + fn read_or_set_timeout(&mut self) -> io::Result { + // First, return if timeout + try!(self.try_poll_timeout()); + + // Then, unset the previous timeout + self.clear_timer(); + + match self.r.read(&mut self.buf) { + Ok(n) => Ok(n), + Err(e) => { + if e.kind() == io::ErrorKind::WouldBlock { + self.timer = Some(Timeout::new(self.timeout, &self.handle).unwrap()); + } + Err(e) + } + } + } + + fn write_or_set_timeout(&mut self, beg: usize, end: usize) -> io::Result { + // First, return if timeout + try!(self.try_poll_timeout()); + + // Then, unset the previous timeout + self.clear_timer(); + + match self.w.write(&self.buf[beg..end]) { + Ok(n) => Ok(n), + Err(e) => { + if e.kind() == io::ErrorKind::WouldBlock { + self.timer = Some(Timeout::new(self.timeout, &self.handle).unwrap()); + } + Err(e) + } + } + } +} + +impl Future for CopyTimeout + where R: Read, + W: Write +{ + type Item = u64; + type Error = io::Error; + + fn poll(&mut self) -> Poll { + loop { + if self.pos == self.cap { + let n = try_nb!(self.read_or_set_timeout()); + + if n == 0 { + // 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. + try_nb!(self.w.flush()); + return Ok(self.amt.into()); + } + + self.pos = 0; + self.cap = n; + + // Clear it before write + self.clear_timer(); + } + + // If our buffer has some data, let's write it out! + while self.pos < self.cap { + let (pos, cap) = (self.pos, self.cap); + let i = try_nb!(self.write_or_set_timeout(pos, cap)); + self.pos += i; + self.amt += i as u64; + } + + // Clear it before read + self.clear_timer(); + } + } +} + +/// Copies all data from `r` to `w` with optional timeout param +pub fn copy_timeout_opt(r: R, w: W, dur: Option, handle: Handle) -> CopyTimeoutOpt + where R: Read, + W: Write +{ + match dur { + Some(d) => CopyTimeoutOpt::CopyTimeout(copy_timeout(r, w, d, handle)), + None => CopyTimeoutOpt::Copy(copy(r, w)), + } +} + +/// Copies all data from `R` to `W` +pub enum CopyTimeoutOpt { + Copy(Copy), + CopyTimeout(CopyTimeout), +} + +impl Future for CopyTimeoutOpt { + type Item = u64; + type Error = io::Error; + + fn poll(&mut self) -> Poll { + match *self { + CopyTimeoutOpt::CopyTimeout(ref mut c) => c.poll(), + CopyTimeoutOpt::Copy(ref mut c) => c.poll(), + } + } +} \ No newline at end of file