Misc simplification (#142)

* Remove unused addr field in Plugin struct

* Replace many Option matches with Option::map and and_then

* Rustfmt run

* Various changes suggested by clippy
This commit is contained in:
Linus Färnstrand
2019-01-24 22:14:48 +08:00
committed by Y. T. CHUNG
parent b9911c888a
commit afff1982aa
26 changed files with 128 additions and 173 deletions
+4 -4
View File
@@ -15,8 +15,8 @@ use shadowsocks::{
VERSION,
};
const BLACK: &'static str = "\x1b[40m \x1b[0m";
const WHITE: &'static str = "\x1b[47m \x1b[0m";
const BLACK: &str = "\x1b[40m \x1b[0m";
const WHITE: &str = "\x1b[47m \x1b[0m";
fn print_qrcode(encoded: &str) {
let qrcode = QrCode::new(encoded.as_bytes()).unwrap();
@@ -24,7 +24,7 @@ fn print_qrcode(encoded: &str) {
for _ in 0..qrcode.width() + 2 {
print!("{}", WHITE);
}
println!("");
println!();
for y in 0..qrcode.width() {
print!("{}", WHITE);
@@ -42,7 +42,7 @@ fn print_qrcode(encoded: &str) {
for _ in 0..qrcode.width() + 2 {
print!("{}", WHITE);
}
println!("");
println!();
}
fn encode(filename: &str, need_qrcode: bool) {
+39 -67
View File
@@ -64,8 +64,7 @@ use serde_urlencoded;
use trust_dns_resolver::config::{NameServerConfigGroup, ResolverConfig};
use url::{self, Url};
use crate::crypto::cipher::CipherType;
use crate::plugin::PluginConfig;
use crate::{crypto::cipher::CipherType, plugin::PluginConfig};
#[derive(Serialize, Deserialize, Debug, Default)]
struct SSConfig {
@@ -221,12 +220,12 @@ impl ServerConfig {
let enc_key = method.bytes_to_key(pwd.as_bytes());
trace!("Initialize config with pwd: {:?}, key: {:?}", pwd, enc_key);
ServerConfig {
addr: addr,
addr,
password: pwd,
method: method,
timeout: timeout,
enc_key: enc_key,
plugin: plugin,
method,
timeout,
enc_key,
plugin,
udp_timeout: None,
plugin_addr: None,
}
@@ -567,11 +566,7 @@ pub struct Error {
impl Error {
pub fn new(kind: ErrorKind, desc: &'static str, detail: Option<String>) -> Error {
Error {
kind: kind,
desc: desc,
detail: detail,
}
Error { kind, desc, detail }
}
}
@@ -609,7 +604,7 @@ impl Config {
mode: Mode::TcpOnly,
no_delay: false,
manager_address: None,
config_type: config_type,
config_type,
}
}
@@ -679,24 +674,17 @@ impl Config {
let plugin = match config.plugin {
None => None,
Some(p) => Some(PluginConfig {
plugin: p,
Some(plugin) => Some(PluginConfig {
plugin,
plugin_opt: config.plugin_opts,
}),
};
let timeout = match config.timeout {
None => None,
Some(t) => Some(Duration::from_secs(t)),
};
let timeout = config.timeout.map(Duration::from_secs);
let udp_timeout = config.udp_timeout.map(Duration::from_secs);
let mut nsvr = ServerConfig::new(addr, pwd, method, timeout, plugin);
let udp_timeout = match config.udp_timeout {
None => None,
Some(t) => Some(Duration::from_secs(t)),
};
nsvr.udp_timeout = udp_timeout;
nconfig.server.push(nsvr);
@@ -743,18 +731,11 @@ impl Config {
}),
};
let timeout = match svr.timeout {
None => None,
Some(t) => Some(Duration::from_secs(t)),
};
let timeout = svr.timeout.map(Duration::from_secs);
let udp_timeout = config.udp_timeout.map(Duration::from_secs);
let mut nsvr = ServerConfig::new(addr, svr.password, method, timeout, plugin);
let udp_timeout = match config.udp_timeout {
None => None,
Some(t) => Some(Duration::from_secs(t)),
};
nsvr.udp_timeout = udp_timeout;
nconfig.server.push(nsvr);
@@ -828,39 +809,36 @@ impl Config {
}
pub fn get_dns_config(&self) -> Option<ResolverConfig> {
match self.dns {
None => None,
Some(ref ds) => {
match &ds[..] {
"google" => Some(ResolverConfig::google()),
self.dns.as_ref().and_then(|ds| {
match &ds[..] {
"google" => Some(ResolverConfig::google()),
"cloudflare" => Some(ResolverConfig::cloudflare()),
"cloudflare_tls" => Some(ResolverConfig::cloudflare_tls()),
"cloudflare_https" => Some(ResolverConfig::cloudflare_https()),
"cloudflare" => Some(ResolverConfig::cloudflare()),
"cloudflare_tls" => Some(ResolverConfig::cloudflare_tls()),
"cloudflare_https" => Some(ResolverConfig::cloudflare_https()),
"quad9" => Some(ResolverConfig::quad9()),
"quad9_tls" => Some(ResolverConfig::quad9_tls()),
"quad9" => Some(ResolverConfig::quad9()),
"quad9_tls" => Some(ResolverConfig::quad9_tls()),
_ => {
// Set ips directly
match ds.parse::<IpAddr>() {
Ok(ip) => Some(ResolverConfig::from_parts(
None,
vec![],
NameServerConfigGroup::from_ips_clear(&[ip], 53),
)),
Err(..) => {
error!(
"Failed to parse DNS \"{}\" in config to IpAddr, fallback to system config",
ds
);
None
}
_ => {
// Set ips directly
match ds.parse::<IpAddr>() {
Ok(ip) => Some(ResolverConfig::from_parts(
None,
vec![],
NameServerConfigGroup::from_ips_clear(&[ip], 53),
)),
Err(..) => {
error!(
"Failed to parse DNS \"{}\" in config to IpAddr, fallback to system config",
ds
);
None
}
}
}
}
}
})
}
pub fn get_remote_dns(&self) -> SocketAddr {
@@ -898,10 +876,7 @@ impl fmt::Display for Config {
jconf.method = Some(svr.method().to_string());
jconf.password = Some(svr.password().to_string());
jconf.plugin = svr.plugin().map(|p| p.plugin.to_string());
jconf.plugin_opts = match svr.plugin() {
None => None,
Some(p) => p.plugin_opt.clone(),
};
jconf.plugin_opts = svr.plugin().and_then(|p| p.plugin_opt.clone());
jconf.timeout = svr.timeout().map(|t| t.as_secs());
jconf.udp_timeout = svr.udp_timeout().map(|t| t.as_secs());
} else if self.server.len() > 1 {
@@ -920,10 +895,7 @@ impl fmt::Display for Config {
password: svr.password().to_string(),
method: svr.method().to_string(),
plugin: svr.plugin().map(|p| p.plugin.to_string()),
plugin_opts: match svr.plugin() {
None => None,
Some(p) => p.plugin_opt.clone(),
},
plugin_opts: svr.plugin().and_then(|p| p.plugin_opt.clone()),
timeout: svr.timeout().map(|t| t.as_secs()),
udp_timeout: svr.udp_timeout().map(|t| t.as_secs()),
});
+3 -5
View File
@@ -9,9 +9,7 @@ use std::{
use lru_cache::LruCache;
use trust_dns_resolver::AsyncResolver;
use crate::config::Config;
use crate::plugin::Plugin;
use crate::relay::dns_resolver::create_resolver;
use crate::{config::Config, plugin::Plugin, relay::dns_resolver::create_resolver};
type DnsQueryCache = LruCache<u16, (SocketAddr, Instant)>;
@@ -29,7 +27,7 @@ impl Context {
pub fn new(config: Config) -> Context {
let resolver = create_resolver(config.get_dns_config());
Context {
config: config,
config,
dns_resolver: Arc::new(resolver),
dns_query_cache: None,
plugins: Arc::new(Vec::new()),
@@ -39,7 +37,7 @@ impl Context {
pub fn new_dns(config: Config) -> Context {
let resolver = create_resolver(config.get_dns_config());
Context {
config: config,
config,
dns_resolver: Arc::new(resolver),
dns_query_cache: Some(Arc::new(Mutex::new(LruCache::new(1024)))),
plugins: Arc::new(Vec::new()),
+1 -1
View File
@@ -77,7 +77,7 @@ pub fn new_aead_decryptor(t: CipherType, key: &[u8], nonce: &[u8]) -> BoxAeadDec
}
}
const SUBKEY_INFO: &'static [u8] = b"ss-subkey";
const SUBKEY_INFO: &[u8] = b"ss-subkey";
/// Make Session key
///
+1 -1
View File
@@ -8,8 +8,8 @@ use std::{
str::{self, FromStr},
};
use bytes::{BufMut, Bytes, BytesMut};
use crate::crypto::digest::{self, Digest, DigestType};
use bytes::{BufMut, Bytes, BytesMut};
use openssl::symm;
use rand::{self, RngCore};
use ring::aead::{AES_128_GCM, AES_256_GCM, CHACHA20_POLY1305};
+2 -2
View File
@@ -1,12 +1,12 @@
//! Crypto methods for shadowsocks
use std::convert::From;
use crate::openssl::symm;
pub use self::{
aead::{new_aead_decryptor, new_aead_encryptor, AeadDecryptor, AeadEncryptor, BoxAeadDecryptor, BoxAeadEncryptor},
cipher::{CipherCategory, CipherResult, CipherType},
stream::{new_stream, BoxStreamCipher, StreamCipher},
};
use crate::openssl::symm;
use std::convert::From;
pub mod aead;
pub mod cipher;
+2 -2
View File
@@ -48,10 +48,10 @@ impl RingAeadCipher {
let skey = make_skey(t, key, salt);
let cipher = RingAeadCipher::new_variant(t, &skey, &nonce, is_seal);
RingAeadCipher {
cipher: cipher,
cipher,
cipher_type: t,
key: skey,
nonce: nonce,
nonce,
}
}
+1 -1
View File
@@ -184,7 +184,7 @@ impl SodiumAeadCipher {
SodiumAeadCipher {
cipher_type: t,
key: skey,
nonce: nonce,
nonce,
}
}
+2 -2
View File
@@ -30,8 +30,8 @@ impl TableCipher {
let a = bufr.read_u64::<LittleEndian>().unwrap();
let mut table = [0u64; TABLE_SIZE];
for i in 0..TABLE_SIZE {
table[i] = i as u64;
for (i, element) in table.iter_mut().enumerate() {
*element = i as u64;
}
for i in 1..1024 {
+1 -1
View File
@@ -107,7 +107,7 @@ extern crate typenum;
extern crate url;
/// ShadowSocks version
pub const VERSION: &'static str = env!("CARGO_PKG_VERSION");
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub use self::{
config::{ClientConfig, Config, ConfigType, Mode, ServerAddr, ServerConfig},
+1 -2
View File
@@ -8,8 +8,7 @@ use tokio_io::IoFuture;
use futures::{self, stream::futures_unordered, Future, Stream};
use crate::plugin::Plugin;
use crate::relay::boxed_future;
use crate::{plugin::Plugin, relay::boxed_future};
#[cfg(unix)]
pub fn monitor_signal() -> impl Future<Item = (), Error = io::Error> + Send {
+2 -13
View File
@@ -41,17 +41,9 @@ pub enum PluginMode {
/// Plugin holder
#[derive(Debug)]
pub struct Plugin {
addr: ServerAddr,
process: Popen,
}
impl Plugin {
/// Get address of the plugin
pub fn addr(&self) -> &ServerAddr {
&self.addr
}
}
impl Drop for Plugin {
fn drop(&mut self) {
debug!("Killing Plugin {:?}", self.process);
@@ -74,12 +66,9 @@ pub fn launch_plugin(config: &mut Config, mode: PluginMode) -> io::Result<Vec<Pl
Err(err) => {
panic!("Failed to start plugin \"{}\", err: {}", c.plugin, err);
}
Ok(p) => {
Ok(process) => {
let svr_addr = ServerAddr::SocketAddr(local_addr);
plugins.push(Plugin {
addr: svr_addr.clone(),
process: p,
});
plugins.push(Plugin { process });
// Replace addr with plugin
svr_addr
+5 -3
View File
@@ -4,9 +4,11 @@ use std::io;
use futures::{self, Future};
use crate::config::Config;
use crate::context::{Context, SharedContext};
use crate::relay::udprelay::dns::run as run_udp;
use crate::{
config::Config,
context::{Context, SharedContext},
relay::udprelay::dns::run as run_udp,
};
/// DNS Relay server running under local environment.
pub fn run(config: Config) -> impl Future<Item = (), Error = io::Error> + Send {
+4 -2
View File
@@ -2,8 +2,10 @@
use std::sync::Arc;
use crate::config::{Config, ServerConfig};
use crate::relay::loadbalancing::server::LoadBalancer;
use crate::{
config::{Config, ServerConfig},
relay::loadbalancing::server::LoadBalancer,
};
#[derive(Clone)]
pub struct RoundRobin {
+13 -22
View File
@@ -28,7 +28,7 @@ pub use self::consts::{
use super::utils::{write_bytes, WriteBytes};
#[cfg_attr(rustfmt, rustfmt_skip)]
#[rustfmt::skip]
mod consts {
pub const SOCKS5_VERSION: u8 = 0x05;
@@ -69,7 +69,7 @@ pub enum Command {
impl Command {
#[inline]
#[cfg_attr(rustfmt, rustfmt_skip)]
#[rustfmt::skip]
fn as_u8(self) -> u8 {
match self {
Command::TcpConnect => consts::SOCKS5_CMD_TCP_CONNECT,
@@ -79,7 +79,7 @@ impl Command {
}
#[inline]
#[cfg_attr(rustfmt, rustfmt_skip)]
#[rustfmt::skip]
fn from_u8(code: u8) -> Option<Command> {
match code {
consts::SOCKS5_CMD_TCP_CONNECT => Some(Command::TcpConnect),
@@ -108,7 +108,7 @@ pub enum Reply {
impl Reply {
#[inline]
#[cfg_attr(rustfmt, rustfmt_skip)]
#[rustfmt::skip]
fn as_u8(self) -> u8 {
match self {
Reply::Succeeded => consts::SOCKS5_REPLY_SUCCEEDED,
@@ -125,7 +125,7 @@ impl Reply {
}
#[inline]
#[cfg_attr(rustfmt, rustfmt_skip)]
#[rustfmt::skip]
fn from_u8(code: u8) -> Reply {
match code {
consts::SOCKS5_REPLY_SUCCEEDED => Reply::Succeeded,
@@ -143,7 +143,7 @@ impl Reply {
}
impl fmt::Display for Reply {
#[cfg_attr(rustfmt, rustfmt_skip)]
#[rustfmt::skip]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Reply::Succeeded => write!(f, "Succeeded"),
@@ -172,7 +172,7 @@ pub struct Error {
impl Error {
pub fn new(reply: Reply, message: &str) -> Error {
Error {
reply: reply,
reply,
message: message.to_string(),
}
}
@@ -586,10 +586,7 @@ impl TcpRequestHeader {
})
.and_then(|(r, command)| {
Address::read_from(r).map(move |(conn, address)| {
let header = TcpRequestHeader {
command: command,
address: address,
};
let header = TcpRequestHeader { command, address };
(conn, header)
})
@@ -641,10 +638,7 @@ pub struct TcpResponseHeader {
impl TcpResponseHeader {
/// Creates a response header
pub fn new(reply: Reply, address: Address) -> TcpResponseHeader {
TcpResponseHeader {
reply: reply,
address: address,
}
TcpResponseHeader { reply, address }
}
/// Read from a reader
@@ -668,7 +662,7 @@ impl TcpResponseHeader {
Address::read_from(r).map(move |(r, address)| {
let rep = TcpResponseHeader {
reply: Reply::from_u8(reply_code),
address: address,
address,
};
(r, rep)
@@ -714,7 +708,7 @@ pub struct HandshakeRequest {
impl HandshakeRequest {
/// Creates a handshake request
pub fn new(methods: Vec<u8>) -> HandshakeRequest {
HandshakeRequest { methods: methods }
HandshakeRequest { methods }
}
/// Read from a reader
@@ -734,7 +728,7 @@ impl HandshakeRequest {
Ok((r, nmet))
})
.and_then(|(r, nmet)| read_exact(r, vec![0u8; nmet as usize]))
.and_then(|(r, methods)| Ok((r, HandshakeRequest { methods: methods })))
.and_then(|(r, methods)| Ok((r, HandshakeRequest { methods })))
}
/// Write to a writer
@@ -834,10 +828,7 @@ pub struct UdpAssociateHeader {
impl UdpAssociateHeader {
/// Creates a header
pub fn new(frag: u8, address: Address) -> UdpAssociateHeader {
UdpAssociateHeader {
frag: frag,
address: address,
}
UdpAssociateHeader { frag, address }
}
/// Read from a reader
+7 -5
View File
@@ -10,9 +10,11 @@ use std::{
time::Duration,
};
use crate::config::{ServerAddr, ServerConfig};
use crate::context::SharedContext;
use crate::relay::{boxed_future, dns_resolver::resolve};
use crate::{
config::{ServerAddr, ServerConfig},
context::SharedContext,
relay::{boxed_future, dns_resolver::resolve},
};
use futures::{future, Future, Stream};
use tokio::{self, net::UdpSocket, timer::Interval};
@@ -38,9 +40,9 @@ impl TcpServerContext {
let ctx = TcpServerContext {
tx: AtomicUsize::new(0),
rx: AtomicUsize::new(0),
context: context,
context,
stop_flag: stop_flag.clone(),
svr_cfg: svr_cfg,
svr_cfg,
};
let ctx = Arc::new(ctx);
+1 -1
View File
@@ -135,7 +135,7 @@ where
let buffer_size = w.buffer_size(&DUMMY_BUFFER);
EncryptedWriteAll::Writing {
writer: w,
buf: buf,
buf,
pos: 0,
enc_buf: BytesMut::with_capacity(buffer_size),
encrypted: false,
+7 -5
View File
@@ -9,10 +9,12 @@ use std::{
time::Duration,
};
use crate::config::{ConfigType, ServerAddr, ServerConfig};
use crate::context::SharedContext;
use crate::crypto::CipherCategory;
use crate::relay::{boxed_future, dns_resolver::resolve, socks5::Address};
use crate::{
config::{ConfigType, ServerAddr, ServerConfig},
context::SharedContext,
crypto::CipherCategory,
relay::{boxed_future, dns_resolver::resolve, socks5::Address},
};
use tokio::{
net::{tcp::ConnectFuture, TcpStream},
@@ -500,7 +502,7 @@ impl<R: Read> Future for IgnoreUntilEnd<R> {
/// Ignore all data from the reader
pub fn ignore_until_end<R: Read>(r: R) -> IgnoreUntilEnd<R> {
IgnoreUntilEnd::Pending { r: r, amt: 0 }
IgnoreUntilEnd::Pending { r, amt: 0 }
}
pub enum TimeoutFuture<T, F>
+6 -9
View File
@@ -83,11 +83,11 @@ impl TcpRelayClientHandshake {
try_timeout(fut, timeout)
})
.map(move |(r, addr)| TcpRelayClientPending {
r: r,
addr: addr,
r,
addr,
w: w_fut,
timeout: timeout,
svr_context: svr_context,
timeout,
svr_context,
})
})
})
@@ -160,7 +160,7 @@ where
TcpRelayClientConnected {
server: stream.split(),
client: client_pair,
timeout: timeout,
timeout,
}
})
}
@@ -218,10 +218,7 @@ fn handle_client(svr_context: SharedTcpServerContext, socket: TcpStream) -> impl
trace!("Got connection, addr: {}", addr);
trace!("Picked proxy server: {:?}", svr_context.svr_cfg());
let client = TcpRelayClientHandshake {
s: socket,
svr_context: svr_context,
};
let client = TcpRelayClientHandshake { s: socket, svr_context };
client
.handshake()
+1 -2
View File
@@ -13,8 +13,7 @@ use tokio_io::{
AsyncRead,
};
use crate::config::ServerConfig;
use crate::context::SharedContext;
use crate::{config::ServerConfig, context::SharedContext};
use crate::relay::{
boxed_future,
+2 -2
View File
@@ -5,8 +5,8 @@ use std::{
io::{self, BufRead, Read},
};
use bytes::{BufMut, BytesMut};
use crate::crypto::{new_stream, BoxStreamCipher, CipherType, CryptoMode, StreamCipher};
use bytes::{BufMut, BytesMut};
use tokio_io::{AsyncRead, AsyncWrite};
use super::{DecryptedRead, EncryptedWrite, BUFFER_SIZE};
@@ -35,7 +35,7 @@ where
DecryptedReader {
reader: r,
buffer: BytesMut::with_capacity(buffer_size),
cipher: cipher,
cipher,
pos: 0,
sent_final: false,
}
+1 -1
View File
@@ -50,7 +50,7 @@ where
CopyTimeout {
r: Some(r),
w: Some(w),
timeout: timeout,
timeout,
amt: 0,
timer: None,
buf: [0u8; BUFFER_SIZE],
+6 -4
View File
@@ -18,9 +18,11 @@ use super::{
SendDgramRc,
SharedUdpSocket,
};
use crate::config::{ServerAddr, ServerConfig};
use crate::context::SharedContext;
use crate::relay::{boxed_future, dns_resolver::resolve, socks5::Address};
use crate::{
config::{ServerAddr, ServerConfig},
context::SharedContext,
relay::{boxed_future, dns_resolver::resolve, socks5::Address},
};
struct PrettyRRData<'a> {
data: &'a RRData<'a>,
@@ -82,7 +84,7 @@ struct PrettyPacket<'a> {
impl<'a> PrettyPacket<'a> {
pub fn new(pkt: &'a Packet<'a>) -> PrettyPacket<'a> {
PrettyPacket { pkt: pkt }
PrettyPacket { pkt }
}
}
+9 -7
View File
@@ -11,13 +11,15 @@ use futures::{self, Future, Stream};
use tokio::{self, net::UdpSocket, util::FutureExt};
use crate::config::{ServerAddr, ServerConfig};
use crate::context::SharedContext;
use crate::relay::{
boxed_future,
dns_resolver::resolve,
loadbalancing::server::{LoadBalancer, RoundRobin},
socks5::{Address, UdpAssociateHeader},
use crate::{
config::{ServerAddr, ServerConfig},
context::SharedContext,
relay::{
boxed_future,
dns_resolver::resolve,
loadbalancing::server::{LoadBalancer, RoundRobin},
socks5::{Address, UdpAssociateHeader},
},
};
use super::{
+2 -6
View File
@@ -73,7 +73,7 @@ impl PacketStream {
/// Creates a new `PacketStream`
pub fn new(udp: SharedUdpSocket) -> PacketStream {
PacketStream {
udp: udp,
udp,
buf: [0u8; MAXIMUM_UDP_PAYLOAD_SIZE],
}
}
@@ -106,11 +106,7 @@ pub struct SendDgramRc<B: AsRef<[u8]>> {
impl<B: AsRef<[u8]>> SendDgramRc<B> {
pub fn new(udp: SharedUdpSocket, buf: B, addr: SocketAddr) -> SendDgramRc<B> {
SendDgramRc {
stat: SendDgramStat::Pending {
udp: udp,
buf: buf,
addr: addr,
},
stat: SendDgramStat::Pending { udp, buf, addr },
}
}
}
+5 -3
View File
@@ -11,9 +11,11 @@ use futures::{self, stream::futures_unordered, Future, Stream};
use tokio::{self, net::UdpSocket, util::FutureExt};
use crate::config::ServerConfig;
use crate::context::SharedContext;
use crate::relay::{boxed_future, dns_resolver::resolve, socks5::Address};
use crate::{
config::ServerConfig,
context::SharedContext,
relay::{boxed_future, dns_resolver::resolve, socks5::Address},
};
use super::{
crypto_io::{decrypt_payload, encrypt_payload},