wg_netmanager/
wg_dev.rs

1use std::collections::HashMap;
2use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr};
3
4use ipnet::Ipv4Net;
5
6use crate::error::*;
7
8pub trait WireguardDevice {
9    fn check_device(&self) -> BoxResult<bool>;
10    fn create_device(&self) -> BoxResult<()>;
11    fn take_down_device(&self) -> BoxResult<()>;
12    fn set_ip(&mut self, ip: &Ipv4Addr, subnet: &Ipv4Net) -> BoxResult<()>;
13    fn add_route(&self, host: Ipv4Addr, gateway: Option<Ipv4Addr>) -> BoxResult<()>;
14    fn replace_route(&self, host: Ipv4Addr, gateway: Option<Ipv4Addr>) -> BoxResult<()>;
15    fn del_route(&self, host: Ipv4Addr, gateway: Option<Ipv4Addr>) -> BoxResult<()>;
16    fn set_conf(&self, conf: &str) -> BoxResult<()>;
17    fn sync_conf(&self, conf: &str) -> BoxResult<()>;
18    fn flush_all(&self) -> BoxResult<()>;
19    fn retrieve_conf(&self) -> BoxResult<HashMap<String, SocketAddr>>;
20    fn create_key_pair(&self) -> BoxResult<(String, String)>;
21}
22
23pub fn map_to_ipv6(ipv4: &Ipv4Addr) -> Ipv6Addr {
24    let mut segments = ipv4.to_ipv6_mapped().segments();
25    segments[0] = 0xfd00;
26    Ipv6Addr::from(segments)
27}
28
29// wireguard returns an address like this and the %-part has to be removed:[fe80::3bac:744c:f807:a5a2%br-wan]:50001
30pub fn v6_strip_interface(sa: &str) -> BoxResult<String> {
31    let flds = sa.split('%').collect::<Vec<_>>();
32    if flds.len() == 1 {
33        Ok(flds[0].to_string())
34    } else if flds.len() == 2 {
35        let rem = flds[1].split(']').collect::<Vec<_>>();
36        if rem.len() == 2 {
37            Ok(format!("{}]{}", flds[0], rem[1]))
38        } else {
39            Err(format!("invalid address: {}", sa).into())
40        }
41    } else {
42        Err(format!("invalid address: {}", sa).into())
43    }
44}