aboutsummaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: 523bf562e307e2bcc578258bdb1766996999df3e (plain) (blame)
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
use std::fmt;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

use futures::future;
use futures::stream::{StreamExt, TryStreamExt};
use netlink_packet_route::address::Nla::Address;
use netlink_packet_route::rtnl::constants::{AF_INET, AF_INET6};
use rtnetlink::new_connection;
use tokio::runtime::Runtime;

#[derive(Debug)]
pub enum Error {
    RtNetlink(rtnetlink::Error),
    IoError(std::io::Error),
    LinkNotFound(Option<String>),
}

impl std::error::Error for Error {}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::RtNetlink(e) => write!(fmt, "rtnetlink error: {}", e),
            Self::IoError(e) => write!(fmt, "rtnetlink connection failed: {}", e),
            Self::LinkNotFound(filter) => match filter {
                Some(link) => write!(fmt, "link not found: {}", link),
                None => write!(fmt, "no links found"),
            },
        }
    }
}

impl From<rtnetlink::Error> for Error {
    fn from(e: rtnetlink::Error) -> Self {
        Self::RtNetlink(e)
    }
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Self::IoError(e)
    }
}

pub type Result<T> = std::result::Result<T, Error>;

pub fn addresses(link: String) -> Result<Vec<IpAddr>> {
    let rt = Runtime::new()?;

    rt.block_on(internal_addresses(Some(link)))
}

pub fn all_addresses() -> Result<Vec<IpAddr>> {
    let rt = Runtime::new()?;

    rt.block_on(internal_addresses(None))
}

async fn internal_addresses(filter: Option<String>) -> Result<Vec<IpAddr>> {
    let (connection, handle, _) = new_connection()?;
    tokio::spawn(connection);

    let mut links = handle.link().get();

    if let Some(link) = filter.clone() {
        links = links.match_name(link);
    }

    let mut links = links.execute();

    let mut num_links = 0;
    let mut link_addrs = Vec::new();

    while let Some(link) = links.try_next().await? {
        let addrs = handle
            .address()
            .get()
            .set_link_index_filter(link.header.index)
            .execute();

        let addrs = addrs
            .map_ok(|v| {
                if let Some(Address(bytes)) = v.nlas.first() {
                    match v.header.family as u16 {
                        AF_INET => {
                            let octets: [u8; 4] = (*bytes).clone().try_into().unwrap();
                            let ip = IpAddr::from(Ipv4Addr::from(octets));

                            Some(ip)
                        }
                        AF_INET6 => {
                            let octets: [u8; 16] = (*bytes).clone().try_into().unwrap();
                            let ip = IpAddr::from(Ipv6Addr::from(octets));

                            Some(ip)
                        }
                        _ => None,
                    }
                } else {
                    None
                }
            })
            .try_filter(|v| future::ready(v.is_some()))
            .filter_map(|v| future::ready(v.unwrap()));

        link_addrs.append(&mut addrs.collect::<Vec<IpAddr>>().await);

        num_links += 1;
    }

    if num_links > 0 {
        Ok(link_addrs)
    } else {
        Err(Error::LinkNotFound(filter))
    }
}