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
use futures::channel::mpsc::UnboundedReceiver;
use futures::{
    stream::{StreamExt, TryStreamExt},
    Stream,
};
use netlink_packet_core::{NetlinkMessage, NetlinkPayload};
use netlink_packet_route::{
    rtnl::{address::Nla, RtnlMessage::*},
    AddressMessage, RtnlMessage,
};
use netlink_proto::{
    sys::{AsyncSocket, SocketAddr},
    Connection as RtConnection,
};
use rtnetlink::{constants::*, new_connection, AddressHandle, Handle as RtHandle};
use std::io::{Error, ErrorKind, Result};
use std::net::Ipv4Addr;

/// A retrieved address entry.
#[derive(Debug, Clone)]
pub struct Address {
    addr: Ipv4Addr,
    label: String,
}

impl Address {
    /// Gets the IPv4 address.
    pub fn addr(&self) -> &Ipv4Addr {
        &self.addr
    }

    /// Gets the label of the interface.
    pub fn label(&self) -> &str {
        &self.label
    }
}

impl TryFrom<AddressMessage> for Address {
    type Error = Error;

    fn try_from(am: AddressMessage) -> Result<Address> {
        let mut the_addr = None;
        let mut the_label = None;
        for nla in am.nlas {
            match nla {
                Nla::Address(a) => {
                    let c: [u8; 4] = match a.try_into() {
                        Ok(c) => c,
                        _ => continue,
                    };
                    let addr = Ipv4Addr::from(c);
                    if let Some(label) = the_label {
                        return Ok(Address { addr, label });
                    }
                    the_addr = Some(addr);
                }
                Nla::Label(label) => {
                    if let Some(addr) = the_addr {
                        return Ok(Address { addr, label });
                    }
                    the_label = Some(label);
                }
                _ => {}
            }
        }
        Err(Error::from(ErrorKind::NotFound))
    }
}

/// A handle to get current local addresses.
#[derive(Debug, Clone)]
pub struct Addresses {
    handle: RtHandle,
}

impl Addresses {
    /// Streams the current local addresses.
    pub fn stream(self) -> impl Stream<Item = Address> {
        let inner = AddressHandle::new(self.handle)
            .get()
            .execute()
            .into_stream();
        inner.filter_map(|item| async move { item.ok().and_then(|am| am.try_into().ok()) })
    }
}

/// A message from the monitor, denoting a new or deleted address.
#[derive(Debug, Clone)]
pub struct Message {
    addr: Address,
    new: bool,
}

impl Message {
    fn new(addr: Address, new: bool) -> Self {
        Message { addr, new }
    }

    /// Gets the address.
    pub fn addr(&self) -> &Address {
        &self.addr
    }

    /// Checks whether the address is new or deleted.
    pub fn is_new(&self) -> bool {
        self.new
    }
}

impl TryFrom<RtnlMessage> for Message {
    type Error = Error;

    fn try_from(item: RtnlMessage) -> Result<Message> {
        Ok(match item {
            NewAddress(a) => Message::new(a.try_into()?, true),
            DelAddress(a) => Message::new(a.try_into()?, false),
            _ => {
                return Err(Error::from(ErrorKind::InvalidData));
            }
        })
    }
}

impl TryFrom<NetlinkMessage<RtnlMessage>> for Message {
    type Error = Error;

    fn try_from(item: NetlinkMessage<RtnlMessage>) -> Result<Message> {
        if let NetlinkPayload::InnerMessage(m) = item.payload {
            m.try_into()
        } else {
            Err(Error::from(ErrorKind::InvalidData))
        }
    }
}

/// A monitor to watch the changes of local addresses.
#[derive(Debug)]
pub struct Monitor {
    messages: UnboundedReceiver<(NetlinkMessage<RtnlMessage>, SocketAddr)>,
}

impl Monitor {
    /// Streams the monitor messages.
    pub fn stream(self) -> impl Stream<Item = Message> {
        self.messages
            .filter_map(|item| async { item.0.try_into().ok() })
    }
}

/// Handles to get the current local addresses and their changes.
pub struct Handle {
    pub addresses: Addresses,
    pub monitor: Monitor,
}

/// A pending connection to the netlink socket.
pub struct Connection {
    pub conn: RtConnection<RtnlMessage>,
    /// The `conn` future must be spawned before the `handle` could work.
    pub handle: Handle,
}

impl Connection {
    /// Creates a pending connection to the netlink socket.
    pub fn new() -> Result<Self> {
        let (mut conn, handle, messages) = new_connection()?;
        conn.socket_mut()
            .socket_mut()
            .bind(&SocketAddr::new(0, RTMGRP_IPV4_IFADDR))?;
        Ok(Connection {
            conn,
            handle: Handle {
                addresses: Addresses { handle },
                monitor: Monitor { messages },
            },
        })
    }
}

#[cfg(test)]
mod tests {
    use super::Connection;
    use futures::stream::StreamExt;

    #[tokio::test]
    async fn has_loopback() {
        let c = Connection::new().unwrap();
        let rt = tokio::spawn(c.conn);
        let s = c.handle.addresses.stream();
        let r = s.any(|m| async move { m.addr.is_loopback() }).await;
        assert!(r);
        rt.abort();
    }
}