wireguard_uapi/linux/set/
allowed_ip.rs

1use crate::linux::attr::NLA_F_NESTED;
2use crate::linux::attr::{NlaNested, WgAllowedIpAttribute};
3use crate::linux::consts::NLA_NETWORK_ORDER;
4use neli::err::NlError;
5use neli::genl::Nlattr;
6use neli::types::Buffer;
7use std::convert::TryFrom;
8use std::net::IpAddr;
9
10#[derive(Debug, Clone)]
11pub struct AllowedIp<'a> {
12    pub ipaddr: &'a IpAddr,
13    pub cidr_mask: Option<u8>,
14}
15
16impl<'a> AllowedIp<'a> {
17    pub fn from_ipaddr(ipaddr: &'a IpAddr) -> Self {
18        Self {
19            ipaddr,
20            cidr_mask: None,
21        }
22    }
23}
24
25impl TryFrom<&AllowedIp<'_>> for Nlattr<NlaNested, Buffer> {
26    type Error = NlError;
27
28    fn try_from(allowed_ip: &AllowedIp) -> Result<Self, Self::Error> {
29        let mut nested =
30            Nlattr::new::<Vec<u8>>(false, false, NlaNested::Unspec | NLA_F_NESTED, vec![])?;
31
32        let family = match allowed_ip.ipaddr {
33            IpAddr::V4(_) => libc::AF_INET as u16,
34            IpAddr::V6(_) => libc::AF_INET6 as u16,
35        };
36        nested.add_nested_attribute(&Nlattr::new(
37            false,
38            NLA_NETWORK_ORDER,
39            WgAllowedIpAttribute::Family,
40            &family.to_ne_bytes()[..],
41        )?)?;
42
43        let ipaddr = match allowed_ip.ipaddr {
44            IpAddr::V4(addr) => addr.octets().to_vec(),
45            IpAddr::V6(addr) => addr.octets().to_vec(),
46        };
47        nested.add_nested_attribute(&Nlattr::new(
48            false,
49            NLA_NETWORK_ORDER,
50            WgAllowedIpAttribute::IpAddr,
51            ipaddr,
52        )?)?;
53
54        let cidr_mask = allowed_ip.cidr_mask.unwrap_or(match allowed_ip.ipaddr {
55            IpAddr::V4(_) => 32,
56            IpAddr::V6(_) => 128,
57        });
58        nested.add_nested_attribute(&Nlattr::new(
59            false,
60            NLA_NETWORK_ORDER,
61            WgAllowedIpAttribute::CidrMask,
62            &cidr_mask.to_ne_bytes()[..],
63        )?)?;
64
65        Ok(nested)
66    }
67}