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
use parking_lot::RwLock;
use std::net::IpAddr;
use std::net::SocketAddr;
use std::str::FromStr;
use std::sync::Arc;
use crate::device::{AllowedIps, Error};
use crate::noise::{Tunn, TunnResult};
use crate::device::udp::UDPSocket;
#[derive(Default, Debug)]
pub struct Endpoint {
pub addr: Option<SocketAddr>,
pub conn: Option<Arc<UDPSocket>>,
}
pub struct Peer {
pub(crate) tunnel: Box<Tunn>,
index: u32,
endpoint: RwLock<Endpoint>,
allowed_ips: AllowedIps<()>,
preshared_key: Option<[u8; 32]>,
}
#[derive(Debug)]
pub struct AllowedIP {
pub addr: IpAddr,
pub cidr: u8,
}
impl FromStr for AllowedIP {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let ip: Vec<&str> = s.split('/').collect();
if ip.len() != 2 {
return Err("Invalid IP format".to_owned());
}
let (addr, cidr) = (ip[0].parse::<IpAddr>(), ip[1].parse::<u8>());
match (addr, cidr) {
(Ok(addr @ IpAddr::V4(_)), Ok(cidr)) if cidr <= 32 => Ok(AllowedIP { addr, cidr }),
(Ok(addr @ IpAddr::V6(_)), Ok(cidr)) if cidr <= 128 => Ok(AllowedIP { addr, cidr }),
_ => Err("Invalid IP format".to_owned()),
}
}
}
impl Peer {
pub fn new(
tunnel: Box<Tunn>,
index: u32,
endpoint: Option<SocketAddr>,
allowed_ips: &[AllowedIP],
preshared_key: Option<[u8; 32]>,
) -> Peer {
Peer {
tunnel,
index,
endpoint: RwLock::new(Endpoint {
addr: endpoint,
conn: None,
}),
allowed_ips: allowed_ips.iter().map(|ip| (ip, ())).collect(),
preshared_key,
}
}
pub fn update_timers<'a>(&self, dst: &'a mut [u8]) -> TunnResult<'a> {
self.tunnel.update_timers(dst)
}
pub fn endpoint(&self) -> parking_lot::RwLockReadGuard<'_, Endpoint> {
self.endpoint.read()
}
pub fn shutdown_endpoint(&self) {
if let Some(conn) = self.endpoint.write().conn.take() {
tracing::info!("Disconnecting from endpoint");
conn.shutdown();
}
}
pub fn set_endpoint(&self, addr: SocketAddr) {
let mut endpoint = self.endpoint.write();
if endpoint.addr != Some(addr) {
if let Some(conn) = endpoint.conn.take() {
conn.shutdown();
}
*endpoint = Endpoint {
addr: Some(addr),
conn: None,
}
};
}
pub fn connect_endpoint(
&self,
port: u16,
fwmark: Option<u32>,
) -> Result<Arc<UDPSocket>, Error> {
let mut endpoint = self.endpoint.write();
if endpoint.conn.is_some() {
return Err(Error::Connect("Connected".to_owned()));
}
let udp_conn = Arc::new(match endpoint.addr {
Some(addr @ SocketAddr::V4(_)) => UDPSocket::new()?
.set_non_blocking()?
.set_reuse()?
.bind(port)?
.connect(&addr)?,
Some(addr @ SocketAddr::V6(_)) => UDPSocket::new6()?
.set_non_blocking()?
.set_reuse()?
.bind(port)?
.connect(&addr)?,
None => panic!("Attempt to connect to undefined endpoint"),
});
if let Some(fwmark) = fwmark {
udp_conn.set_fwmark(fwmark)?;
}
tracing::info!(
message="Connected endpoint",
port=port,
endpoint=?endpoint.addr.unwrap()
);
endpoint.conn = Some(Arc::clone(&udp_conn));
Ok(udp_conn)
}
pub fn is_allowed_ip<I: Into<IpAddr>>(&self, addr: I) -> bool {
self.allowed_ips.find(addr.into()).is_some()
}
pub fn allowed_ips(&self) -> impl Iterator<Item = (IpAddr, u8)> + '_ {
self.allowed_ips.iter().map(|(_, ip, cidr)| (ip, cidr))
}
pub fn time_since_last_handshake(&self) -> Option<std::time::Duration> {
self.tunnel.time_since_last_handshake()
}
pub fn persistent_keepalive(&self) -> Option<u16> {
self.tunnel.persistent_keepalive()
}
pub fn preshared_key(&self) -> Option<&[u8; 32]> {
self.preshared_key.as_ref()
}
pub fn index(&self) -> u32 {
self.index
}
}