chore: code formatting and cleanup

merge-requests/60/head
Gabriel Souza Franco 3 years ago
parent e73de2317e
commit 7faa021ff5

@ -1,16 +1,16 @@
use crate::{database::Config, utils, Error, Result}; use crate::{database::Config, utils, Error, Result};
use log::error; use log::{error, info};
use ruma::{ use ruma::{
api::federation::discovery::{ServerSigningKeys, VerifyKey}, api::federation::discovery::{ServerSigningKeys, VerifyKey},
ServerName, ServerSigningKeyId, ServerName, ServerSigningKeyId,
}; };
use rustls::{ServerCertVerifier, WebPKIVerifier};
use std::{ use std::{
collections::{BTreeMap, HashMap}, collections::{BTreeMap, HashMap},
sync::{Arc, RwLock}, sync::{Arc, RwLock},
time::Duration, time::Duration,
}; };
use trust_dns_resolver::TokioAsyncResolver; use trust_dns_resolver::TokioAsyncResolver;
use rustls::{ServerCertVerifier, WebPKIVerifier};
pub const COUNTER: &str = "c"; pub const COUNTER: &str = "c";
@ -42,21 +42,20 @@ impl ServerCertVerifier for MatrixServerVerifier {
dns_name: webpki::DNSNameRef<'_>, dns_name: webpki::DNSNameRef<'_>,
ocsp_response: &[u8], ocsp_response: &[u8],
) -> std::result::Result<rustls::ServerCertVerified, rustls::TLSError> { ) -> std::result::Result<rustls::ServerCertVerified, rustls::TLSError> {
let cache = self.tls_name_override.read().unwrap(); if let Some(override_name) = self.tls_name_override.read().unwrap().get(dns_name.into()) {
log::debug!("Searching for override for {:?}", dns_name); let result = self.inner.verify_server_cert(
log::debug!("Cache: {:?}", cache); roots,
let override_name = match cache.get(dns_name.into()) { presented_certs,
Some(host) => { override_name.as_ref(),
log::debug!("Override found! {:?}", host); ocsp_response,
host.as_ref() );
}, if result.is_ok() {
None => dns_name return result;
}; }
info!("Server {:?} is non-compliant, retrying TLS verification with original name", dns_name);
self.inner.verify_server_cert(roots, presented_certs, override_name, ocsp_response).or_else(|_| { }
log::warn!("Server is non-compliant, retrying with original name!"); self.inner
self.inner.verify_server_cert(roots, presented_certs, dns_name, ocsp_response) .verify_server_cert(roots, presented_certs, dns_name, ocsp_response)
})
} }
} }
@ -101,10 +100,14 @@ impl Globals {
}; };
let tls_name_override = Arc::new(RwLock::new(TlsNameMap::new())); let tls_name_override = Arc::new(RwLock::new(TlsNameMap::new()));
let verifier = Arc::new(MatrixServerVerifier { inner: WebPKIVerifier::new(), tls_name_override: tls_name_override.clone() }); let verifier = Arc::new(MatrixServerVerifier {
inner: WebPKIVerifier::new(),
tls_name_override: tls_name_override.clone(),
});
let mut tlsconfig = rustls::ClientConfig::new(); let mut tlsconfig = rustls::ClientConfig::new();
tlsconfig.dangerous().set_certificate_verifier(verifier); tlsconfig.dangerous().set_certificate_verifier(verifier);
tlsconfig.root_store = rustls_native_certs::load_native_certs().expect("Error loading system certificates"); tlsconfig.root_store =
rustls_native_certs::load_native_certs().expect("Error loading system certificates");
let reqwest_client = reqwest::Client::builder() let reqwest_client = reqwest::Client::builder()
.connect_timeout(Duration::from_secs(30)) .connect_timeout(Duration::from_secs(30))

