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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
//! Asynchronous library for retrieving IP address information
//!
//! For retrieval of a single address, simply use `get_ip` and set
//! appropriate parameters.
//!
//! In case a finer-grained control over the source of addresses is required,
//! individual `Providers` on which `get_ip` is based can be found in `gip`
//! (for global) and `hostip` (for local).
//!
//! Module `libc_getips` contains a low-level function to receive all addresses
//! directly from the interfaces/adapters.
//
//  Copyright (C) 2021 Zhang Maiyun <myzhang1029@hotmail.com>
//
//  This file is part of DNS updater.
//
//  DNS updater is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Affero General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  DNS updater is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Affero General Public License for more details.
//
//  You should have received a copy of the GNU Affero General Public License
//  along with DNS updater.  If not, see <https://www.gnu.org/licenses/>.
//

#![warn(
    clippy::pedantic,
    missing_docs,
    missing_debug_implementations,
    missing_copy_implementations,
    trivial_casts,
    trivial_numeric_casts,
    unsafe_op_in_unsafe_fn,
    unused_extern_crates,
    unused_import_braces,
    unused_qualifications,
    variant_size_differences
)]
#![allow(clippy::no_effect_underscore_binding)]

pub mod gip;
pub mod hostip;
pub mod libc_getips;

use async_trait::async_trait;
use serde::Deserialize;
use std::net::IpAddr;
use thiserror::Error;

/// Scope of the IP to be received.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
pub enum IpScope {
    /// Address as found by an external service.
    /// If used behind NAT, the address outside the NAT is received.
    /// If IPv6 private address extension is enabled, the preferred address is usually used.
    Global,
    /// Address of the NIC.
    /// If `IpType` is `Ipv6`, the permanent or secured address is preferred.
    /// If `IpType` is `Ipv4`, the first address is used.
    Local,
}

/// Type of global address.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
pub enum IpType {
    /// An IPv4 address.
    #[serde(rename = "IPv4")]
    Ipv4,
    /// An IPv6 address.
    #[serde(rename = "IPv6")]
    Ipv6,
}

