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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
use std::borrow::Cow;
use std::future::Future;
use std::net::{IpAddr, SocketAddr};
use std::pin::Pin;
use std::str;
use std::task::{Context, Poll};

use futures_core::Stream;
use futures_util::future::BoxFuture;
use futures_util::{future, ready, stream};
use http::{Response, Uri};
use hyper::{
    body::{self, Body, Buf},
    client::{Builder, Client},
};
use pin_project_lite::pin_project;
use thiserror::Error;
use tracing::trace_span;
use tracing_futures::Instrument;

#[cfg(feature = "tokio-http-resolver")]
use hyper::client::connect::{HttpConnector, HttpInfo};

#[cfg(feature = "tokio-http-resolver")]
type GaiResolver = hyper_system_resolver::system::Resolver;

use crate::{Resolutions, Version};

///////////////////////////////////////////////////////////////////////////////
// Hardcoded resolvers

/// All builtin HTTP resolvers.
pub const ALL: &dyn crate::Resolver<'static> = &&[
    #[cfg(feature = "ipify-org")]
    HTTP_IPIFY_ORG,
    #[cfg(feature = "whatismyipaddress-com")]
    HTTP_WHATISMYIPADDRESS_COM,
];

/// `http://api.ipify.org` HTTP resolver options
#[cfg(feature = "ipify-org")]
#[cfg_attr(docsrs, doc(cfg(feature = "ipify-org")))]
pub const HTTP_IPIFY_ORG: &dyn crate::Resolver<'static> =
    &Resolver::new_static("http://api.ipify.org", ExtractMethod::PlainText);

/// `http://bot.whatismyipaddress.com` HTTP resolver options
#[cfg(feature = "whatismyipaddress-com")]
#[cfg_attr(docsrs, doc(cfg(feature = "whatismyipaddress-com")))]
pub const HTTP_WHATISMYIPADDRESS_COM: &dyn crate::Resolver<'static> =
    &Resolver::new_static("http://bot.whatismyipaddress.com", ExtractMethod::PlainText);

///////////////////////////////////////////////////////////////////////////////
// Error

/// HTTP resolver error
#[derive(Debug, Error)]
pub enum Error {
    /// Client error.
    #[error("{0}")]
    Client(hyper::Error),
    /// URI parsing error.
    #[error("{0}")]
    Uri(http::uri::InvalidUri),
}

///////////////////////////////////////////////////////////////////////////////
// Details & options

/// A resolution produced from a HTTP resolver
#[derive(Debug, Clone)]
pub struct Details {
    uri: Uri,
    server: SocketAddr,
    method: ExtractMethod,
}

impl Details {
    /// URI used in the resolution of the associated IP address
    pub fn uri(&self) -> &Uri {
        &self.uri
    }

    /// HTTP server used in the resolution of our IP address.
    pub fn server(&self) -> SocketAddr {
        self.server
    }

    /// The extract method used in the resolution of the associated IP address
    pub fn extract_method(&self) -> ExtractMethod {
        self.method
    }
}

/// Method used to extract an IP address from a http response
#[derive(Debug, Clone, Copy)]
pub enum ExtractMethod {
    /// Parses the body with whitespace trimmed as the IP address.
    PlainText,
    /// Parses the body with double quotes and whitespace trimmed as the IP address.
    StripDoubleQuotes,
    /// Parses the value of the JSON property `"ip"` within the body as the IP address.
    ///
    /// Note this method does not validate the JSON.
    ExtractJsonIpField,
}

///////////////////////////////////////////////////////////////////////////////
// Resolver

/// Options to build a HTTP resolver
#[derive(Debug, Clone)]
pub struct Resolver<'r> {
    uri: Cow<'r, str>,
    method: ExtractMethod,
}

impl<'r> Resolver<'r> {
    /// Create new HTTP resolver options
    pub fn new<U>(uri: U, method: ExtractMethod) -> Self
    where
        U: Into<Cow<'r, str>>,
    {
        Self {
            uri: uri.into(),
            method,
        }
    }
}

impl Resolver<'static> {
    /// Create new HTTP resolver options from static
    #[must_use]
    pub const fn new_static(uri: &'static str, method: ExtractMethod) -> Self {
        Self {
            uri: Cow::Borrowed(uri),
            method,
        }
    }
}

///////////////////////////////////////////////////////////////////////////////
// Resolutions

