1use std::collections::{HashMap, HashSet};
2use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr};
3use std::time::Duration;
4
5use super::Cidr;
6use crate::noise::crypto::LocalStaticSecret;
7
8#[derive(Clone)]
21pub struct DeviceConfig {
22 pub private_key: [u8; 32],
23 pub listen_addrs: (Ipv4Addr, Ipv6Addr),
24 pub listen_port: u16,
25 pub fwmark: u32,
26 pub peers: HashMap<[u8; 32], PeerConfig>,
27}
28
29#[derive(Default, Clone)]
31pub struct PeerConfig {
32 pub public_key: [u8; 32],
33 pub allowed_ips: HashSet<Cidr>,
34 pub endpoint: Option<SocketAddr>,
35 pub preshared_key: Option<[u8; 32]>,
36 pub persistent_keepalive: Option<Duration>,
37}
38
39impl DeviceConfig {
40 #[inline(always)]
41 pub fn private_key(mut self, key: [u8; 32]) -> Self {
42 self.private_key = key;
43 self
44 }
45
46 #[inline(always)]
47 pub fn listen_addr_v4(mut self, addr: Ipv4Addr) -> Self {
48 self.listen_addrs.0 = addr;
49 self
50 }
51
52 #[inline(always)]
53 pub fn listen_addr_v6(mut self, addr: Ipv6Addr) -> Self {
54 self.listen_addrs.1 = addr;
55 self
56 }
57
58 #[inline(always)]
59 pub fn listen_port(mut self, port: u16) -> Self {
60 self.listen_port = port;
61 self
62 }
63
64 #[inline(always)]
65 pub fn peer(mut self, peer: PeerConfig) -> Self {
66 self.peers.insert(peer.public_key, peer);
67 self
68 }
69
70 #[inline(always)]
71 pub fn local_secret(&self) -> LocalStaticSecret {
72 LocalStaticSecret::new(self.private_key)
73 }
74}
75
76impl Default for DeviceConfig {
77 fn default() -> Self {
78 Self {
79 private_key: [0; 32],
80 listen_addrs: (Ipv4Addr::UNSPECIFIED, Ipv6Addr::UNSPECIFIED),
81 listen_port: 0,
82 fwmark: 0,
83 peers: HashMap::new(),
84 }
85 }
86}
87
88impl PeerConfig {
89 #[inline(always)]
90 pub fn public_key(mut self, key: [u8; 32]) -> Self {
91 self.public_key = key;
92 self
93 }
94
95 #[inline(always)]
96 pub fn allowed_ips<T: Into<Cidr>>(mut self, ips: impl IntoIterator<Item = T>) -> Self {
97 self.allowed_ips = ips.into_iter().map(|i| i.into()).collect();
98 self
99 }
100
101 #[inline(always)]
102 pub fn allowed_ip<I: Into<Cidr>>(mut self, ip: I) -> Self {
103 self.allowed_ips.insert(ip.into());
104 self
105 }
106
107 #[inline(always)]
108 pub fn endpoint(mut self, endpoint: SocketAddr) -> Self {
109 self.endpoint = Some(endpoint);
110 self
111 }
112
113 #[inline(always)]
114 pub fn preshared_key(mut self, key: [u8; 32]) -> Self {
115 self.preshared_key = Some(key);
116 self
117 }
118
119 #[inline(always)]
120 pub fn persistent_keepalive(mut self, interval: Duration) -> Self {
121 self.persistent_keepalive = Some(interval);
122 self
123 }
124}