ferron_common/util/
match_hostname.rs1pub fn match_hostname(hostname: Option<&str>, req_hostname: Option<&str>) -> bool {
3 if hostname.is_none() || hostname == Some("*") {
4 return true;
5 }
6
7 if let (Some(hostname), Some(req_hostname)) = (hostname, req_hostname) {
8 if hostname.starts_with("*.") && hostname != "*." {
9 let hostnames_root = &hostname[2..];
10 if req_hostname == hostnames_root
11 || (req_hostname.len() > hostnames_root.len() && req_hostname.ends_with(&format!(".{hostnames_root}")[..]))
12 {
13 return true;
14 }
15 } else if req_hostname == hostname {
16 return true;
17 }
18 }
19
20 false
21}
22
23#[cfg(test)]
24mod tests {
25 use super::*;
26
27 #[test]
28 fn should_return_true_if_hostname_is_undefined() {
29 assert!(match_hostname(None, Some("example.com")));
30 }
31
32 #[test]
33 fn should_return_true_if_hostname_is_star() {
34 assert!(match_hostname(Some("*"), Some("example.com")));
35 }
36
37 #[test]
38 fn should_return_true_if_req_hostname_matches_hostname_exactly() {
39 assert!(match_hostname(Some("example.com"), Some("example.com")));
40 }
41
42 #[test]
43 fn should_return_false_if_req_hostname_does_not_match_hostname_exactly() {
44 assert!(!match_hostname(Some("example.com"), Some("example.org")));
45 }
46
47 #[test]
48 fn should_return_true_if_hostname_starts_with_star_dot_and_req_hostname_matches_the_root() {
49 assert!(match_hostname(Some("*.example.com"), Some("sub.example.com")));
50 }
51
52 #[test]
53 fn should_return_false_if_hostname_starts_with_star_dot_and_req_hostname_does_not_match_the_root() {
54 assert!(!match_hostname(Some("*.example.com"), Some("example.org")));
55 }
56
57 #[test]
58 fn should_return_true_if_hostname_starts_with_star_dot_and_req_hostname_is_the_root() {
59 assert!(match_hostname(Some("*.example.com"), Some("example.com")));
60 }
61
62 #[test]
63 fn should_return_false_if_hostname_is_star_dot() {
64 assert!(!match_hostname(Some("*."), Some("example.com")));
65 }
66
67 #[test]
68 fn should_return_false_if_req_hostname_is_undefined() {
69 assert!(!match_hostname(Some("example.com"), None));
70 }
71
72 #[test]
73 fn should_return_false_if_hostname_does_not_start_with_star_dot_and_req_hostname_does_not_match() {
74 assert!(!match_hostname(Some("sub.example.com"), Some("example.com")));
75 }
76
77 #[test]
78 fn should_return_true_if_hostname_starts_with_star_dot_and_req_hostname_matches_the_root_with_additional_subdomains()
79 {
80 assert!(match_hostname(Some("*.example.com"), Some("sub.sub.example.com")));
81 }
82
83 #[test]
84 fn should_return_false_if_hostname_starts_with_star_dot_and_req_hostname_does_not_match_the_root_with_additional_subdomains(
85 ) {
86 assert!(!match_hostname(Some("*.example.com"), Some("sub.sub.example.org")));
87 }
88}