@ -46,13 +46,13 @@ use std::{
use rocket::{get, post, put}; use rocket::{get, post, put};
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
enum FederationDestination { enum FedDest {
Literal(SocketAddr), Literal(SocketAddr),
Named(String, String), Named(String, String),
} }
impl FederationDestination { impl FedDest {
fn into_url(self) -> String { fn into_https_url(self) -> String {
match self { match self {
Self::Literal(addr) => format!("https://{}", addr), Self::Literal(addr) => format!("https://{}", addr),
Self::Named(host, port) => format!("https://{}{}", host, port), Self::Named(host, port) => format!("https://{}{}", host, port),
@ -69,7 +69,7 @@ impl FederationDestination {
fn host(&self) -> String { fn host(&self) -> String {
match &self { match &self {
Self::Literal(addr) => addr.ip().to_string(), Self::Literal(addr) => addr.ip().to_string(),
Self::Named(host, _) => host.clone() Self::Named(host, _) => host.clone(),
} }
} }
} }
@ -99,13 +99,13 @@ where
} else { } else {
let result = find_actual_destination(globals, &destination).await; let result = find_actual_destination(globals, &destination).await;
let (actual_destination, host) = result.clone(); let (actual_destination, host) = result.clone();
let result = (result.0.into_url(), result.1.into_uri()); let result = (result.0.into_https_url(), result.1.into_uri());
globals globals
.actual_destination_cache .actual_destination_cache
.write() .write()
.unwrap() .unwrap()
.insert(Box::<ServerName>::from(destination), result.clone()); .insert(Box::<ServerName>::from(destination), result.clone());
if actual_destination != host { if actual_destination.host() != host.host() {
globals.tls_name_override.write().unwrap().insert( globals.tls_name_override.write().unwrap().insert(
actual_destination.host(), actual_destination.host(),
webpki::DNSNameRef::try_from_ascii_str(&host.host()) webpki::DNSNameRef::try_from_ascii_str(&host.host())
@ -241,23 +241,23 @@ where
} }
#[tracing::instrument] #[tracing::instrument]
fn get_ip_with_port(destination_str: &str) -> Option<FederationDestination> { fn get_ip_with_port(destination_str: &str) -> Option<FedDest> {
if let Ok(destination) = destination_str.parse::<SocketAddr>() { if let Ok(destination) = destination_str.parse::<SocketAddr>() {
Some(FederationDestination::Literal(destination)) Some(FedDest::Literal(destination))
} else if let Ok(ip_addr) = destination_str.parse::<IpAddr>() { } else if let Ok(ip_addr) = destination_str.parse::<IpAddr>() {
Some(FederationDestination::Literal(SocketAddr::new(ip_addr, 8448))) Some(FedDest::Literal(SocketAddr::new(ip_addr, 8448)))
} else { } else {
None None
} }
} }
#[tracing::instrument] #[tracing::instrument]
fn add_port_to_hostname(destination_str: &str) -> FederationDestination { fn add_port_to_hostname(destination_str: &str) -> FedDest {
let (host, port) = match destination_str.find(':') { let (host, port) = match destination_str.find(':') {
None => (destination_str, ":8448"), None => (destination_str, ":8448"),
Some(pos) => destination_str.split_at(pos), Some(pos) => destination_str.split_at(pos),
}; };
FederationDestination::Named(host.to_string(), port.to_string()) FedDest::Named(host.to_string(), port.to_string())
} }
/// Returns: actual_destination, host header /// Returns: actual_destination, host header
@ -267,65 +267,66 @@ fn add_port_to_hostname(destination_str: &str) -> FederationDestination {
async fn find_actual_destination( async fn find_actual_destination(
globals: &crate::database::globals::Globals, globals: &crate::database::globals::Globals,
destination: &'_ ServerName, destination: &'_ ServerName,
) -> (FederationDestination, FederationDestination) { ) -> (FedDest, FedDest) {
let destination_str = destination.as_str().to_owned(); let destination_str = destination.as_str().to_owned();
let mut hostname = destination_str.clone(); let mut hostname = destination_str.clone();
let actual_destination = match get_ip_with_port(&destination_str) { let actual_destination = match get_ip_with_port(&destination_str) {
Some(host_port) => { Some(host_port) => {
// 1: IP literal with provided or default port // 1: IP literal with provided or default port
host_port host_port
} }
None => { None => {
if let Some(pos) = destination_str.find(':') { if let Some(pos) = destination_str.find(':') {
// 2: Hostname with included port // 2: Hostname with included port
let (host, port) = destination_str.split_at(pos); let (host, port) = destination_str.split_at(pos);
FederationDestination::Named(host.to_string(), port.to_string()) FedDest::Named(host.to_string(), port.to_string())
} else { } else {
match request_well_known(globals, &destination.as_str()).await { match request_well_known(globals, &destination.as_str()).await {
// 3: A .well-known file is available // 3: A .well-known file is available
Some(delegated_hostname) => { Some(delegated_hostname) => {
hostname = delegated_hostname.clone(); hostname = delegated_hostname.clone();
match get_ip_with_port(&delegated_hostname) { match get_ip_with_port(&delegated_hostname) {
Some(host_and_port) => host_and_port, // 3.1: IP literal in .well-known file Some(host_and_port) => host_and_port, // 3.1: IP literal in .well-known file
None => { None => {
if let Some(pos) = destination_str.find(':') { if let Some(pos) = destination_str.find(':') {
// 3.2: Hostname with port in .well-known file // 3.2: Hostname with port in .well-known file
let (host, port) = destination_str.split_at(pos); let (host, port) = destination_str.split_at(pos);
FederationDestination::Named(host.to_string(), port.to_string()) FedDest::Named(host.to_string(), port.to_string())
} else { } else {
match query_srv_record(globals, &delegated_hostname).await { match query_srv_record(globals, &delegated_hostname).await {
// 3.3: SRV lookup successful // 3.3: SRV lookup successful
Some(hostname) => hostname, Some(hostname) => hostname,
// 3.4: No SRV records, just use the hostname from .well-known // 3.4: No SRV records, just use the hostname from .well-known
None => add_port_to_hostname(&delegated_hostname), None => add_port_to_hostname(&delegated_hostname),
}
} }
} }
} }
} }
// 4: No .well-known or an error occured }
None => { // 4: No .well-known or an error occured
match query_srv_record(globals, &destination_str).await { None => {
// 4: SRV record found match query_srv_record(globals, &destination_str).await {
Some(hostname) => hostname, // 4: SRV record found
// 5: No SRV record found Some(hostname) => hostname,
None => add_port_to_hostname(&destination_str), // 5: No SRV record found
} None => add_port_to_hostname(&destination_str),
} }
} }
} }
} }
};
let hostname = get_ip_with_port(&hostname).unwrap_or_else(|| {
match hostname.find(':') {
Some(pos) => {
let (host, port) = hostname.split_at(pos);
FederationDestination::Named(host.to_string(), port.to_string())
}
None => FederationDestination::Named(hostname, "".to_string())
} }
}); };
let hostname = if let Ok(addr) = hostname.parse::<SocketAddr>() {
FedDest::Literal(addr)
} else if let Ok(addr) = hostname.parse::<IpAddr>() {
FedDest::Named(addr.to_string(), "".to_string())
} else if let Some(pos) = hostname.find(':') {
let (host, port) = hostname.split_at(pos);
FedDest::Named(host.to_string(), port.to_string())
} else {
FedDest::Named(hostname, "".to_string())
};
(actual_destination, hostname) (actual_destination, hostname)
} }
@ -333,16 +334,20 @@ async fn find_actual_destination(
async fn query_srv_record( async fn query_srv_record(
globals: &crate::database::globals::Globals, globals: &crate::database::globals::Globals,
hostname: &'_ str, hostname: &'_ str,
) -> Option<FederationDestination> { ) -> Option<FedDest> {
if let Ok(Some(host_port)) = globals if let Ok(Some(host_port)) = globals
.dns_resolver() .dns_resolver()
.srv_lookup(format!("_matrix._tcp.{}", hostname)) .srv_lookup(format!("_matrix._tcp.{}", hostname))
.await .await
.map(|srv| { .map(|srv| {
srv.iter().next().map(|result| { srv.iter().next().map(|result| {
FederationDestination::Named( FedDest::Named(
result.target().to_string().trim_end_matches('.').to_string(), result
format!(":{}", result.port()) .target()
.to_string()
.trim_end_matches('.')
.to_string(),
format!(":{}", result.port()),
) )
}) })
}) })

Loading…
Cancel
Save