pin_project! {
    #[project = HttpResolutionsProj]
    enum HttpResolutions<'r> {
        HttpRequest {
            #[pin]
            response: BoxFuture<'r, Result<(IpAddr, crate::Details), crate::Error>>,
        },
        Done,
    }
}

impl<'r> Stream for HttpResolutions<'r> {
    type Item = Result<(IpAddr, crate::Details), crate::Error>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        match self.as_mut().project() {
            HttpResolutionsProj::HttpRequest { response } => {
                let response = ready!(response.poll(cx));
                *self = HttpResolutions::Done;
                Poll::Ready(Some(response))
            }
            HttpResolutionsProj::Done => Poll::Ready(None),
        }
    }
}

async fn resolve(
    version: Version,
    uri: Uri,
    method: ExtractMethod,
) -> Result<(IpAddr, crate::Details), crate::Error> {
    let response = http_client(version)
        .get(uri.clone())
        .await
        .map_err(Error::Client)?;
    // TODO
    let server = remote_addr(&response);
    let mut body = body::aggregate(response.into_body())
        .await
        .map_err(Error::Client)?;
    let body = body.copy_to_bytes(body.remaining());
    let body_str = str::from_utf8(body.as_ref())?;
    let address_str = match method {
        ExtractMethod::PlainText => body_str.trim(),
        ExtractMethod::ExtractJsonIpField => extract_json_ip_field(body_str)?,
        ExtractMethod::StripDoubleQuotes => body_str.trim().trim_matches('"'),
    };
    let address = address_str.parse()?;
    let details = Box::new(Details {
        uri,
        server,
        method,
    });
    Ok((address, crate::Details::from(details)))
}

impl<'r> crate::Resolver<'r> for Resolver<'r> {
    fn resolve(&self, version: Version) -> Resolutions<'r> {
        let method = self.method;
        let uri: Uri = match self.uri.as_ref().parse() {
            Ok(name) => name,
            Err(err) => return Box::pin(stream::once(future::ready(Err(crate::Error::new(err))))),
        };
        let span = trace_span!("http resolver", ?version, ?method, %uri);
        let resolutions = HttpResolutions::HttpRequest {
            response: Box::pin(resolve(version, uri, method)),
        };
        Box::pin(resolutions.instrument(span))
    }
}

fn extract_json_ip_field(s: &str) -> Result<&str, crate::Error> {
    s.split_once(r#""ip":"#)
        .and_then(|(_, after_prop)| after_prop.split('"').nth(1))
        .ok_or(crate::Error::Addr)
}

///////////////////////////////////////////////////////////////////////////////
// Client

#[cfg(feature = "tokio-http-resolver")]
fn http_client(version: Version) -> Client<HttpConnector<GaiResolver>, Body> {
    use dns_lookup::{AddrFamily, AddrInfoHints, SockType};
    use hyper_system_resolver::system::System;
    let hints = match version {
        Version::V4 => AddrInfoHints {
            address: AddrFamily::Inet.into(),
            ..AddrInfoHints::default()
        },
        Version::V6 => AddrInfoHints {
            address: AddrFamily::Inet6.into(),
            ..AddrInfoHints::default()
        },
        Version::Any => AddrInfoHints {
            socktype: SockType::Stream.into(),
            ..AddrInfoHints::default()
        },
    };
    let system = System {
        addr_info_hints: Some(hints),
        service: None,
    };
    let connector = HttpConnector::new_with_resolver(system.resolver());
    Builder::default().build(connector)
}

#[cfg(feature = "tokio-http-resolver")]
fn remote_addr(response: &Response<Body>) -> SocketAddr {
    response
        .extensions()
        .get::<HttpInfo>()
        .unwrap()
        .remote_addr()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_json_ip_field() {
        const VALID: &str = r#"{
            "ip": "123.123.123.123",
        }"#;

        const INVALID: &str = r#"{
            "ipp": "123.123.123.123",
        }"#;

        const VALID_INVALID: &str = r#"{
            "ip": "123.123.123.123",
            "ip": "321.321.321.321",
        }"#;

        assert_eq!(extract_json_ip_field(VALID).unwrap(), "123.123.123.123");
        assert_eq!(
            extract_json_ip_field(VALID_INVALID).unwrap(),
            "123.123.123.123"
        );
        assert!(matches!(
            extract_json_ip_field(INVALID).unwrap_err(),
            crate::Error::Addr
        ));
    }
}