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
use crate::error::Error;
pub fn validate(server_name: &str) -> Result<(), Error> {
use std::net::Ipv6Addr;
if server_name.is_empty() {
return Err(Error::InvalidServerName);
}
// As per spec, the server name can be a hostname plus an optional port.
//
// The hostname is defined as follows:
//
// hostname = IPv4address / "[" IPv6address "]" / dns-name
//
// 1. IPv4 addresses are at most 15 characters long.
// 2. IPv6 addresses are at most 45 characters long.
// 3. DNS names are at most 255 characters long.
//
// The optional port must be separated by a ":" character followed by at most 5 digits.
//
// This brings the maximum allowed length of a server name to 255 + 1 + 5 => 261.
//
// [1]: https://spec.matrix.org/v1.19/appendices/#server-name
if server_name.len() > 261 {
return Err(Error::InvalidServerName);
}
let end_of_host = if server_name.starts_with('[') {
let Some(end_of_ipv6) = server_name.find(']') else {
return Err(Error::InvalidServerName);
};
if server_name[1..end_of_ipv6].parse::<Ipv6Addr>().is_err() {
return Err(Error::InvalidServerName);
}
end_of_ipv6 + 1
} else {
#[allow(clippy::unnecessary_lazy_evaluations)]
let end_of_host = server_name.find(':').unwrap_or_else(|| server_name.len());
if end_of_host == 0 {
return Err(Error::InvalidServerName);
}
if server_name[..end_of_host]
.bytes()
.any(|byte| !(byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'.'))
{
return Err(Error::InvalidServerName);
}
end_of_host
};
if server_name.len() != end_of_host
&& (
// hostname is followed by something other than ":port"
server_name.as_bytes()[end_of_host] != b':'
// the remaining characters after ':' are not a valid port
|| server_name[end_of_host + 1..].parse::<u16>().is_err()
)
{
Err(Error::InvalidServerName)
} else {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::validate;
use crate::user_id;
#[test]
fn rejects_hostless_server_name_with_port() {
assert!(validate(":8448").is_err());
}
#[test]
fn rejects_user_id_with_hostless_server_name() {
assert!(user_id::validate("@alice::8448").is_err());
}
}