ruma_identifiers_validation/
server_name.rs
1use crate::error::Error;
2
3pub fn validate(server_name: &str) -> Result<(), Error> {
4 use std::net::Ipv6Addr;
5
6 if server_name.is_empty() {
7 return Err(Error::InvalidServerName);
8 }
9
10 let end_of_host = if server_name.starts_with('[') {
11 let end_of_ipv6 = match server_name.find(']') {
12 Some(idx) => idx,
13 None => return Err(Error::InvalidServerName),
14 };
15
16 if server_name[1..end_of_ipv6].parse::<Ipv6Addr>().is_err() {
17 return Err(Error::InvalidServerName);
18 }
19
20 end_of_ipv6 + 1
21 } else {
22 #[allow(clippy::unnecessary_lazy_evaluations)]
23 let end_of_host = server_name.find(':').unwrap_or_else(|| server_name.len());
24
25 if server_name[..end_of_host]
26 .bytes()
27 .any(|byte| !(byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'.'))
28 {
29 return Err(Error::InvalidServerName);
30 }
31
32 end_of_host
33 };
34
35 if server_name.len() != end_of_host
36 && (
37 server_name.as_bytes()[end_of_host] != b':'
39 || server_name[end_of_host + 1..].parse::<u16>().is_err()
41 )
42 {
43 Err(Error::InvalidServerName)
44 } else {
45 Ok(())
46 }
47}