pub mod address;
mod caps;
#[cfg(feature = "http")]
mod client;
mod error;
pub mod proxy;
#[cfg(feature = "sockets")]
pub mod sockets;
pub mod status;
#[cfg(feature = "webtransport")]
pub mod webtransport;
#[cfg(feature = "ws")]
pub mod ws;
#[cfg(not(target_family = "wasm"))]
mod native;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
mod web;
#[cfg(all(
target_family = "wasm",
not(all(target_arch = "wasm32", target_os = "unknown"))
))]
compile_error!("tilo-net has backends for native targets and wasm32-unknown-unknown only");
pub use ::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header};
pub use bytes::Bytes;
pub use caps::{Availability, Feature, Unsupported, availability, available};
#[cfg(feature = "http")]
pub use client::{Client, ClientBuilder, Redirects, Request, RequestBuilder, Response};
#[cfg(all(feature = "http", not(target_family = "wasm")))]
pub use client::{Lookup, refused_lookup};
pub use error::NetError;
pub use url::Url;
#[must_use]
pub fn secure_origin(url: &Url) -> bool {
match url.scheme() {
"https" => true,
"http" => match url.host() {
Some(url::Host::Domain(name)) => loopback_name(name),
Some(url::Host::Ipv4(address)) => address.is_loopback(),
Some(url::Host::Ipv6(address)) => address.is_loopback(),
None => false,
},
_ => false,
}
}
#[must_use]
pub fn secure_endpoint(url: &Url) -> bool {
secure_origin(url)
&& url.host().is_some()
&& url.username().is_empty()
&& url.password().is_none()
}
#[must_use]
pub fn loopback_name(name: &str) -> bool {
let name = name.trim_end_matches('.').to_ascii_lowercase();
name == "localhost" || name.ends_with(".localhost")
}
#[cfg(test)]
mod secure_origin_tests {
use super::{Url, loopback_name, secure_endpoint, secure_origin};
#[test]
fn a_name_under_localhost_is_this_machine() {
for name in ["localhost", "tilo.localhost", "a.b.localhost", "LOCALHOST."] {
assert!(loopback_name(name), "{name}");
}
for name in [
"localhost.tilo.sh",
"tilo.sh",
"notlocalhost",
"localhost.example",
] {
assert!(!loopback_name(name), "{name}");
}
}
#[test]
fn https_anywhere_and_http_only_on_this_machine() {
for secure in [
"https://tilo.sh",
"https://eu1.tilo.sh:8443",
"http://localhost:24110",
"http://localhost./",
"http://tilo.localhost:24120",
"http://127.0.0.1:24100",
"http://127.1.2.3",
"http://[::1]:80",
] {
assert!(secure_origin(&Url::parse(secure).unwrap()), "{secure}");
}
for open in [
"http://tilo.sh",
"http://localhost.tilo.sh",
"http://10.0.0.1",
"http://0.0.0.0/",
"http://[::]/",
"http://[::ffff:127.0.0.1]/",
"ws://localhost",
"ftp://localhost",
] {
assert!(!secure_origin(&Url::parse(open).unwrap()), "{open}");
}
}
#[test]
fn secure_endpoints_allow_local_http_and_refuse_credentials() {
for safe in [
"https://tilo.sh",
"https://eu1.tilo.sh:8443/entries",
"http://localhost:24110/",
"http://localhost./",
"http://tilo.localhost:24120/",
"http://127.0.0.1:24100/",
"http://127.1.2.3:8080/",
"http://[::1]:8080/",
] {
assert!(secure_endpoint(&Url::parse(safe).unwrap()), "{safe}");
}
for refused in [
"http://tilo.sh/",
"http://localhost.tilo.sh/",
"http://10.0.0.1/",
"http://0.0.0.0/",
"http://[::]/",
"http://[::ffff:127.0.0.1]/",
"https://placeholder:placeholder@tilo.sh/",
"https://placeholder@tilo.sh/",
"https://:placeholder@tilo.sh/",
"http://placeholder:placeholder@localhost:8080/",
"http://placeholder:placeholder@127.0.0.1:8080/",
"http://placeholder:placeholder@[::1]:8080/",
"file:///tmp/app.tapp",
"ws://localhost/",
"ftp://localhost/",
] {
assert!(!secure_endpoint(&Url::parse(refused).unwrap()), "{refused}");
}
}
}
#[cfg(not(target_family = "wasm"))]
pub use native::tls::{
client_config, client_config_also_trusting, client_config_with_roots, crypto_provider,
install_crypto_provider, lacks_authorities, pinned_client_config,
server_verifier_also_trusting, system_roots,
};
#[allow(dead_code, reason = "a compile-time check, never called")]
mod send_check {
fn send<T: Send>(_: &T) {}
#[cfg(feature = "http")]
fn http(client: &crate::Client, response: crate::Response) {
send(&client.get("https://example.com/").send());
send(&response.bytes());
}
#[cfg(feature = "ws")]
fn ws(socket: crate::ws::WebSocket) {
send(&socket.close());
}
#[cfg(feature = "webtransport")]
fn webtransport(stream: crate::webtransport::RecvStream) {
send(&stream.read_to_end(1));
}
fn status(watch: &mut crate::status::Watch) {
send(&watch.changed());
}
}
#[cfg(all(feature = "http", not(target_family = "wasm")))]
pub mod http {
#[cfg(feature = "blocking")]
pub mod fetch;
#[cfg(feature = "blocking")]
pub type BlockingClient = reqwest::blocking::Client;
#[allow(
clippy::disallowed_methods,
reason = "this is the sanctioned constructor; it installs the provider first"
)]
pub fn client() -> reqwest::ClientBuilder {
crate::install_crypto_provider();
let builder = reqwest::Client::builder()
.gzip(false)
.brotli(false)
.dns_resolver(LoopbackNames);
#[cfg(target_os = "android")]
let builder = builder.tls_certs_only(system_certificates());
builder
}
#[cfg(feature = "blocking")]
#[allow(
clippy::disallowed_methods,
reason = "this is the sanctioned constructor; it installs the provider first"
)]
pub fn blocking_client() -> reqwest::blocking::ClientBuilder {
crate::install_crypto_provider();
let builder = reqwest::blocking::Client::builder()
.gzip(false)
.brotli(false)
.dns_resolver(std::sync::Arc::new(LoopbackNames));
#[cfg(target_os = "android")]
let builder = builder.tls_certs_only(system_certificates());
builder
}
#[cfg(feature = "blocking")]
pub fn blocking_client_looking(lookup: crate::Lookup) -> reqwest::blocking::ClientBuilder {
blocking_client()
.dns_resolver(std::sync::Arc::new(crate::native::http::Looked(lookup)))
.no_proxy()
}
#[must_use]
pub fn refused_by_lookup(error: &(dyn std::error::Error + 'static)) -> Option<String> {
crate::native::http::refused(error)
}
struct LoopbackNames;
impl reqwest::dns::Resolve for LoopbackNames {
fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
let host = name.as_str().to_owned();
if crate::loopback_name(&host) {
let addrs: Vec<std::net::SocketAddr> = vec![
std::net::SocketAddr::from((std::net::Ipv4Addr::LOCALHOST, 0)),
std::net::SocketAddr::from((std::net::Ipv6Addr::LOCALHOST, 0)),
];
let addrs: reqwest::dns::Addrs = Box::new(addrs.into_iter());
return Box::pin(std::future::ready(Ok(addrs)));
}
Box::pin(async move {
let addresses = tokio::task::spawn_blocking(move || {
use std::net::ToSocketAddrs as _;
(host.as_str(), 0).to_socket_addrs()
})
.await
.map_err(|error| Box::new(error) as Box<dyn std::error::Error + Send + Sync>)?
.map_err(|error| Box::new(error) as Box<dyn std::error::Error + Send + Sync>)?;
Ok(Box::new(addresses) as reqwest::dns::Addrs)
})
}
}
#[cfg(test)]
mod tests {
use reqwest::dns::{Name, Resolve as _};
#[test]
#[allow(
clippy::expect_used,
reason = "a test's own name and runtime are fixtures"
)]
fn a_name_under_localhost_is_this_machine() {
let runtime = tokio::runtime::Builder::new_current_thread()
.build()
.expect("a runtime");
for host in [
"localhost",
"tilo.localhost",
"a.b.localhost",
"TILO.Localhost.",
] {
let addrs: Vec<std::net::SocketAddr> = runtime
.block_on(super::LoopbackNames.resolve(host.parse::<Name>().expect("a name")))
.expect("loopback needs no resolver")
.collect();
assert!(!addrs.is_empty(), "{host}");
assert!(
addrs.iter().all(|address| address.ip().is_loopback()),
"{host}"
);
}
}
}
#[cfg(target_os = "android")]
fn system_certificates() -> Vec<reqwest::Certificate> {
rustls_native_certs::load_native_certs()
.certs
.iter()
.filter_map(|der| reqwest::Certificate::from_der(der).ok())
.collect()
}
}