mirror of
https://github.com/shadowsocks/shadowsocks-rust.git
synced 2026-11-18 16:16:52 +00:00
Optimize buffers with bytes
This commit is contained in:
Generated
+22
-1
@@ -1,10 +1,11 @@
|
||||
[root]
|
||||
name = "shadowsocks-rust"
|
||||
version = "1.2.1"
|
||||
version = "1.3.0"
|
||||
dependencies = [
|
||||
"argon2rs 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"base64 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"byteorder 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"bytes 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"clap 2.20.5 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"domain 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"env_logger 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
@@ -82,6 +83,15 @@ name = "byteorder"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"byteorder 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"iovec 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "0.1.0"
|
||||
@@ -225,6 +235,15 @@ name = "inflate"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
|
||||
[[package]]
|
||||
name = "iovec"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"libc 0.2.20 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "0.3.1"
|
||||
@@ -636,6 +655,7 @@ dependencies = [
|
||||
"checksum blake2-rfc 0.2.17 (registry+https://github.com/rust-lang/crates.io-index)" = "0c6a476f32fef3402f1161f89d0d39822809627754a126f8441ff2a9d45e2d59"
|
||||
"checksum byteorder 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "0fc10e8cc6b2580fda3f36eb6dc5316657f812a3df879a44a66fc9f0fdbc4855"
|
||||
"checksum byteorder 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c40977b0ee6b9885c9013cd41d9feffdd22deb3bb4dc3a71d901cc7a77de18c8"
|
||||
"checksum bytes 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "46112a0060ae15e3a3f9a445428a53e082b91215b744fa27a1948842f4a64b96"
|
||||
"checksum cfg-if 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "de1e760d7b6535af4241fca8bd8adf68e2e7edacc6b29f5d399050c5e48cf88c"
|
||||
"checksum clap 2.20.5 (registry+https://github.com/rust-lang/crates.io-index)" = "7db281b0520e97fbd15cd615dcd8f8bcad0c26f5f7d5effe705f090f39e9a758"
|
||||
"checksum color_quant 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a475fc4af42d83d28adf72968d9bcfaf035a1a9381642d8e85d8a04957767b0d"
|
||||
@@ -654,6 +674,7 @@ dependencies = [
|
||||
"checksum glob 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "8be18de09a56b60ed0edf84bc9df007e30040691af7acd1c41874faac5895bfb"
|
||||
"checksum image 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)" = "979bad0502082fd60053a490282e87d6c89650942e3a270e0d4c83569c7f5899"
|
||||
"checksum inflate 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "e7e0062d2dc2f17d2f13750d95316ae8a2ff909af0fda957084f5defd87c43bb"
|
||||
"checksum iovec 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "29d062ee61fccdf25be172e70f34c9f6efc597e1fb8f6526e8437b2046ab26be"
|
||||
"checksum itoa 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "eb2f404fbc66fd9aac13e998248505e7ecb2ad8e44ab6388684c5fb11c6c251c"
|
||||
"checksum jpeg-decoder 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)" = "5c4ff3d14e7ef3522471ab712832c3dd50001f7fb7aa4cdc48af811d63b531e9"
|
||||
"checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d"
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "shadowsocks-rust"
|
||||
version = "1.2.1"
|
||||
version = "1.3.0"
|
||||
authors = ["Y. T. CHUNG <zonyitoo@gmail.com>"]
|
||||
description = "shadowsocks is a fast tunnel proxy that helps you bypass firewalls."
|
||||
repository = "https://github.com/zonyitoo/shadowsocks-rust"
|
||||
@@ -47,6 +47,7 @@ lazy_static = "0.2"
|
||||
serde_json = "0.9"
|
||||
base64 = "0.4"
|
||||
domain = "0.1"
|
||||
bytes = "0.4"
|
||||
|
||||
[dependencies.argon2rs]
|
||||
version = "0.2"
|
||||
|
||||
+1
-1
@@ -104,4 +104,4 @@ pub fn increase_nonce(nonce: &mut [u8]) {
|
||||
*v = r;
|
||||
adding = overflow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+14
-11
@@ -13,6 +13,8 @@ use crypto::{AeadDecryptor, AeadEncryptor};
|
||||
use crypto::cipher::Error;
|
||||
use crypto::aead::{make_skey, increase_nonce};
|
||||
|
||||
use bytes::{BytesMut, BufMut};
|
||||
|
||||
/// Cipher provided by Rust-Crypto
|
||||
pub enum CryptoCipher {
|
||||
ChaCha20(ChaCha20),
|
||||
@@ -31,25 +33,26 @@ impl CryptoCipher {
|
||||
}
|
||||
|
||||
impl StreamCipher for CryptoCipher {
|
||||
fn update(&mut self, data: &[u8], out: &mut Vec<u8>) -> CipherResult<()> {
|
||||
out.reserve(data.len());
|
||||
let orig_len = out.len();
|
||||
unsafe {
|
||||
out.set_len(orig_len + data.len());
|
||||
}
|
||||
let mut out = &mut out[orig_len..];
|
||||
|
||||
fn update<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()> {
|
||||
let mut buf = BytesMut::with_capacity(self.buffer_size(data));
|
||||
unsafe { buf.set_len(self.buffer_size(data)) }; // NOTE: Set length
|
||||
assert_eq!(buf.len(), data.len());
|
||||
match *self {
|
||||
CryptoCipher::ChaCha20(ref mut cipher) => cipher.process(data, out),
|
||||
CryptoCipher::Salsa20(ref mut cipher) => cipher.process(data, out),
|
||||
CryptoCipher::ChaCha20(ref mut cipher) => cipher.process(data, &mut *buf),
|
||||
CryptoCipher::Salsa20(ref mut cipher) => cipher.process(data, &mut *buf),
|
||||
}
|
||||
out.put(buf);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finalize(&mut self, _: &mut Vec<u8>) -> CipherResult<()> {
|
||||
fn finalize<B: BufMut>(&mut self, _: &mut B) -> CipherResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn buffer_size(&self, data: &[u8]) -> usize {
|
||||
data.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// AEAD ciphers provided by Rust-Crypto
|
||||
|
||||
+10
-4
@@ -2,18 +2,24 @@
|
||||
|
||||
use super::{StreamCipher, CipherResult};
|
||||
|
||||
use bytes::BufMut;
|
||||
|
||||
/// Dummy cipher
|
||||
///
|
||||
/// Copies data directly to output, very dummy
|
||||
pub struct DummyCipher;
|
||||
|
||||
impl StreamCipher for DummyCipher {
|
||||
fn update(&mut self, data: &[u8], out: &mut Vec<u8>) -> CipherResult<()> {
|
||||
out.extend_from_slice(data);
|
||||
fn update<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()> {
|
||||
out.put_slice(data);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finalize(&mut self, _: &mut Vec<u8>) -> CipherResult<()> {
|
||||
fn finalize<B: BufMut>(&mut self, _: &mut B) -> CipherResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn buffer_size(&self, data: &[u8]) -> usize {
|
||||
data.len()
|
||||
}
|
||||
}
|
||||
|
||||
+29
-12
@@ -8,6 +8,7 @@ use crypto::cipher;
|
||||
use crypto::CryptoMode;
|
||||
|
||||
use openssl::symm;
|
||||
use bytes::{BufMut, BytesMut};
|
||||
|
||||
/// Core cipher of OpenSSL
|
||||
pub struct OpenSSLCrypto {
|
||||
@@ -43,24 +44,36 @@ impl OpenSSLCrypto {
|
||||
}
|
||||
|
||||
/// Update data
|
||||
pub fn update(&mut self, data: &[u8], out: &mut Vec<u8>) -> CipherResult<()> {
|
||||
let orig_length = out.len();
|
||||
pub fn update<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()> {
|
||||
let least_reserved = data.len() + self.cipher.block_size();
|
||||
out.resize(orig_length + least_reserved, 0);
|
||||
let length = try!(self.inner.update(data, &mut out[orig_length..]));
|
||||
out.resize(orig_length + length, 0);
|
||||
let mut buf = BytesMut::with_capacity(least_reserved); // NOTE: len() is 0 now!
|
||||
unsafe {
|
||||
buf.set_len(least_reserved);
|
||||
}
|
||||
let length = self.inner.update(data, &mut *buf)?;
|
||||
buf.truncate(length);
|
||||
out.put(buf);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Generate the final block
|
||||
pub fn finalize(&mut self, out: &mut Vec<u8>) -> CipherResult<()> {
|
||||
let orig_length = out.len();
|
||||
pub fn finalize<B: BufMut>(&mut self, out: &mut B) -> CipherResult<()> {
|
||||
let least_reserved = self.cipher.block_size();
|
||||
out.resize(orig_length + least_reserved, 0);
|
||||
let length = try!(self.inner.finalize(&mut out[orig_length..]));
|
||||
out.resize(orig_length + length, 0);
|
||||
let mut buf = BytesMut::with_capacity(least_reserved); // NOTE: len() is 0 now!
|
||||
unsafe {
|
||||
buf.set_len(least_reserved);
|
||||
}
|
||||
|
||||
let length = self.inner.finalize(&mut *buf)?;
|
||||
buf.truncate(length);
|
||||
out.put(buf);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Gets output buffer size based on data
|
||||
pub fn buffer_size(&self, data: &[u8]) -> usize {
|
||||
self.cipher.block_size() + data.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// The Cipher binding for OpenSSL's `libcrypto`.
|
||||
@@ -106,11 +119,15 @@ impl OpenSSLCipher {
|
||||
unsafe impl Send for OpenSSLCipher {}
|
||||
|
||||
impl StreamCipher for OpenSSLCipher {
|
||||
fn update(&mut self, data: &[u8], out: &mut Vec<u8>) -> CipherResult<()> {
|
||||
fn update<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()> {
|
||||
self.worker.update(data, out)
|
||||
}
|
||||
|
||||
fn finalize(&mut self, out: &mut Vec<u8>) -> CipherResult<()> {
|
||||
fn finalize<B: BufMut>(&mut self, out: &mut B) -> CipherResult<()> {
|
||||
self.worker.finalize(out)
|
||||
}
|
||||
|
||||
fn buffer_size(&self, data: &[u8]) -> usize {
|
||||
self.worker.buffer_size(data)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ use crypto::{StreamCipher, CipherType, CipherResult};
|
||||
use crypto::digest::{self, Digest, DigestType};
|
||||
use crypto::CryptoMode;
|
||||
|
||||
use bytes::BufMut;
|
||||
|
||||
/// Rc4Md5 Cipher
|
||||
pub struct Rc4Md5Cipher {
|
||||
crypto: OpenSSLCrypto,
|
||||
@@ -23,13 +25,17 @@ impl Rc4Md5Cipher {
|
||||
}
|
||||
|
||||
impl StreamCipher for Rc4Md5Cipher {
|
||||
fn update(&mut self, data: &[u8], out: &mut Vec<u8>) -> CipherResult<()> {
|
||||
fn update<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()> {
|
||||
self.crypto.update(data, out)
|
||||
}
|
||||
|
||||
fn finalize(&mut self, out: &mut Vec<u8>) -> CipherResult<()> {
|
||||
fn finalize<B: BufMut>(&mut self, out: &mut B) -> CipherResult<()> {
|
||||
self.crypto.finalize(out)
|
||||
}
|
||||
|
||||
fn buffer_size(&self, data: &[u8]) -> usize {
|
||||
self.crypto.buffer_size(data)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for Rc4Md5Cipher {}
|
||||
|
||||
+16
-5
@@ -8,13 +8,16 @@ use crypto::rc4_md5;
|
||||
use crypto::dummy;
|
||||
use crypto::crypto::CryptoCipher;
|
||||
|
||||
use bytes::BufMut;
|
||||
|
||||
/// Basic operation of Cipher, which is a Symmetric Cipher.
|
||||
///
|
||||
/// The `update` method could be called multiple times, and the `finalize` method will
|
||||
/// encrypt the last block
|
||||
pub trait StreamCipher {
|
||||
fn update(&mut self, data: &[u8], out: &mut Vec<u8>) -> CipherResult<()>;
|
||||
fn finalize(&mut self, out: &mut Vec<u8>) -> CipherResult<()>;
|
||||
fn update<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()>;
|
||||
fn finalize<B: BufMut>(&mut self, out: &mut B) -> CipherResult<()>;
|
||||
fn buffer_size(&self, data: &[u8]) -> usize;
|
||||
}
|
||||
|
||||
macro_rules! define_stream_ciphers {
|
||||
@@ -36,7 +39,7 @@ macro_rules! define_stream_ciphers {
|
||||
}
|
||||
|
||||
impl StreamCipher for StreamCipherVariant {
|
||||
fn update(&mut self, data: &[u8], out: &mut Vec<u8>) -> CipherResult<()> {
|
||||
fn update<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()> {
|
||||
match *self {
|
||||
$(
|
||||
StreamCipherVariant::$name(ref mut cipher) => cipher.update(data, out),
|
||||
@@ -44,13 +47,21 @@ macro_rules! define_stream_ciphers {
|
||||
}
|
||||
}
|
||||
|
||||
fn finalize(&mut self, out: &mut Vec<u8>) -> CipherResult<()> {
|
||||
fn finalize<B: BufMut>(&mut self, out: &mut B) -> CipherResult<()> {
|
||||
match *self {
|
||||
$(
|
||||
StreamCipherVariant::$name(ref mut cipher) => cipher.finalize(out),
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
fn buffer_size(&self, data: &[u8]) -> usize {
|
||||
match *self {
|
||||
$(
|
||||
StreamCipherVariant::$name(ref cipher) => cipher.buffer_size(data),
|
||||
)+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$(
|
||||
@@ -87,4 +98,4 @@ pub fn new_stream(t: CipherType, key: &[u8], iv: &[u8], mode: CryptoMode) -> Str
|
||||
|
||||
_ => StreamCipherVariant::new(openssl::OpenSSLCipher::new(t, key, iv, mode)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+15
-6
@@ -7,6 +7,7 @@ use crypto::digest::{self, DigestType, Digest};
|
||||
use crypto::CryptoMode;
|
||||
|
||||
use byteorder::{ReadBytesExt, LittleEndian};
|
||||
use bytes::{BufMut, BytesMut};
|
||||
|
||||
const TABLE_SIZE: usize = 256usize;
|
||||
|
||||
@@ -48,23 +49,31 @@ impl TableCipher {
|
||||
}
|
||||
}
|
||||
|
||||
fn process(&mut self, data: &[u8], out: &mut Vec<u8>) -> CipherResult<()> {
|
||||
out.reserve(data.len());
|
||||
for d in data.iter() {
|
||||
out.push(self.table[*d as usize]);
|
||||
fn process<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()> {
|
||||
let mut buf = BytesMut::with_capacity(self.buffer_size(data));
|
||||
unsafe {
|
||||
buf.set_len(self.buffer_size(data)); // Set length
|
||||
}
|
||||
for (idx, d) in data.iter().enumerate() {
|
||||
buf[idx] = self.table[*d as usize];
|
||||
}
|
||||
out.put(buf);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl StreamCipher for TableCipher {
|
||||
fn update(&mut self, data: &[u8], out: &mut Vec<u8>) -> CipherResult<()> {
|
||||
fn update<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()> {
|
||||
self.process(data, out)
|
||||
}
|
||||
|
||||
fn finalize(&mut self, _: &mut Vec<u8>) -> CipherResult<()> {
|
||||
fn finalize<B: BufMut>(&mut self, _: &mut B) -> CipherResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn buffer_size(&self, data: &[u8]) -> usize {
|
||||
data.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -88,6 +88,7 @@ extern crate futures;
|
||||
extern crate tokio_core;
|
||||
extern crate net2;
|
||||
extern crate domain;
|
||||
extern crate bytes;
|
||||
|
||||
extern crate libc;
|
||||
#[macro_use]
|
||||
|
||||
+47
-30
@@ -36,7 +36,7 @@ use std::io::{self, Read, Write, BufRead, Cursor};
|
||||
use std::cmp;
|
||||
use std::u16;
|
||||
|
||||
use byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
|
||||
use bytes::{Buf, BufMut, BytesMut, BigEndian};
|
||||
|
||||
use crypto::{self, CipherType, AeadEncryptor, AeadDecryptor};
|
||||
|
||||
@@ -53,8 +53,8 @@ pub struct DecryptedReader<R>
|
||||
where R: Read
|
||||
{
|
||||
reader: R,
|
||||
buffer: Vec<u8>,
|
||||
data: Vec<u8>,
|
||||
buffer: BytesMut,
|
||||
data: BytesMut,
|
||||
cipher: Box<AeadDecryptor>,
|
||||
pos: usize,
|
||||
sent_final: bool,
|
||||
@@ -68,8 +68,8 @@ impl<R> DecryptedReader<R>
|
||||
pub fn new(r: R, t: CipherType, key: &[u8], nounce: &[u8]) -> DecryptedReader<R> {
|
||||
DecryptedReader {
|
||||
reader: r,
|
||||
buffer: Vec::new(),
|
||||
data: Vec::new(),
|
||||
buffer: BytesMut::with_capacity(BUFFER_SIZE),
|
||||
data: BytesMut::with_capacity(BUFFER_SIZE),
|
||||
cipher: crypto::new_aead_decryptor(t, key, nounce),
|
||||
pos: 0,
|
||||
sent_final: false,
|
||||
@@ -102,6 +102,7 @@ impl<R> DecryptedReader<R>
|
||||
|
||||
fn read_exact(&mut self, expect_length: usize, ignore_final: bool) -> io::Result<()> {
|
||||
let mut incoming = [0u8; BUFFER_SIZE];
|
||||
self.buffer.reserve(expect_length);
|
||||
|
||||
while self.buffer.len() < expect_length {
|
||||
let remain = expect_length - self.buffer.len();
|
||||
@@ -115,7 +116,7 @@ impl<R> DecryptedReader<R>
|
||||
|
||||
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "unexpected eof"));
|
||||
}
|
||||
Ok(n) => self.buffer.extend_from_slice(&incoming[..n]),
|
||||
Ok(n) => self.buffer.put_slice(&incoming[..n]),
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
@@ -131,12 +132,11 @@ impl<R> DecryptedReader<R>
|
||||
{
|
||||
let data = &self.buffer[..2];
|
||||
let tag = &self.buffer[2..];
|
||||
let mut len_buf = [0u8; 2];
|
||||
self.cipher.decrypt(data, &mut len_buf, tag)?;
|
||||
|
||||
let len = {
|
||||
let mut cur = Cursor::new(&mut len_buf);
|
||||
cur.read_u16::<BigEndian>().unwrap() as usize
|
||||
let mut len_buf = [0u8; 2];
|
||||
self.cipher.decrypt(data, &mut len_buf, tag)?;
|
||||
Cursor::new(len_buf).get_u16::<BigEndian>() as usize
|
||||
};
|
||||
|
||||
self.read_step = ReadingStep::DataAndTag(len);
|
||||
@@ -156,8 +156,12 @@ impl<R> DecryptedReader<R>
|
||||
// Ok, got data
|
||||
let data = &self.buffer[..dlen];
|
||||
let tag = &self.buffer[dlen..];
|
||||
self.data.resize(dlen, 0);
|
||||
self.cipher.decrypt(data, &mut self.data, tag)?;
|
||||
self.data.clear();
|
||||
self.data.reserve(dlen);
|
||||
unsafe {
|
||||
self.data.set_len(dlen); // Decrypted data has exactly the same length
|
||||
}
|
||||
self.cipher.decrypt(data, &mut *self.data, tag)?;
|
||||
}
|
||||
|
||||
self.read_step = ReadingStep::Done;
|
||||
@@ -221,7 +225,14 @@ impl<R> Read for DecryptedReader<R>
|
||||
}
|
||||
}
|
||||
|
||||
impl<R> DecryptedRead for DecryptedReader<R> where R: Read {}
|
||||
impl<R> DecryptedRead for DecryptedReader<R>
|
||||
where R: Read
|
||||
{
|
||||
fn buffer_size(&self, data: &[u8]) -> usize {
|
||||
2 + self.tag_size // len and len_tag
|
||||
+ data.len() + self.tag_size // data and data_tag
|
||||
}
|
||||
}
|
||||
|
||||
/// Writer wrapper that will encrypt data automatically
|
||||
pub struct EncryptedWriter<W>
|
||||
@@ -256,38 +267,44 @@ impl<W> EncryptedWrite for EncryptedWriter<W>
|
||||
self.writer.flush()
|
||||
}
|
||||
|
||||
fn encrypt(&mut self, data: &[u8], buf: &mut Vec<u8>) -> io::Result<()> {
|
||||
fn encrypt<B: BufMut>(&mut self, data: &[u8], buf: &mut B) -> io::Result<()> {
|
||||
// Data.Len is a 16-bit big-endian integer indicating the length of Data. It should be smaller than 0x3FFF.
|
||||
assert!(data.len() <= 0x3FFF);
|
||||
|
||||
let data_length = data.len() as u16;
|
||||
|
||||
let mut data_len_buf = [0u8; 2];
|
||||
{
|
||||
let mut cur = Cursor::new(&mut data_len_buf[..]);
|
||||
let _ = cur.write_u16::<BigEndian>(data_length);
|
||||
let mut data_len_buf = BytesMut::with_capacity(2);
|
||||
data_len_buf.put_u16::<BigEndian>(data_length);
|
||||
|
||||
let mut tag_buf = BytesMut::with_capacity(self.tag_size);
|
||||
unsafe {
|
||||
tag_buf.set_len(self.tag_size);
|
||||
}
|
||||
|
||||
let mut tag_buf = vec![0u8; self.tag_size];
|
||||
|
||||
let mut encrypted_data_len = [0u8; 2];
|
||||
self.cipher.encrypt(&data_len_buf[..], &mut encrypted_data_len, &mut tag_buf[..]);
|
||||
self.cipher.encrypt(&data_len_buf, &mut encrypted_data_len, &mut *tag_buf);
|
||||
|
||||
trace!("LENGTH TAG: {:?}", tag_buf);
|
||||
|
||||
buf.extend_from_slice(&encrypted_data_len);
|
||||
buf.extend_from_slice(&tag_buf);
|
||||
buf.put(&encrypted_data_len[..]);
|
||||
buf.put_slice(&tag_buf);
|
||||
|
||||
let orig_buf_len = buf.len();
|
||||
buf.reserve(data.len() + self.tag_size);
|
||||
buf.resize(orig_buf_len + data.len(), 0);
|
||||
self.cipher.encrypt(data, &mut buf[orig_buf_len..], &mut tag_buf);
|
||||
let mut data_buf = BytesMut::with_capacity(data.len());
|
||||
unsafe {
|
||||
data_buf.set_len(data.len());
|
||||
}
|
||||
self.cipher.encrypt(data, &mut *data_buf, &mut *tag_buf);
|
||||
|
||||
trace!("DATA TAG: {:?}", tag_buf);
|
||||
|
||||
buf.append(&mut tag_buf);
|
||||
|
||||
buf.put(data_buf);
|
||||
buf.put(tag_buf);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn buffer_size(&self, data: &[u8]) -> usize {
|
||||
2 + self.tag_size // len and len_tag
|
||||
+ data.len() + self.tag_size // data and data_tag
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,14 +9,21 @@ use futures::{Future, Poll, Async};
|
||||
use tokio_core::reactor::{Handle, Timeout};
|
||||
use tokio_core::io::{copy, Copy};
|
||||
|
||||
use bytes::{BufMut, BytesMut};
|
||||
|
||||
use super::BUFFER_SIZE;
|
||||
use super::utils::{copy_timeout, copy_timeout_opt, CopyTimeout, CopyTimeoutOpt};
|
||||
|
||||
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 {
|
||||
/// 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,
|
||||
@@ -52,34 +59,22 @@ pub trait EncryptedWrite {
|
||||
/// Flush the writer
|
||||
fn flush(&mut self) -> io::Result<()>;
|
||||
/// Encrypt data into buffer for writing
|
||||
fn encrypt(&mut self, data: &[u8], buf: &mut Vec<u8>) -> io::Result<()>;
|
||||
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::Writing {
|
||||
writer: self,
|
||||
buf: buf,
|
||||
pos: 0,
|
||||
enc_buf: Vec::new(),
|
||||
encrypted: false,
|
||||
}
|
||||
EncryptedWriteAll::new(self, buf)
|
||||
}
|
||||
|
||||
/// Copies all data from `r`
|
||||
fn copy<R: Read>(self, r: R) -> EncryptedCopy<R, Self>
|
||||
where Self: Sized
|
||||
{
|
||||
EncryptedCopy {
|
||||
reader: r,
|
||||
writer: self,
|
||||
read_done: false,
|
||||
amt: 0,
|
||||
pos: 0,
|
||||
cap: 0,
|
||||
buf: Vec::new(),
|
||||
}
|
||||
EncryptedCopy::new(r, self)
|
||||
}
|
||||
|
||||
/// Copies all data from `r` with timeout
|
||||
@@ -109,12 +104,28 @@ pub enum EncryptedWriteAll<W, B>
|
||||
writer: W,
|
||||
buf: B,
|
||||
pos: usize,
|
||||
enc_buf: Vec<u8>,
|
||||
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]>
|
||||
@@ -128,6 +139,11 @@ impl<W, B> Future for EncryptedWriteAll<W, B>
|
||||
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)?;
|
||||
}
|
||||
|
||||
@@ -157,7 +173,25 @@ pub struct EncryptedCopy<R: Read, W: EncryptedWrite> {
|
||||
amt: u64,
|
||||
pos: usize,
|
||||
cap: usize,
|
||||
buf: Vec<u8>,
|
||||
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: r,
|
||||
writer: w,
|
||||
read_done: false,
|
||||
amt: 0,
|
||||
pos: 0,
|
||||
cap: 0,
|
||||
buf: BytesMut::with_capacity(buffer_size),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: Read, W: EncryptedWrite> Future for EncryptedCopy<R, W> {
|
||||
@@ -175,7 +209,12 @@ impl<R: Read, W: EncryptedWrite> Future for EncryptedCopy<R, W> {
|
||||
if n == 0 {
|
||||
self.read_done = true;
|
||||
} else {
|
||||
self.writer.encrypt(&local_buf[..n], &mut self.buf)?;
|
||||
let data = &local_buf[..n];
|
||||
// Ensure we have enough space
|
||||
let buffer_len = self.writer.buffer_size(data);
|
||||
self.buf.reserve(buffer_len);
|
||||
|
||||
self.writer.encrypt(data, &mut self.buf)?;
|
||||
}
|
||||
self.pos = 0;
|
||||
self.cap = self.buf.len();
|
||||
@@ -211,11 +250,12 @@ pub struct EncryptedCopyTimeout<R: Read, W: EncryptedWrite> {
|
||||
handle: Handle,
|
||||
timer: Option<Timeout>,
|
||||
read_buf: [u8; BUFFER_SIZE],
|
||||
write_buf: Vec<u8>,
|
||||
write_buf: BytesMut,
|
||||
}
|
||||
|
||||
impl<R: Read, W: EncryptedWrite> EncryptedCopyTimeout<R, W> {
|
||||
fn new(r: R, w: W, dur: Duration, handle: Handle) -> EncryptedCopyTimeout<R, W> {
|
||||
let buffer_size = w.buffer_size(&DUMMY_BUFFER);
|
||||
EncryptedCopyTimeout {
|
||||
reader: r,
|
||||
writer: w,
|
||||
@@ -227,7 +267,7 @@ impl<R: Read, W: EncryptedWrite> EncryptedCopyTimeout<R, W> {
|
||||
handle: handle,
|
||||
timer: None,
|
||||
read_buf: [0u8; BUFFER_SIZE],
|
||||
write_buf: Vec::new(),
|
||||
write_buf: BytesMut::with_capacity(buffer_size),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -263,7 +303,12 @@ impl<R: Read, W: EncryptedWrite> EncryptedCopyTimeout<R, W> {
|
||||
Ok(0)
|
||||
}
|
||||
Ok(n) => {
|
||||
self.writer.encrypt(&self.read_buf[..n], &mut self.write_buf)?;
|
||||
let data = &self.read_buf[..n];
|
||||
// Ensoure we have enough space
|
||||
let buffer_len = self.writer.buffer_size(data);
|
||||
self.write_buf.reserve(buffer_len);
|
||||
|
||||
self.writer.encrypt(data, &mut self.write_buf)?;
|
||||
self.cap = self.write_buf.len();
|
||||
self.pos = 0;
|
||||
Ok(n)
|
||||
@@ -358,4 +403,4 @@ impl<R, W> Future for EncryptedCopyOpt<R, W>
|
||||
EncryptedCopyOpt::CopyTimeout(ref mut c) => c.poll(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,8 @@ use tokio_core::io::Io;
|
||||
|
||||
use futures::{self, Future, Poll};
|
||||
|
||||
use bytes::BufMut;
|
||||
|
||||
use net2::TcpBuilder;
|
||||
|
||||
pub use self::crypto_io::{DecryptedRead, EncryptedWrite};
|
||||
@@ -66,7 +68,14 @@ impl Read for DecryptedHalf {
|
||||
}
|
||||
}
|
||||
|
||||
impl DecryptedRead for DecryptedHalf {}
|
||||
impl DecryptedRead for DecryptedHalf {
|
||||
fn buffer_size(&self, data: &[u8]) -> usize {
|
||||
match *self {
|
||||
DecryptedHalf::Stream(ref e) => e.buffer_size(data),
|
||||
DecryptedHalf::Aead(ref e) => e.buffer_size(data),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BufRead for DecryptedHalf {
|
||||
fn fill_buf(&mut self) -> io::Result<&[u8]> {
|
||||
@@ -117,12 +126,19 @@ impl EncryptedWrite for EncryptedHalf {
|
||||
}
|
||||
}
|
||||
|
||||
fn encrypt(&mut self, data: &[u8], buf: &mut Vec<u8>) -> io::Result<()> {
|
||||
fn encrypt<B: BufMut>(&mut self, data: &[u8], buf: &mut B) -> io::Result<()> {
|
||||
match *self {
|
||||
EncryptedHalf::Stream(ref mut e) => e.encrypt(data, buf),
|
||||
EncryptedHalf::Aead(ref mut e) => e.encrypt(data, buf),
|
||||
}
|
||||
}
|
||||
|
||||
fn buffer_size(&self, data: &[u8]) -> usize {
|
||||
match *self {
|
||||
EncryptedHalf::Stream(ref e) => e.buffer_size(data),
|
||||
EncryptedHalf::Aead(ref e) => e.buffer_size(data),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<StreamEncryptedWriter<TcpWriteHalf>> for EncryptedHalf {
|
||||
@@ -176,7 +192,7 @@ pub fn proxy_server_handshake(remote_stream: TcpStream,
|
||||
relay_addr);
|
||||
|
||||
// Send relay address to remote
|
||||
let local_buf = Vec::new();
|
||||
let local_buf = Vec::with_capacity(128); // 128Bytes should be enough for most Addresses
|
||||
relay_addr.write_to(local_buf)
|
||||
.and_then(move |buf| {
|
||||
trace!("Sending address buffer as {:?}", buf);
|
||||
@@ -401,4 +417,4 @@ fn io_timeout<T, F>(fut: F, dur: Duration, handle: &Handle) -> BoxIoFuture<T>
|
||||
}
|
||||
});
|
||||
boxed_future(fut)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,16 +4,19 @@ use std::io::{self, Read, BufRead, Write};
|
||||
use std::cmp;
|
||||
|
||||
use crypto::{CipherType, StreamCipher, StreamCipherVariant, CryptoMode, new_stream};
|
||||
use bytes::{BufMut, BytesMut};
|
||||
|
||||
use super::BUFFER_SIZE;
|
||||
use super::{EncryptedWrite, DecryptedRead};
|
||||
|
||||
const DUMMY_BUFFER: [u8; BUFFER_SIZE] = [0u8; BUFFER_SIZE];
|
||||
|
||||
/// Reader wrapper that will decrypt data automatically
|
||||
pub struct DecryptedReader<R>
|
||||
where R: Read
|
||||
{
|
||||
reader: R,
|
||||
buffer: Vec<u8>,
|
||||
buffer: BytesMut,
|
||||
cipher: StreamCipherVariant,
|
||||
pos: usize,
|
||||
sent_final: bool,
|
||||
@@ -23,10 +26,12 @@ impl<R> DecryptedReader<R>
|
||||
where R: Read
|
||||
{
|
||||
pub fn new(r: R, t: CipherType, key: &[u8], iv: &[u8]) -> DecryptedReader<R> {
|
||||
let cipher = new_stream(t, key, iv, CryptoMode::Decrypt);
|
||||
let buffer_size = cipher.buffer_size(&DUMMY_BUFFER);
|
||||
DecryptedReader {
|
||||
reader: r,
|
||||
buffer: Vec::new(),
|
||||
cipher: new_stream(t, key, iv, CryptoMode::Decrypt),
|
||||
buffer: BytesMut::with_capacity(buffer_size),
|
||||
cipher: cipher,
|
||||
pos: 0,
|
||||
sent_final: false,
|
||||
}
|
||||
@@ -68,14 +73,24 @@ impl<R> BufRead for DecryptedReader<R>
|
||||
self.buffer.clear();
|
||||
match self.reader.read(&mut incoming) {
|
||||
Ok(0) => {
|
||||
// Ensure we have enough space
|
||||
let buffer_len = self.buffer_size(&[]);
|
||||
self.buffer.reserve(buffer_len);
|
||||
|
||||
// EOF
|
||||
try!(self.cipher
|
||||
.finalize(&mut self.buffer));
|
||||
self.sent_final = true;
|
||||
}
|
||||
Ok(l) => {
|
||||
let data = &incoming[..l];
|
||||
|
||||
// Ensure we have enough space
|
||||
let buffer_len = self.buffer_size(data);
|
||||
self.buffer.reserve(buffer_len);
|
||||
|
||||
try!(self.cipher
|
||||
.update(&incoming[..l], &mut self.buffer));
|
||||
.update(data, &mut self.buffer));
|
||||
}
|
||||
Err(err) => {
|
||||
return Err(err);
|
||||
@@ -106,7 +121,13 @@ impl<R> Read for DecryptedReader<R>
|
||||
}
|
||||
}
|
||||
|
||||
impl<R> DecryptedRead for DecryptedReader<R> where R: Read {}
|
||||
impl<R> DecryptedRead for DecryptedReader<R>
|
||||
where R: Read
|
||||
{
|
||||
fn buffer_size(&self, data: &[u8]) -> usize {
|
||||
self.cipher.buffer_size(data)
|
||||
}
|
||||
}
|
||||
|
||||
/// Writer wrapper that will encrypt data automatically
|
||||
pub struct EncryptedWriter<W>
|
||||
@@ -127,11 +148,11 @@ impl<W> EncryptedWriter<W>
|
||||
}
|
||||
}
|
||||
|
||||
fn cipher_update(&mut self, data: &[u8], buf: &mut Vec<u8>) -> io::Result<()> {
|
||||
fn cipher_update<B: BufMut>(&mut self, data: &[u8], buf: &mut B) -> io::Result<()> {
|
||||
self.cipher.update(data, buf).map_err(From::from)
|
||||
}
|
||||
|
||||
fn cipher_finalize(&mut self, buf: &mut Vec<u8>) -> io::Result<()> {
|
||||
fn cipher_finalize<B: BufMut>(&mut self, buf: &mut B) -> io::Result<()> {
|
||||
self.cipher.finalize(buf).map_err(From::from)
|
||||
}
|
||||
}
|
||||
@@ -160,7 +181,11 @@ impl<W> EncryptedWrite for EncryptedWriter<W>
|
||||
self.writer.flush()
|
||||
}
|
||||
|
||||
fn encrypt(&mut self, data: &[u8], buf: &mut Vec<u8>) -> io::Result<()> {
|
||||
fn encrypt<B: BufMut>(&mut self, data: &[u8], buf: &mut B) -> io::Result<()> {
|
||||
self.cipher_update(data, buf)
|
||||
}
|
||||
}
|
||||
|
||||
fn buffer_size(&self, data: &[u8]) -> usize {
|
||||
self.cipher.buffer_size(data)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,4 +110,4 @@ fn decrypt_payload_aead(t: CipherType, key: &[u8], payload: &[u8]) -> io::Result
|
||||
try!(cipher.decrypt(data, &mut recv_payload, tag));
|
||||
|
||||
Ok(recv_payload)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user