summary refs log tree commit diff
path: root/rust/src/http/resolver.rs
blob: 77e9bf5c20a956c43b6dc9d75097fb8e4e5e2e0d (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
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use std::collections::BTreeMap;
use std::future::Future;
use std::net::IpAddr;
use std::pin::Pin;
use std::str::FromStr;
use std::{
    io::Cursor,
    sync::{Arc, Mutex},
    task::{self, Poll},
};

use anyhow::{bail, Error};
use futures::{FutureExt, TryFutureExt};
use futures_util::stream::StreamExt;
use http::Uri;
use hyper::client::connect::Connection;
use hyper::client::connect::{Connected, HttpConnector};
use hyper::server::conn::Http;
use hyper::service::Service;
use hyper::Client;
use hyper_tls::HttpsConnector;
use hyper_tls::MaybeHttpsStream;
use log::info;
use native_tls::TlsConnector;
use serde::Deserialize;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::net::TcpStream;
use tokio_native_tls::TlsConnector as AsyncTlsConnector;
use trust_dns_resolver::error::ResolveErrorKind;

pub struct Endpoint {
    pub host: String,
    pub port: u16,

    pub host_header: String,
    pub tls_name: String,
}

#[derive(Clone)]
pub struct MatrixResolver {
    resolver: trust_dns_resolver::TokioAsyncResolver,
    http_client: Client<HttpsConnector<HttpConnector>>,
}

impl MatrixResolver {
    pub fn new() -> Result<MatrixResolver, Error> {
        let http_client = hyper::Client::builder().build(HttpsConnector::new());

        MatrixResolver::with_client(http_client)
    }

    pub fn with_client(
        http_client: Client<HttpsConnector<HttpConnector>>,
    ) -> Result<MatrixResolver, Error> {
        let resolver = trust_dns_resolver::TokioAsyncResolver::tokio_from_system_conf()?;

        Ok(MatrixResolver {
            resolver,
            http_client,
        })
    }

    /// Does SRV lookup
    pub async fn resolve_server_name_from_uri(&self, uri: &Uri) -> Result<Vec<Endpoint>, Error> {
        let host = uri.host().expect("URI has no host").to_string();
        let port = uri.port_u16();

        self.resolve_server_name_from_host_port(host, port).await
    }

    pub async fn resolve_server_name_from_host_port(
        &self,
        mut host: String,
        mut port: Option<u16>,
    ) -> Result<Vec<Endpoint>, Error> {
        let mut authority = if let Some(p) = port {
            format!("{}:{}", host, p)
        } else {
            host.to_string()
        };

        // If a literal IP or includes port then we shortcircuit.
        if host.parse::<IpAddr>().is_ok() || port.is_some() {
            return Ok(vec![Endpoint {
                host: host.to_string(),
                port: port.unwrap_or(8448),

                host_header: authority.to_string(),
                tls_name: host.to_string(),
            }]);
        }

        // Do well-known delegation lookup.
        if let Some(server) = get_well_known(&self.http_client, &host).await {
            let a = http::uri::Authority::from_str(&server.server)?;
            host = a.host().to_string();
            port = a.port_u16();
            authority = a.to_string();
        }

        // If a literal IP or includes port then we shortcircuit.
        if host.parse::<IpAddr>().is_ok() || port.is_some() {
            return Ok(vec![Endpoint {
                host: host.clone(),
                port: port.unwrap_or(8448),

                host_header: authority.to_string(),
                tls_name: host.clone(),
            }]);
        }

        let result = self
            .resolver
            .srv_lookup(format!("_matrix._tcp.{}", host))
            .await;

        let records = match result {
            Ok(records) => records,
            Err(err) => match err.kind() {
                ResolveErrorKind::NoRecordsFound { .. } => {
                    return Ok(vec![Endpoint {
                        host: host.clone(),
                        port: 8448,
                        host_header: authority.to_string(),
                        tls_name: host.clone(),
                    }])
                }
                _ => return Err(err.into()),
            },
        };

        let mut priority_map: BTreeMap<u16, Vec<_>> = BTreeMap::new();

        let mut count = 0;
        for record in records {
            count += 1;
            let priority = record.priority();
            priority_map.entry(priority).or_default().push(record);
        }

        let mut results = Vec::with_capacity(count);

        for (_priority, records) in priority_map {
            // TODO: Correctly shuffle records
            results.extend(records.into_iter().map(|record| Endpoint {
                host: record.target().to_utf8(),
                port: record.port(),

                host_header: host.to_string(),
                tls_name: host.to_string(),
            }))
        }

        Ok(results)
    }
}

async fn get_well_known<C>(http_client: &Client<C>, host: &str) -> Option<WellKnownServer>
where
    C: Service<Uri> + Clone + Sync + Send + 'static,
    C::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
    C::Future: Unpin + Send,
    C::Response: AsyncRead + AsyncWrite + Connection + Unpin + Send + 'static,
{
    // TODO: Add timeout.

    let uri = hyper::Uri::builder()
        .scheme("https")
        .authority(host)
        .path_and_query("/.well-known/matrix/server")
        .build()
        .ok()?;

    let mut body = http_client.get(uri).await.ok()?.into_body();

    let mut vec = Vec::new();
    while let Some(next) = body.next().await {
        let chunk = next.ok()?;
        vec.extend(chunk);
    }

    serde_json::from_slice(&vec).ok()?
}

#[derive(Deserialize)]
struct WellKnownServer {
    #[serde(rename = "m.server")]
    server: String,
}

#[derive(Clone)]
pub struct MatrixConnector {
    resolver: MatrixResolver,
}

impl MatrixConnector {
    pub fn with_resolver(resolver: MatrixResolver) -> MatrixConnector {
        MatrixConnector { resolver }
    }
}

impl Service<Uri> for MatrixConnector {
    type Response = MaybeHttpsStream<TcpStream>;
    type Error = Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, _: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>> {
        // This connector is always ready, but others might not be.
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, dst: Uri) -> Self::Future {
        let resolver = self.resolver.clone();

        if dst.scheme_str() != Some("matrix") {
            return HttpsConnector::new()
                .call(dst)
                .map_err(|e| Error::msg(e))
                .boxed();
        }

        async move {
            let endpoints = resolver
                .resolve_server_name_from_host_port(
                    dst.host().expect("hostname").to_string(),
                    dst.port_u16(),
                )
                .await?;

            for endpoint in endpoints {
                match try_connecting(&dst, &endpoint).await {
                    Ok(r) => return Ok(r),
                    // Errors here are not unexpected, and we just move on
                    // with our lives.
                    Err(e) => info!(
                        "Failed to connect to {} via {}:{} because {}",
                        dst.host().expect("hostname"),
                        endpoint.host,
                        endpoint.port,
                        e,
                    ),
                }
            }

            bail!(
                "failed to resolve host: {:?} port {:?}",
                dst.host(),
                dst.port()
            )
        }
        .boxed()
    }
}

/// Attempts to connect to a particular endpoint.
async fn try_connecting(
    dst: &Uri,
    endpoint: &Endpoint,
) -> Result<MaybeHttpsStream<TcpStream>, Error> {
    let tcp = TcpStream::connect((&endpoint.host as &str, endpoint.port)).await?;

    let connector: AsyncTlsConnector = if dst.host().expect("hostname").contains("localhost") {
        TlsConnector::builder()
            .danger_accept_invalid_certs(true)
            .build()?
            .into()
    } else {
        TlsConnector::new().unwrap().into()
    };

    let tls = connector.connect(&endpoint.tls_name, tcp).await?;

    Ok(tls.into())
}

/// A connector that reutrns a connection which returns 200 OK to all connections.
#[derive(Clone)]
pub struct TestConnector;

impl Service<Uri> for TestConnector {
    type Response = TestConnection;
    type Error = Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, _: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>> {
        // This connector is always ready, but others might not be.
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, _dst: Uri) -> Self::Future {
        let (client, server) = TestConnection::double_ended();

        {
            let service = hyper::service::service_fn(|_| async move {
                Ok(hyper::Response::new(hyper::Body::from("Hello World")))
                    as Result<_, hyper::http::Error>
            });
            let fut = Http::new().serve_connection(server, service);
            tokio::spawn(fut);
        }

        futures::future::ok(client).boxed()
    }
}

#[derive(Default)]
struct TestConnectionInner {
    outbound_buffer: Cursor<Vec<u8>>,
    inbound_buffer: Cursor<Vec<u8>>,
    wakers: Vec<futures::task::Waker>,
}

/// A in memory connection for use with tests.
#[derive(Clone, Default)]
pub struct TestConnection {
    inner: Arc<Mutex<TestConnectionInner>>,
    direction: bool,
}

impl TestConnection {
    pub fn double_ended() -> (TestConnection, TestConnection) {
        let inner: Arc<Mutex<TestConnectionInner>> = Arc::default();

        let a = TestConnection {
            inner: inner.clone(),
            direction: false,
        };

        let b = TestConnection {
            inner,
            direction: true,
        };

        (a, b)
    }
}

impl AsyncRead for TestConnection {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut task::Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<Result<(), std::io::Error>> {
        let mut conn = self.inner.lock().expect("mutex");

        let buffer = if self.direction {
            &mut conn.inbound_buffer
        } else {
            &mut conn.outbound_buffer
        };

        let bytes_read = std::io::Read::read(buffer, buf.initialize_unfilled())?;
        buf.advance(bytes_read);
        if bytes_read > 0 {
            Poll::Ready(Ok(()))
        } else {
            conn.wakers.push(cx.waker().clone());
            Poll::Pending
        }
    }
}

impl AsyncWrite for TestConnection {
    fn poll_write(
        self: Pin<&mut Self>,
        _cx: &mut task::Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize, std::io::Error>> {
        let mut conn = self.inner.lock().expect("mutex");

        if self.direction {
            conn.outbound_buffer.get_mut().extend_from_slice(buf);
        } else {
            conn.inbound_buffer.get_mut().extend_from_slice(buf);
        }

        for waker in conn.wakers.drain(..) {
            waker.wake()
        }

        Poll::Ready(Ok(buf.len()))
    }
    fn poll_flush(
        self: Pin<&mut Self>,
        cx: &mut task::Context<'_>,
    ) -> Poll<Result<(), std::io::Error>> {
        let mut conn = self.inner.lock().expect("mutex");

        if self.direction {
            Pin::new(&mut conn.outbound_buffer).poll_flush(cx)
        } else {
            Pin::new(&mut conn.inbound_buffer).poll_flush(cx)
        }
    }
    fn poll_shutdown(
        self: Pin<&mut Self>,
        cx: &mut task::Context<'_>,
    ) -> Poll<Result<(), std::io::Error>> {
        let mut conn = self.inner.lock().expect("mutex");

        if self.direction {
            Pin::new(&mut conn.outbound_buffer).poll_shutdown(cx)
        } else {
            Pin::new(&mut conn.inbound_buffer).poll_shutdown(cx)
        }
    }
}

impl Connection for TestConnection {
    fn connected(&self) -> Connected {
        Connected::new()
    }
}

#[tokio::test]
async fn test_memory_connection() {
    let client: hyper::Client<_, hyper::Body> = hyper::Client::builder().build(TestConnector);

    let response = client
        .get("http://localhost".parse().unwrap())
        .await
        .unwrap();

    assert!(response.status().is_success());

    let bytes = hyper::body::to_bytes(response.into_body()).await.unwrap();
    assert_eq!(&bytes[..], b"Hello World");
}