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
use crate::sources::interfaces::{IpFuture, IpResult, Source};
use log::trace;

use hyper::body::HttpBody;
use hyper::Client;
use hyper_tls::HttpsConnector;

/// HTTP(s) Source of the external ip
///
/// It expects a URL to contact to retrive in the content of the message the IP
/// without any additional processing (if not trimming the string).
#[derive(Debug, Clone)]
pub struct HTTPSource {
    url: String,
}

impl HTTPSource {
    fn source<S: Into<String>>(url: S) -> Box<dyn Source> {
        Box::new(HTTPSource { url: url.into() })
    }
}

impl Source for HTTPSource {
    fn get_ip<'a>(&'a self) -> IpFuture<'a> {
        async fn run(_self: &HTTPSource) -> IpResult {
            trace!("Contacting {:?}", _self.url);

            let https = HttpsConnector::new();
            let client = Client::builder().build::<_, hyper::Body>(https);

            let mut res = client.get(_self.url.parse()?).await?;
            trace!("Result for {:?}: {:?}", _self.url, res);

            let mut message = vec![];
            while let Some(chunk) = res.body_mut().data().await {
                message.extend(chunk?);
            }

            Ok(std::str::from_utf8(&message)?.trim().parse()?)
        };

        Box::pin(run(self))
    }

    fn box_clone(&self) -> Box<dyn Source> {
        Box::new(self.clone())
    }
}

impl std::fmt::Display for HTTPSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "HttpSource: {}", self.url)
    }
}

/// Returns a collection of HTTP(s) sources to use to retrieve the external ip
pub fn get_http_sources<T>() -> T
where
    T: std::iter::FromIterator<Box<dyn Source>>,
{
    [
        "https://icanhazip.com/",
        "https://myexternalip.com/raw",
        "https://ifconfig.io/ip",
        "https://ipecho.net/plain",
        "https://checkip.amazonaws.com/",
        "https://ident.me/",
        "http://whatismyip.akamai.com/",
        "https://tnx.nl/ip",
        "https://myip.dnsomatic.com/",
        "https://diagnostic.opendns.com/myip",
    ]
    .into_iter()
    .map(|x| HTTPSource::source(*x))
    .collect()
}