aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/builder.rs23
-rw-r--r--src/config.rs4
-rw-r--r--src/main.rs22
-rw-r--r--src/manager.rs70
-rw-r--r--src/model.rs37
-rw-r--r--src/model/ip.rs64
-rw-r--r--src/proto.rs8
-rw-r--r--src/wg.rs18
8 files changed, 131 insertions, 115 deletions
diff --git a/src/builder.rs b/src/builder.rs
index ba3843b..9fc2291 100644
--- a/src/builder.rs
+++ b/src/builder.rs
@@ -16,7 +16,7 @@ pub struct ConfigError {
impl ConfigError {
fn new(err: &'static str, s: &config::Source, p: &proto::Peer, important: bool) -> Self {
- ConfigError {
+ Self {
url: s.url.clone(),
peer: p.public_key.clone(),
important,
@@ -27,7 +27,7 @@ impl ConfigError {
impl error::Error for ConfigError {}
impl fmt::Display for ConfigError {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} [{}] from [{}]: {}",
@@ -53,7 +53,7 @@ pub struct ConfigBuilder<'a> {
impl<'a> ConfigBuilder<'a> {
#[inline]
pub fn new(public_key: model::Key, pc: &'a config::PeerConfig) -> Self {
- ConfigBuilder {
+ Self {
c: model::Config::default(),
err: vec![],
public_key,
@@ -96,15 +96,12 @@ impl<'a> ConfigBuilder<'a> {
let ent = if p.base == self.public_key {
insert_peer(&mut self.c, &mut self.err, s, &p.peer, |_| {})
+ } else if let Some(ent) = self.c.peers.get_mut(&p.base) {
+ ent
} else {
- match self.c.peers.get_mut(&p.base) {
- Some(ent) => ent,
- None => {
- self.err
- .push(ConfigError::new("Unknown base peer", s, &p.peer, true));
- return;
- }
- }
+ self.err
+ .push(ConfigError::new("Unknown base peer", s, &p.peer, true));
+ return;
};
add_peer(&mut self.err, ent, s, &p.peer)
}
@@ -146,7 +143,7 @@ fn add_peer(
let mut added = false;
let mut removed = false;
- for i in p.ipv4.iter() {
+ for i in &p.ipv4 {
if s.ipv4.contains(i) {
ent.ipv4.push(*i);
added = true;
@@ -154,7 +151,7 @@ fn add_peer(
removed = true;
}
}
- for i in p.ipv6.iter() {
+ for i in &p.ipv6 {
if s.ipv6.contains(i) {
ent.ipv6.push(*i);
added = true;
diff --git a/src/config.rs b/src/config.rs
index 6eb3761..bfa6342 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -3,9 +3,9 @@
// See COPYING.
use crate::model::{Ipv4Set, Ipv6Set, Key};
-use std::path::PathBuf;
-use std::collections::HashMap;
use serde_derive;
+use std::collections::HashMap;
+use std::path::PathBuf;
#[serde(deny_unknown_fields)]
#[derive(serde_derive::Serialize, serde_derive::Deserialize, Clone, PartialEq, Eq, Debug)]
diff --git a/src/main.rs b/src/main.rs
index dfadaf4..d56ba39 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -2,20 +2,22 @@
//
// See COPYING.
+#![deny(rust_2018_idioms)]
+
#[macro_use]
extern crate arrayref;
-use std::{env, fs, io, process, thread};
-use std::time::Instant;
use std::ffi::{OsStr, OsString};
+use std::time::Instant;
+use std::{env, fs, io, process, thread};
use toml;
mod builder;
-mod model;
mod config;
+mod manager;
+mod model;
mod proto;
mod wg;
-mod manager;
fn load_config(path: &OsStr) -> io::Result<config::Config> {
let mut data = String::new();
@@ -30,13 +32,19 @@ fn load_config(path: &OsStr) -> io::Result<config::Config> {
}
fn usage(argv0: &str) -> i32 {
- eprintln!("<1>Invalid arguments. See `{} --help` for more information", argv0);
+ eprintln!(
+ "<1>Invalid arguments. See `{} --help` for more information",
+ argv0
+ );
1
}
fn help(argv0: &str) -> i32 {
println!("Usage:");
- println!(" {} IFNAME CONFIG - run daemon on iterface", argv0);
+ println!(
+ " {} IFNAME CONFIG - run daemon on iterface",
+ argv0
+ );
println!(" {} --check-source PATH - validate source JSON", argv0);
1
}
@@ -113,7 +121,7 @@ fn run_check_source(argv0: String, args: Vec<OsString>) -> i32 {
}
}
-fn main() -> () {
+fn main() {
let mut iter_args = env::args_os();
let argv0 = iter_args.next().unwrap().to_string_lossy().into_owned();
diff --git a/src/manager.rs b/src/manager.rs
index 20d7f50..3e7dc5f 100644
--- a/src/manager.rs
+++ b/src/manager.rs
@@ -2,11 +2,11 @@
//
// See COPYING.
-use std::{io, fs};
use crate::{builder, config, model, proto, wg};
-use std::time::{Duration, Instant, SystemTime};
use std::ffi::{OsStr, OsString};
use std::path::PathBuf;
+use std::time::{Duration, Instant, SystemTime};
+use std::{fs, io};
struct Source {
name: String,
@@ -33,11 +33,10 @@ impl Updater {
}
fn cache_update(&self, src: &Source) -> io::Result<bool> {
- let path = match self.cache_path(src) {
- Some(path) => path,
- None => {
- return Ok(false);
- }
+ let path = if let Some(path) = match self.cache_path(src) {
+ path
+ } else {
+ return Ok(false);
};
let mut tmp_path = OsString::from(path.clone());
@@ -64,18 +63,16 @@ impl Updater {
}
fn cache_load(&self, src: &mut Source) -> bool {
- let path = match self.cache_path(src) {
- Some(path) => path,
- None => {
- return false;
- }
+ let path = if let Some(path) = match self.cache_path(src) {
+ path
+ } else {
+ return false;
};
- let mut file = match fs::File::open(&path) {
- Ok(file) => file,
- Err(_) => {
- return false;
- }
+ let mut file = if let Some(file) = fs::File::open(&path) {
+ file
+ } else {
+ return false;
};
let mut data = Vec::new();
@@ -121,13 +118,17 @@ impl Updater {
Err(r) => r,
};
- let b = src.backoff.unwrap_or_else(|| Duration::from_secs(10).min(refresh / 10));
+ let b = src
+ .backoff
+ .unwrap_or_else(|| Duration::from_secs(10).min(refresh / 10));
src.next_update = now + b;
src.backoff = Some((b + b / 3).min(refresh / 3));
- eprintln!("<3>Failed to update [{}], retrying after {:.1?}: {}", &src.config.url, b, &r);
+ eprintln!(
+ "<3>Failed to update [{}], retrying after {:.1?}: {}",
+ &src.config.url, b, &r
+ );
(false, now)
}
-
}
pub struct Manager {
@@ -139,8 +140,8 @@ pub struct Manager {
}
impl Manager {
- pub fn new(ifname: OsString, c: config::Config) -> io::Result<Manager> {
- let mut m = Manager {
+ pub fn new(ifname: OsString, c: config::Config) -> io::Result<Self> {
+ let mut m = Self {
dev: wg::Device::new(ifname)?,
peer_config: c.peer_config,
sources: vec![],
@@ -151,7 +152,7 @@ impl Manager {
},
};
- for (name, cfg) in c.sources.into_iter() {
+ for (name, cfg) in c.sources {
m.add_source(name, cfg)?;
}
@@ -188,7 +189,10 @@ impl Manager {
if self.updater.update(s).0 {
return Ok(());
}
- Err(io::Error::new(io::ErrorKind::Other, format!("Failed to update required source [{}]", &s.config.url)))
+ Err(io::Error::new(
+ io::ErrorKind::Other,
+ format!("Failed to update required source [{}]", &s.config.url),
+ ))
}
fn make_config(
@@ -198,8 +202,10 @@ impl Manager {
) -> (model::Config, Vec<builder::ConfigError>, SystemTime) {
let mut t_cfg = ts + Duration::from_secs(1 << 30);
let mut sources: Vec<(&Source, &proto::SourceConfig)> = vec![];
- for src in self.sources.iter() {
- let sc = src.data.next
+ for src in &self.sources {
+ let sc = src
+ .data
+ .next
.as_ref()
.and_then(|next| {
if ts >= next.update_at {
@@ -215,14 +221,14 @@ impl Manager {
let mut cfg = builder::ConfigBuilder::new(public_key, &self.peer_config);
- for (src, sc) in sources.iter() {
- for peer in sc.servers.iter() {
+ for (src, sc) in &sources {
+ for peer in &sc.servers {
cfg.add_server(&src.config, peer);
}
}
- for (src, sc) in sources.iter() {
- for peer in sc.road_warriors.iter() {
+ for (src, sc) in &sources {
+ for peer in &sc.road_warriors {
cfg.add_road_warrior(&src.config, peer);
}
}
@@ -236,7 +242,7 @@ impl Manager {
let mut now = Instant::now();
let mut t_refresh = now + refresh;
- for src in self.sources.iter_mut() {
+ for src in &mut self.sources {
if now >= src.next_update {
now = self.updater.update(src).1;
}
@@ -260,7 +266,7 @@ impl Manager {
if config != self.current {
eprintln!("<5>Applying configuration update");
- for err in errors.iter() {
+ for err in &errors {
eprintln!("<{}>{}", if err.important { '4' } else { '5' }, err);
}
self.dev.apply_diff(&self.current, &config)?;
diff --git a/src/model.rs b/src/model.rs
index bc800b2..bb4a93b 100644
--- a/src/model.rs
+++ b/src/model.rs
@@ -16,8 +16,8 @@ pub type KeyParseError = base64::DecodeError;
pub struct Key([u8; 32]);
impl Key {
- pub fn from_bytes(s: &[u8]) -> Result<Key, KeyParseError> {
- let mut v = Key([0u8; 32]);
+ pub fn from_bytes(s: &[u8]) -> Result<Self, KeyParseError> {
+ let mut v = Self([0; 32]);
let l = base64::decode_config_slice(s, base64::STANDARD, &mut v.0)?;
if l != v.0.len() {
return Err(base64::DecodeError::InvalidLength);
@@ -28,7 +28,7 @@ impl Key {
impl fmt::Display for Key {
#[inline]
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
@@ -40,8 +40,8 @@ impl fmt::Display for Key {
impl FromStr for Key {
type Err = KeyParseError;
#[inline]
- fn from_str(s: &str) -> Result<Key, base64::DecodeError> {
- Key::from_bytes(s.as_bytes())
+ fn from_str(s: &str) -> Result<Self, base64::DecodeError> {
+ Self::from_bytes(s.as_bytes())
}
}
@@ -63,7 +63,7 @@ impl<'de> serde::Deserialize<'de> for Key {
type Value = Key;
#[inline]
- fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("WireGuard key")
}
@@ -74,7 +74,7 @@ impl<'de> serde::Deserialize<'de> for Key {
}
de.deserialize_str(KeyVisitor)
} else {
- serde::Deserialize::deserialize(de).map(Key)
+ serde::Deserialize::deserialize(de).map(Self)
}
}
}
@@ -109,7 +109,7 @@ impl Endpoint {
}
impl fmt::Display for Endpoint {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(ipv4) = self.ipv4_address() {
write!(f, "{}:", ipv4)?;
} else {
@@ -121,11 +121,11 @@ impl fmt::Display for Endpoint {
impl FromStr for Endpoint {
type Err = NetParseError;
- fn from_str(s: &str) -> Result<Endpoint, NetParseError> {
+ fn from_str(s: &str) -> Result<Self, NetParseError> {
use std::net;
net::SocketAddr::from_str(s)
.map_err(|_| NetParseError)
- .map(|v| Endpoint {
+ .map(|v| Self {
address: match v.ip() {
net::IpAddr::V4(a) => a.to_ipv6_mapped(),
net::IpAddr::V6(a) => a,
@@ -140,7 +140,7 @@ impl serde::Serialize for Endpoint {
if ser.is_human_readable() {
ser.collect_str(self)
} else {
- let mut buf = [0u8; 16 + 2];
+ let mut buf = [0_u8; 16 + 2];
let (buf_addr, buf_port) = mut_array_refs![&mut buf, 16, 2];
*buf_addr = self.address.octets();
*buf_port = self.port.to_be_bytes();
@@ -157,7 +157,7 @@ impl<'de> serde::Deserialize<'de> for Endpoint {
type Value = Endpoint;
#[inline]
- fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("IP:port")
}
@@ -170,7 +170,7 @@ impl<'de> serde::Deserialize<'de> for Endpoint {
} else {
let buf = <[u8; 16 + 2] as serde::Deserialize>::deserialize(de)?;
let (buf_addr, buf_port) = array_refs![&buf, 16, 2];
- Ok(Endpoint {
+ Ok(Self {
address: (*buf_addr).into(),
port: u16::from_be_bytes(*buf_port),
})
@@ -194,8 +194,15 @@ pub struct Config {
impl Default for Config {
#[inline]
- fn default() -> Config {
- Config {
+ fn default() -> Self {
+ Self::empty()
+ }
+}
+
+impl Config {
+ #[inline]
+ pub fn empty() -> Self {
+ Self {
peers: HashMap::new(),
}
}
diff --git a/src/model/ip.rs b/src/model/ip.rs
index 0ada314..4e284de 100644
--- a/src/model/ip.rs
+++ b/src/model/ip.rs
@@ -14,7 +14,7 @@ pub struct NetParseError;
impl error::Error for NetParseError {}
impl fmt::Display for NetParseError {
#[inline]
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Invalid address")
}
}
@@ -30,7 +30,7 @@ macro_rules! per_proto {
impl $nett {
const BITS: u8 = $bytes * 8;
- pub fn contains(&self, other: &$nett) -> bool {
+ pub fn contains(&self, other: &Self) -> bool {
if self.prefix_len > other.prefix_len {
return false;
}
@@ -50,18 +50,18 @@ macro_rules! per_proto {
impl fmt::Display for $nett {
#[inline]
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}/{}", self.address, self.prefix_len)
}
}
impl FromStr for $nett {
type Err = NetParseError;
- fn from_str(s: &str) -> Result<$nett, NetParseError> {
+ fn from_str(s: &str) -> Result<Self, NetParseError> {
let (addr, pfx) = pfx_split(s)?;
let addr = $addrt::from_str(addr).map_err(|_| NetParseError)?;
- let r = $nett {
+ let r = Self {
address: addr,
prefix_len: pfx,
};
@@ -77,7 +77,7 @@ macro_rules! per_proto {
if ser.is_human_readable() {
ser.collect_str(self)
} else {
- let mut buf = [0u8; $bytes + 1];
+ let mut buf = [0_u8; $bytes + 1];
*array_mut_ref![&mut buf, 0, $bytes] = self.address.octets();
buf[$bytes] = self.prefix_len;
ser.serialize_bytes(&buf)
@@ -93,7 +93,7 @@ macro_rules! per_proto {
type Value = $nett;
#[inline]
- fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str($expecting)
}
@@ -105,7 +105,7 @@ macro_rules! per_proto {
de.deserialize_str(NetVisitor)
} else {
let buf = <[u8; $bytes + 1] as serde::Deserialize>::deserialize(de)?;
- let r = $nett {
+ let r = Self {
address: (*array_ref![&buf, 0, $bytes]).into(),
prefix_len: buf[$bytes],
};
@@ -125,14 +125,14 @@ macro_rules! per_proto {
impl Default for $sett {
#[inline]
fn default() -> Self {
- $sett::new()
+ Self::new()
}
}
impl $sett {
#[inline]
pub fn new() -> Self {
- $sett { nets: vec![] }
+ Self { nets: vec![] }
}
#[inline]
@@ -147,11 +147,10 @@ macro_rules! per_proto {
}
pub fn insert(&mut self, mut net: $nett) {
- let mut i = match self.nets.binary_search(&net) {
- Err(i) => i,
- Ok(_) => {
- return;
- }
+ let mut i = if let Err(i) = self.nets.binary_search(&net) {
+ i
+ } else {
+ return;
};
let mut j = i;
if i != 0 && self.nets[i - 1].contains(&net) {
@@ -188,7 +187,7 @@ macro_rules! per_proto {
}
#[inline]
- pub fn iter(&self) -> std::slice::Iter<$nett> {
+ pub fn iter(&self) -> std::slice::Iter<'_, $nett> {
self.nets.iter()
}
}
@@ -205,8 +204,8 @@ macro_rules! per_proto {
impl FromIterator<$nett> for $sett {
#[inline]
- fn from_iter<I: IntoIterator<Item = $nett>>(it: I) -> $sett {
- let mut r = $sett::new();
+ fn from_iter<I: IntoIterator<Item = $nett>>(it: I) -> Self {
+ let mut r = Self::new();
for net in it {
r.insert(net);
}
@@ -216,27 +215,27 @@ macro_rules! per_proto {
impl<'a> From<$nett> for $sett {
#[inline]
- fn from(v: $nett) -> $sett {
- $sett { nets: vec![v] }
+ fn from(v: $nett) -> Self {
+ Self { nets: vec![v] }
}
}
impl<'a> From<[$nett; 1]> for $sett {
#[inline]
- fn from(v: [$nett; 1]) -> $sett {
- $sett { nets: vec![v[0]] }
+ fn from(v: [$nett; 1]) -> Self {
+ Self { nets: vec![v[0]] }
}
}
impl From<$sett> for Vec<$nett> {
- fn from(v: $sett) -> Vec<$nett> {
+ fn from(v: $sett) -> Self {
v.nets
}
}
impl From<Vec<$nett>> for $sett {
- fn from(nets: Vec<$nett>) -> $sett {
- let mut s = $sett { nets };
+ fn from(nets: Vec<$nett>) -> Self {
+ let mut s = Self { nets };
let len = s.nets.len();
if len == 0 {
return s;
@@ -264,14 +263,14 @@ macro_rules! per_proto {
impl<'a> From<&'a [$nett]> for $sett {
#[inline]
- fn from(nets: &'a [$nett]) -> $sett {
+ fn from(nets: &'a [$nett]) -> Self {
Vec::from(nets).into()
}
}
impl<'a> From<&'a mut [$nett]> for $sett {
#[inline]
- fn from(nets: &'a mut [$nett]) -> $sett {
+ fn from(nets: &'a mut [$nett]) -> Self {
Vec::from(nets).into()
}
}
@@ -286,7 +285,7 @@ macro_rules! per_proto {
impl<'de> serde::Deserialize<'de> for $sett {
#[inline]
fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
- <Vec<$nett> as serde::Deserialize>::deserialize(de).map($sett::from)
+ <Vec<$nett> as serde::Deserialize>::deserialize(de).map(Self::from)
}
}
};
@@ -332,11 +331,10 @@ impl Ipv6Net {
}
fn pfx_split(s: &str) -> Result<(&str, u8), NetParseError> {
- let i = match s.find('/') {
- Some(i) => i,
- None => {
- return Err(NetParseError);
- }
+ let i = if let Some(i) = s.find('/') {
+ i
+ } else {
+ return Err(NetParseError);
};
let (addr, pfx) = s.split_at(i);
let pfx = u8::from_str(&pfx[1..]).map_err(|_| NetParseError)?;
diff --git a/src/proto.rs b/src/proto.rs
index 9c98fff..d74a05f 100644
--- a/src/proto.rs
+++ b/src/proto.rs
@@ -58,8 +58,8 @@ pub struct Source {
}
impl Source {
- pub fn empty() -> Source {
- Source {
+ pub fn empty() -> Self {
+ Self {
config: SourceConfig {
servers: vec![],
road_warriors: vec![],
@@ -80,7 +80,7 @@ mod serde_utc {
if ser.is_human_readable() {
ser.serialize_str(&t.to_rfc3339_opts(SecondsFormat::Nanos, true))
} else {
- let mut buf = [0u8; 12];
+ let mut buf = [0_u8; 12];
let (buf_secs, buf_nanos) = mut_array_refs![&mut buf, 8, 4];
*buf_secs = t.timestamp().to_be_bytes();
*buf_nanos = t.timestamp_subsec_nanos().to_be_bytes();
@@ -94,7 +94,7 @@ mod serde_utc {
impl<'de> serde::de::Visitor<'de> for RFC3339Visitor {
type Value = SystemTime;
- fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("RFC3339 time")
}
diff --git a/src/wg.rs b/src/wg.rs
index 745c7b4..06188b6 100644
--- a/src/wg.rs
+++ b/src/wg.rs
@@ -14,7 +14,7 @@ pub struct Device {
impl Device {
#[inline]
pub fn new(ifname: OsString) -> io::Result<Self> {
- let dev = Device { ifname };
+ let dev = Self { ifname };
let _ = dev.get_public_key()?;
Ok(dev)
}
@@ -33,7 +33,7 @@ impl Device {
}
pub fn get_public_key(&self) -> io::Result<model::Key> {
- let mut proc = Device::wg_command();
+ let mut proc = Self::wg_command();
proc.stdin(Stdio::null());
proc.stdout(Stdio::piped());
proc.arg("show");
@@ -54,14 +54,14 @@ impl Device {
}
pub fn apply_diff(&mut self, old: &model::Config, new: &model::Config) -> io::Result<()> {
- let mut proc = Device::wg_command();
+ let mut proc = Self::wg_command();
proc.stdin(Stdio::piped());
proc.arg("set");
proc.arg(&self.ifname);
let mut psks = String::new();
- for (pubkey, conf) in new.peers.iter() {
+ for (pubkey, conf) in &new.peers {
let old_endpoint;
if let Some(old_peer) = old.peers.get(pubkey) {
if *old_peer == *conf {
@@ -73,12 +73,12 @@ impl Device {
}
proc.arg("peer");
- proc.arg(format!("{}", pubkey));
+ proc.arg(pubkey.to_string());
if old_endpoint != conf.endpoint {
if let Some(ref endpoint) = conf.endpoint {
proc.arg("endpoint");
- proc.arg(format!("{}", endpoint));
+ proc.arg(endpoint.to_string());
}
}
@@ -94,13 +94,13 @@ impl Device {
let mut ips = String::new();
{
use std::fmt::Write;
- for ip in conf.ipv4.iter() {
+ for ip in &conf.ipv4 {
if !ips.is_empty() {
ips.push(',');
}
write!(ips, "{}", ip).unwrap();
}
- for ip in conf.ipv6.iter() {
+ for ip in &conf.ipv6 {
if !ips.is_empty() {
ips.push(',');
}
@@ -117,7 +117,7 @@ impl Device {
continue;
}
proc.arg("peer");
- proc.arg(format!("{}", pubkey));
+ proc.arg(pubkey.to_string());
proc.arg("remove");
}