/// Error type of IP retrieval methods.
#[derive(Debug, Error)]
pub enum Error {
    /// Error from a global IP provider.
    #[error(transparent)]
    GlobalIpError(#[from] crate::gip::GlobalIpError),

    /// Cannot parse string as an IP.
    #[error(transparent)]
    AddrParseError(#[from] std::net::AddrParseError),

    /// Cannot parse data as UTF-8.
    #[error(transparent)]
    UnicodeParseError(#[from] std::string::FromUtf8Error),

    /// Command exited with a non-zero status.
    #[error("Command exited with status {0}")]
    NonZeroExit(std::process::ExitStatus),

    /// All libc-related errors.
    #[error(transparent)]
    IoError(#[from] std::io::Error),

    /// No address found.
    #[error("no address returned")]
    NoAddress,
}

/// A `Result` alias where the `Err` variant is `getip::Error`.
pub type Result<R> = std::result::Result<R, Error>;

/// Any IP Provider.
#[async_trait]
pub trait Provider: Sized {
    /// Get the address provided by this provider.
    async fn get_addr(&self) -> Result<IpAddr>;
    /// Get the `IpType` that this provider gives.
    fn get_type(&self) -> IpType;
}

/// Receive a IP address of family `ip_type` that has a scope of `ip_scope` on an interface named `nic`.
///
/// If `ip_scope` is `Global`, the address is received from an external service, and `nic` is ignored.
/// If `nic` is `None`, this function uses the first one returned by the OS.
///
/// # Examples
///
/// Get an global IPv4 address:
///
/// ```
/// use getip::get_ip;
/// use getip::{IpScope, IpType, Result};
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
///     let address = get_ip(IpType::Ipv4, IpScope::Global, None).await?;
///     println!("{}", address);
///     Ok(())
/// }
/// ```
///
/// # Errors
///
/// Any errors returned by the underlying provider is propagated here.
///
pub async fn get_ip(ip_type: IpType, ip_scope: IpScope, nic: Option<&str>) -> Result<IpAddr> {
    match (ip_type, ip_scope) {
        (IpType::Ipv4, IpScope::Global) => {
            // Get a global IPv4 address
            let p = gip::ProviderMultiple::default();
            p.get_addr().await
        }
        (IpType::Ipv6, IpScope::Global) => {
            // Get a global IPv6 address
            let p = gip::ProviderMultiple::default_v6();
            p.get_addr().await
        }
        (IpType::Ipv4, IpScope::Local) => {
            // Get a local IPv4 address
            let p = hostip::LocalLibcProvider::new(nic, IpType::Ipv4);
            p.get_addr().await
        }
        (IpType::Ipv6, IpScope::Local) => {
            // Get a local IPv6 address
            if let Some(nic) = nic {
                let command_provider = hostip::LocalIpv6CommandProvider::new(nic, true);
                let command_result = command_provider.get_addr().await;
                if command_result.is_ok() || matches!(command_result, Err(Error::NoAddress)) {
                    return command_result;
                }
            };
            let p = hostip::LocalLibcProvider::new(nic, IpType::Ipv6);
            p.get_addr().await
        }
    }
}

#[cfg(test)]
mod test {
    use crate::{get_ip, libc_getips, IpScope, IpType};
    use std::net::IpAddr;

    /// Test if any IPv6 address is available on an interface
    /// If not, the test is skipped
    fn has_any_ipv6_address(iface_name: Option<&str>, global: bool) -> bool {
        if let Ok(addresses) = libc_getips::get_iface_addrs(Some(IpType::Ipv6), iface_name) {
            addresses
                .iter()
                .filter(|ip| {
                    !ip.is_loopback()
                        && !ip.is_unspecified()
                        && if global {
                            if let IpAddr::V6(dcasted) = ip {
                                // !is_unicast_link_local
                                (dcasted.segments()[0] & 0xffc0) != 0xfe80
                                    // !is_unique_local
                                    && (dcasted.segments()[0] & 0xfe00) != 0xfc00
                            } else {
                                unreachable!()
                            }
                        } else {
                            true
                        }
                })
                .next()
                .is_some()
        } else {
            false
        }
    }

    #[tokio::test]
    async fn test_global_ipv4_is_any() {
        let addr = get_ip(IpType::Ipv4, IpScope::Global, None).await;
        assert!(addr.is_ok(), "The result of get_addr() should be Ok()");
        if let IpAddr::V4(addr) = addr.unwrap() {
            assert!(
                !addr.is_private(),
                "The result of get_addr() should not be private"
            );
            assert!(
                !addr.is_loopback(),
                "The result of get_addr() should not be loopback"
            );
        } else {
            assert!(false, "The result of get_addr() should be an IPv4 address");
        }
    }

    #[tokio::test]
    async fn test_global_ipv6_is_any() {
        if !has_any_ipv6_address(None, true) {
            return;
        }
        let addr = get_ip(IpType::Ipv6, IpScope::Global, None).await;
        assert!(addr.is_ok(), "The result of get_addr() should be Ok()");
        if let IpAddr::V6(addr) = addr.unwrap() {
            assert!(
                !addr.is_loopback(),
                "The result of get_addr() should not be loopback"
            );
            assert!(
                !addr.is_unspecified(),
                "The result of get_addr() should not be unspecified"
            );
        } else {
            assert!(false, "The result of get_addr() should be an IPv6 address");
        }
    }

    #[tokio::test]
    async fn test_local_ipv4_is_any() {
        let addr = get_ip(IpType::Ipv4, IpScope::Local, None).await;
        assert!(addr.is_ok(), "The result of get_addr() should be Ok()");
        if !addr.unwrap().is_ipv4() {
            assert!(false, "The result of get_addr() should be an IPv4 address");
        }
    }

    #[tokio::test]
    async fn test_local_ipv6_is_any() {
        if !has_any_ipv6_address(None, true) {
            return;
        }
        let addr = get_ip(IpType::Ipv6, IpScope::Local, None).await;
        assert!(addr.is_ok(), "The result of get_addr() should be Ok()");
        if !addr.unwrap().is_ipv6() {
            assert!(false, "The result of get_addr() should be an IPv6 address");
        }
    }
}