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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
|
use core::net::SocketAddr;
use dbus::{channel::MatchingReceiver, message::MatchRule};
use dbus_crossroads::{Context, Crossroads, MethodErr};
use defguard_wireguard_rs::{
host::Peer, key::Key, net::IpAddrMask, InterfaceConfiguration, WGApi, WireguardInterfaceApi,
};
use log::{debug, error, info, warn};
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeSet, HashMap},
fs::File,
io::{ErrorKind, Read, Write},
marker::PhantomData,
net::ToSocketAddrs,
ops::DerefMut,
str::FromStr,
sync::Arc,
time::SystemTime,
};
use thiserror::Error;
use tokio::{
net::TcpListener,
runtime::Builder,
signal::unix::{signal, SignalKind},
sync::{broadcast, RwLock},
task,
};
use xdg::BaseDirectories;
use crate::{daemon_dbus::*, daemon_network::*};
#[derive(Debug, Error)]
pub enum DaemonError {
#[error("{0}")]
Io(#[from] std::io::Error),
#[error("{0}")]
XdgBase(#[from] xdg::BaseDirectoriesError),
// TODO hier wärs nett zu unterscheiden was decoded wurde
#[error("{0}")]
Decoding(#[from] serde_json::Error),
#[error("{0}")]
IpMaskParse(#[from] defguard_wireguard_rs::net::IpAddrParseError),
#[error("{0}")]
WgInterfaceError(#[from] defguard_wireguard_rs::error::WireguardInterfaceError),
#[error("{0}")]
DbusError(#[from] dbus::Error),
}
#[derive(Serialize, Deserialize, Clone)]
pub enum Endpoint {
Ip(SocketAddr),
Domain(String, u16),
}
// subset of defguard_wireguard_rs::host::Peer, with hostname added
#[derive(Serialize, Deserialize)]
pub struct PeerConfig {
pub psk: Option<Key>,
pub ips: Vec<(IpAddrMask, Option<String>)>,
// if false: the hostnames are kept around for sharing, but we personally do not use them
pub use_hostnames: bool,
pub endpoint: Option<Endpoint>,
pub last_changed: SystemTime,
pub known_to: Vec<usize>,
pub mäsch_endpoint: SocketAddr,
}
fn default_wg_port() -> u16 {
51820
}
#[derive(Serialize, Deserialize)]
pub struct Network {
pub privkey: String,
// this really should be a different type, but this is what defguard takes...
pub address: String,
#[serde(default = "default_wg_port")]
pub listen_port: u16,
pub peers: HashMap<Key, PeerConfig>,
pub mäsch_port: u16,
}
#[derive(Serialize, Deserialize, Default)]
pub struct Config {
pub networks: HashMap<String, Network>,
}
// TODO das überschreibt änderungen an /etc/hosts während der runtime :(
pub struct State {
pub conf: Config,
pub nw_handles: HashMap<String, (WGApi, task::JoinHandle<()>)>,
pub hostfile: Option<(String, BTreeSet<String>)>,
}
impl Drop for State {
fn drop(&mut self) {
for (wg_api, _) in self.nw_handles.values() {
let _ = wg_api.remove_interface();
}
}
}
pub fn daemon() -> Result<(), DaemonError> {
let config_path = BaseDirectories::with_prefix("mäsch")?.place_state_file("daemon.json")?;
let config: Config = match File::open(config_path) {
Ok(f) => serde_json::from_reader(f)?,
Err(e) => match e.kind() {
ErrorKind::NotFound => Config::default(),
_ => Err(e)?,
},
};
info!("read config");
let hostfile = match File::open("/etc/hosts") {
Ok(mut f) => {
let mut r = String::new();
f.read_to_string(&mut r)?;
let seen_hostnames: BTreeSet<String> = r
.lines()
.map(|l| {
l.split_whitespace()
.take_while(|dom| dom.chars().next().unwrap() != '#')
.skip(1)
})
.flatten()
.map(|dom| dom.to_owned())
.collect();
Some((r, seen_hostnames))
}
Err(e) => {
warn!("failed to read /etc/hosts: {e}");
None
}
};
let state = Arc::new(RwLock::new(State {
conf: config,
nw_handles: HashMap::new(),
hostfile,
}));
let rt = Builder::new_current_thread().enable_all().build()?;
rt.block_on(run_networks(state))?;
Ok(())
}
async fn run_networks(state: Arc<RwLock<State>>) -> Result<(), DaemonError> {
let mut state_rw_guard = state.write().await;
let state_rw = state_rw_guard.deref_mut();
// load existing configurations
for (name, nw) in &state_rw.conf.networks {
let wg_api = add_network(
&mut state_rw.hostfile,
name.clone(),
nw.privkey.clone(),
nw.address.clone(),
nw.listen_port,
&nw.peers,
)
.await?;
let addr = IpAddrMask::from_str(&nw.address)?.ip;
let h = task::spawn(print_error(run_network(
state.clone(),
TcpListener::bind((addr, nw.mäsch_port)).await?,
name.clone(),
)));
state_rw.nw_handles.insert(name.clone(), (wg_api, h));
debug!("loaded configuration for {0}", name);
}
info!("loaded all existing configurations");
drop(state_rw_guard);
// set up dbus interface
let mut cr = Crossroads::new();
let state_ref = state.clone();
let if_token = cr.register("de.a.maesch", move |b| {
b.signal::<(String, String), _>("Proposal", ("network", "peer_data"));
b.method_with_cr_async(
"AddNetwork",
("name", "key", "ip", "listen_port", "maesch_port"),
("success",),
move |ctx, _, args: (String, String, String, u16, u16)| {
debug!("Received AddNetwork");
handle_add_network(ctx, state_ref.clone(), args)
},
);
});
cr.insert("/de/a/maesch", &[if_token], ());
// drive dbus interface
let (res, c) = dbus_tokio::connection::new_system_sync()?;
cr.set_async_support(Some((
c.clone(),
Box::new(|x| {
tokio::spawn(x);
}),
)));
let _ = tokio::spawn(print_error(async {
res.await;
Result::<!, &'static str>::Err("lost connection to dbus!")
}));
let receive_token = c.start_receive(
MatchRule::new_method_call(),
Box::new(move |msg, conn| {
cr.handle_message(msg, conn).unwrap();
true
}),
);
c.request_name("de.a.maesch", false, true, false).await?;
// wait for SIGTERM/SIGINT
let mut sigterm_fut = signal(SignalKind::terminate())?;
let mut sigint_fut = signal(SignalKind::interrupt())?;
let mut sighup_fut = signal(SignalKind::hangup())?;
tokio::select! {
_ = sigterm_fut.recv() => info!("Received SIGTERM"),
_ = sigint_fut.recv() => info!("Received SIGINT"),
_ = sighup_fut.recv() => info!("Received SIGHUP"),
};
// clean exit
c.stop_receive(receive_token);
let mut state_rw_guard = state.write().await;
for (_, (wg_api, h)) in state_rw_guard.nw_handles.drain() {
let _ = wg_api.remove_interface();
h.abort(); // could also join the handles... don't think that would do too much, though
}
Ok(())
}
pub async fn print_error<E: std::fmt::Display, O, F: std::future::Future<Output = Result<O, E>>>(
f: F,
) -> () {
match f.await {
Err(e) => error!("oh no: {e}"),
_ => (),
};
}
|