Skip to main content

tilo_net/
lib.rs

1//! The network capability on Linux, macOS and the web.
2//!
3//! One async API on every target, every future `Send`, so an app hands requests
4//! to `tilo_rt::app()` instead of running a blocking client on a thread of its
5//! own. What a target cannot provide is an [`Unsupported`] error at run time,
6//! never a missing item.
7
8pub mod address;
9mod caps;
10#[cfg(feature = "http")]
11mod client;
12mod error;
13pub mod proxy;
14#[cfg(feature = "sockets")]
15pub mod sockets;
16pub mod status;
17#[cfg(feature = "webtransport")]
18pub mod webtransport;
19#[cfg(feature = "ws")]
20pub mod ws;
21
22#[cfg(not(target_family = "wasm"))]
23mod native;
24#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
25mod web;
26#[cfg(all(
27    target_family = "wasm",
28    not(all(target_arch = "wasm32", target_os = "unknown"))
29))]
30compile_error!("tilo-net has backends for native targets and wasm32-unknown-unknown only");
31
32pub use ::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header};
33pub use bytes::Bytes;
34pub use caps::{Availability, Feature, Unsupported, availability, available};
35#[cfg(feature = "http")]
36pub use client::{Client, ClientBuilder, Redirects, Request, RequestBuilder, Response};
37#[cfg(all(feature = "http", not(target_family = "wasm")))]
38pub use client::{Lookup, refused_lookup};
39pub use error::NetError;
40pub use url::Url;
41
42/// Whether `url` is on an origin browsers treat as secure: `https`, or plain
43/// `http` on this machine, which never leaves it.
44#[must_use]
45pub fn secure_origin(url: &Url) -> bool {
46    match url.scheme() {
47        "https" => true,
48        "http" => match url.host() {
49            Some(url::Host::Domain(name)) => loopback_name(name),
50            Some(url::Host::Ipv4(address)) => address.is_loopback(),
51            Some(url::Host::Ipv6(address)) => address.is_loopback(),
52            None => false,
53        },
54        _ => false,
55    }
56}
57
58/// Whether `url` is a credential-free endpoint on a [`secure_origin`]: `https`,
59/// or plain `http` on this machine, with a host and neither username nor password.
60#[must_use]
61pub fn secure_endpoint(url: &Url) -> bool {
62    secure_origin(url)
63        && url.host().is_some()
64        && url.username().is_empty()
65        && url.password().is_none()
66}
67
68/// Whether `name` is a name of this machine: `localhost` and every name under it, which a
69/// browser resolves to loopback itself. The local stack serves the site as `tilo.localhost`.
70#[must_use]
71pub fn loopback_name(name: &str) -> bool {
72    let name = name.trim_end_matches('.').to_ascii_lowercase();
73    name == "localhost" || name.ends_with(".localhost")
74}
75
76#[cfg(test)]
77mod secure_origin_tests {
78    use super::{Url, loopback_name, secure_endpoint, secure_origin};
79
80    #[test]
81    fn a_name_under_localhost_is_this_machine() {
82        for name in ["localhost", "tilo.localhost", "a.b.localhost", "LOCALHOST."] {
83            assert!(loopback_name(name), "{name}");
84        }
85        for name in [
86            "localhost.tilo.sh",
87            "tilo.sh",
88            "notlocalhost",
89            "localhost.example",
90        ] {
91            assert!(!loopback_name(name), "{name}");
92        }
93    }
94
95    #[test]
96    fn https_anywhere_and_http_only_on_this_machine() {
97        for secure in [
98            "https://tilo.sh",
99            "https://eu1.tilo.sh:8443",
100            "http://localhost:24110",
101            "http://localhost./",
102            "http://tilo.localhost:24120",
103            "http://127.0.0.1:24100",
104            "http://127.1.2.3",
105            "http://[::1]:80",
106        ] {
107            assert!(secure_origin(&Url::parse(secure).unwrap()), "{secure}");
108        }
109        for open in [
110            "http://tilo.sh",
111            "http://localhost.tilo.sh",
112            "http://10.0.0.1",
113            "http://0.0.0.0/",
114            "http://[::]/",
115            "http://[::ffff:127.0.0.1]/",
116            "ws://localhost",
117            "ftp://localhost",
118        ] {
119            assert!(!secure_origin(&Url::parse(open).unwrap()), "{open}");
120        }
121    }
122
123    #[test]
124    fn secure_endpoints_allow_local_http_and_refuse_credentials() {
125        for safe in [
126            "https://tilo.sh",
127            "https://eu1.tilo.sh:8443/entries",
128            "http://localhost:24110/",
129            "http://localhost./",
130            "http://tilo.localhost:24120/",
131            "http://127.0.0.1:24100/",
132            "http://127.1.2.3:8080/",
133            "http://[::1]:8080/",
134        ] {
135            assert!(secure_endpoint(&Url::parse(safe).unwrap()), "{safe}");
136        }
137        for refused in [
138            "http://tilo.sh/",
139            "http://localhost.tilo.sh/",
140            "http://10.0.0.1/",
141            "http://0.0.0.0/",
142            "http://[::]/",
143            "http://[::ffff:127.0.0.1]/",
144            "https://placeholder:placeholder@tilo.sh/",
145            "https://placeholder@tilo.sh/",
146            "https://:placeholder@tilo.sh/",
147            "http://placeholder:placeholder@localhost:8080/",
148            "http://placeholder:placeholder@127.0.0.1:8080/",
149            "http://placeholder:placeholder@[::1]:8080/",
150            "file:///tmp/app.tapp",
151            "ws://localhost/",
152            "ftp://localhost/",
153        ] {
154            assert!(!secure_endpoint(&Url::parse(refused).unwrap()), "{refused}");
155        }
156    }
157}
158
159#[cfg(not(target_family = "wasm"))]
160pub use native::tls::{
161    client_config, client_config_also_trusting, client_config_with_roots, crypto_provider,
162    install_crypto_provider, lacks_authorities, pinned_client_config,
163    server_verifier_also_trusting, system_roots,
164};
165
166/// Every future of the public API is `Send` on every target; this fails to
167/// compile otherwise.
168#[allow(dead_code, reason = "a compile-time check, never called")]
169mod send_check {
170    fn send<T: Send>(_: &T) {}
171
172    #[cfg(feature = "http")]
173    fn http(client: &crate::Client, response: crate::Response) {
174        send(&client.get("https://example.com/").send());
175        send(&response.bytes());
176    }
177
178    #[cfg(feature = "ws")]
179    fn ws(socket: crate::ws::WebSocket) {
180        send(&socket.close());
181    }
182
183    #[cfg(feature = "webtransport")]
184    fn webtransport(stream: crate::webtransport::RecvStream) {
185        send(&stream.read_to_end(1));
186    }
187
188    fn status(watch: &mut crate::status::Watch) {
189        send(&watch.changed());
190    }
191}
192
193/// reqwest builders on Tilo's TLS defaults, for desktop-only code. They panic
194/// unless a process default provider is installed, so every client starts
195/// from these functions.
196#[cfg(all(feature = "http", not(target_family = "wasm")))]
197pub mod http {
198    /// One resumable, verified download from a trusted origin.
199    #[cfg(feature = "blocking")]
200    pub mod fetch;
201
202    /// The one blocking client a caller keeps for its requests: its own type, so
203    /// a caller need not name `reqwest`.
204    #[cfg(feature = "blocking")]
205    pub type BlockingClient = reqwest::blocking::Client;
206
207    #[allow(
208        clippy::disallowed_methods,
209        reason = "this is the sanctioned constructor; it installs the provider first"
210    )]
211    pub fn client() -> reqwest::ClientBuilder {
212        crate::install_crypto_provider();
213        let builder = reqwest::Client::builder()
214            .gzip(false)
215            .brotli(false)
216            .dns_resolver(LoopbackNames);
217        #[cfg(target_os = "android")]
218        let builder = builder.tls_certs_only(system_certificates());
219        builder
220    }
221
222    #[cfg(feature = "blocking")]
223    #[allow(
224        clippy::disallowed_methods,
225        reason = "this is the sanctioned constructor; it installs the provider first"
226    )]
227    pub fn blocking_client() -> reqwest::blocking::ClientBuilder {
228        crate::install_crypto_provider();
229        let builder = reqwest::blocking::Client::builder()
230            .gzip(false)
231            .brotli(false)
232            .dns_resolver(std::sync::Arc::new(LoopbackNames));
233        #[cfg(target_os = "android")]
234        let builder = builder.tls_certs_only(system_certificates());
235        builder
236    }
237
238    /// [`blocking_client`] for a caller that keeps its requests off some
239    /// addresses: for every name it dials only the addresses `lookup` answers,
240    /// in the one lookup the connection itself makes
241    /// ([`crate::ClientBuilder::lookup`]), and it takes no proxy from the
242    /// environment, which would resolve a name behind that lookup. An address
243    /// written into a URL is not looked up: its caller asks
244    /// [`crate::address::asked_as_written`] before it sends anything there.
245    #[cfg(feature = "blocking")]
246    pub fn blocking_client_looking(lookup: crate::Lookup) -> reqwest::blocking::ClientBuilder {
247        blocking_client()
248            .dns_resolver(std::sync::Arc::new(crate::native::http::Looked(lookup)))
249            .no_proxy()
250    }
251
252    /// What a client's own lookup said when it refused the name a request was
253    /// for, read from that request's `error`: nothing was sent.
254    #[must_use]
255    pub fn refused_by_lookup(error: &(dyn std::error::Error + 'static)) -> Option<String> {
256        crate::native::http::refused(error)
257    }
258
259    /// Resolution for Tilo's clients: a name under `localhost` is this machine's
260    /// ([`crate::loopback_name`]), whoever the machine's resolver is, and every
261    /// other name is the system resolver's, as reqwest's own is.
262    struct LoopbackNames;
263
264    impl reqwest::dns::Resolve for LoopbackNames {
265        fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
266            let host = name.as_str().to_owned();
267            if crate::loopback_name(&host) {
268                let addrs: Vec<std::net::SocketAddr> = vec![
269                    std::net::SocketAddr::from((std::net::Ipv4Addr::LOCALHOST, 0)),
270                    std::net::SocketAddr::from((std::net::Ipv6Addr::LOCALHOST, 0)),
271                ];
272                let addrs: reqwest::dns::Addrs = Box::new(addrs.into_iter());
273                return Box::pin(std::future::ready(Ok(addrs)));
274            }
275            Box::pin(async move {
276                let addresses = tokio::task::spawn_blocking(move || {
277                    use std::net::ToSocketAddrs as _;
278                    (host.as_str(), 0).to_socket_addrs()
279                })
280                .await
281                .map_err(|error| Box::new(error) as Box<dyn std::error::Error + Send + Sync>)?
282                .map_err(|error| Box::new(error) as Box<dyn std::error::Error + Send + Sync>)?;
283                Ok(Box::new(addresses) as reqwest::dns::Addrs)
284            })
285        }
286    }
287
288    #[cfg(test)]
289    mod tests {
290        use reqwest::dns::{Name, Resolve as _};
291
292        #[test]
293        #[allow(
294            clippy::expect_used,
295            reason = "a test's own name and runtime are fixtures"
296        )]
297        fn a_name_under_localhost_is_this_machine() {
298            let runtime = tokio::runtime::Builder::new_current_thread()
299                .build()
300                .expect("a runtime");
301            for host in [
302                "localhost",
303                "tilo.localhost",
304                "a.b.localhost",
305                "TILO.Localhost.",
306            ] {
307                let addrs: Vec<std::net::SocketAddr> = runtime
308                    .block_on(super::LoopbackNames.resolve(host.parse::<Name>().expect("a name")))
309                    .expect("loopback needs no resolver")
310                    .collect();
311                assert!(!addrs.is_empty(), "{host}");
312                assert!(
313                    addrs.iter().all(|address| address.ip().is_loopback()),
314                    "{host}"
315                );
316            }
317        }
318    }
319
320    /// Android's platform verifier aborts without the app's JVM context, so
321    /// clients there verify against Android's system store.
322    #[cfg(target_os = "android")]
323    fn system_certificates() -> Vec<reqwest::Certificate> {
324        rustls_native_certs::load_native_certs()
325            .certs
326            .iter()
327            .filter_map(|der| reqwest::Certificate::from_der(der).ok())
328            .collect()
329    }
330}