Debian Codegraph @

src/url_parser/mod.rs

raw symbols SCIP
1 //! Simplified URL parsing infrastructure, including the domain resolver
2 //! implementation if the `embedded-domain-resolver` feature is disabled.
3
4 mod parser;
5 // mod parser_regex;
6
7 #[cfg(not(feature = "embedded-domain-resolver"))]
8 static DOMAIN_RESOLVER: once_cell::sync::OnceCell<Box<dyn ResolvesDomain>> =
9 once_cell::sync::OnceCell::new();
10
11 /// Sets the library's domain resolver implementation.
12 ///
13 /// If the `embedded-domain-resolver` feature is disabled and the library is
14 /// used without this having been set, panics may occur!
15 ///
16 /// Will return the resolver if it has already been previously set.
17 #[cfg(not(feature = "embedded-domain-resolver"))]
18 pub fn set_domain_resolver(
19 resolver: Box<dyn ResolvesDomain>,
20 ) -> Result<(), Box<dyn ResolvesDomain>> {
21 DOMAIN_RESOLVER.set(resolver)
22 }
23
24 /// Default `addr`-based domain resolution implementation used when the
25 /// `embedded-domain-resolver` feature is enabled.
26 #[cfg(feature = "embedded-domain-resolver")]
27 struct DefaultResolver;
28
29 #[cfg(feature = "embedded-domain-resolver")]
30 impl ResolvesDomain for DefaultResolver {
31 fn get_host_domain(&self, host: &str) -> (usize, usize) {
32 use addr::parser::DomainName;
33 use addr::psl::List;
34
35 if host.is_empty() {
36 (0, 0)
37 } else {
38 match List.parse_domain_name(host) {
39 Err(_e) => (0, host.len()),
40 Ok(domain) => {
41 let host_len = host.len();
42 let domain_len = domain.root().unwrap_or_else(|| domain.suffix()).len();
43 (host_len - domain_len, host_len)
44 }
45 }
46 }
47 }
48 }
49
50 /// Required trait for any domain resolution implementation used with this
51 /// crate.
52 pub trait ResolvesDomain: Send + Sync {
53 /// Return the start and end indices of the domain (eTLD+1) of the given hostname.
54 ///
55 /// If there isn't a valid domain, `(0, host.len())` should be returned.
56 ///
57 /// ```
58 /// # use adblock::url_parser::ResolvesDomain;
59 /// # /// I'd use DefaultResolver here, but I can't use private structs in doctests.
60 /// # /// Enjoy this mock implementation instead :(
61 /// # struct Resolver;
62 /// # impl ResolvesDomain for Resolver {
63 /// # fn get_host_domain(&self, host: &str) -> (usize, usize) {
64 /// # match host {
65 /// # "api.m.example.com" => (6, 17),
66 /// # "a.b.co.uk" => (2, 9),
67 /// # _ => unreachable!()
68 /// # }
69 /// # }
70 /// # }
71 /// # let resolver = Resolver;
72 /// let host = "api.m.example.com";
73 /// let (start, end) = resolver.get_host_domain(host);
74 /// assert_eq!(&host[start..end], "example.com");
75 ///
76 /// let host = "a.b.co.uk";
77 /// let (start, end) = resolver.get_host_domain(host);
78 /// assert_eq!(&host[start..end], "b.co.uk");
79 /// ```
80 fn get_host_domain(&self, host: &str) -> (usize, usize);
81 }
82
83 /// Parsed URL representation.
84 pub struct RequestUrl {
85 pub url: String,
86 schema_end: usize,
87 pub hostname_pos: (usize, usize),
88 domain: (usize, usize),
89 }
90
91 impl RequestUrl {
92 pub fn schema(&self) -> &str {
93 &self.url[..self.schema_end]
94 }
95 pub fn hostname(&self) -> &str {
96 &self.url[self.hostname_pos.0..self.hostname_pos.1]
97 }
98 pub fn domain(&self) -> &str {
99 &self.url[self.hostname_pos.0 + self.domain.0..self.hostname_pos.0 + self.domain.1]
100 }
101 }
102
103 /// Return the start and end indices of the domain of the given hostname.
104 pub(crate) fn get_host_domain(host: &str) -> (usize, usize) {
105 #[cfg(not(feature = "embedded-domain-resolver"))]
106 let domain_resolver = DOMAIN_RESOLVER.get().expect("An external domain resolver must be set when the `embedded-domain-resolver` feature is disabled.");
107 #[cfg(feature = "embedded-domain-resolver")]
108 let domain_resolver = DefaultResolver;
109
110 domain_resolver.get_host_domain(host)
111 }
112
113 /// Return the string representation of the host (domain or IP address) for
114 /// this URL, if any together with the URL.
115 ///
116 /// As part of hostname parsing, punycode decoding is used to convert URLs with
117 /// UTF characters to plain ASCII ones. Serialisation then contains this
118 /// decoded URL that is used for further matching.
119 pub fn parse_url(url: &str) -> Option<RequestUrl> {
120 let parsed = parser::Hostname::parse(url).ok();
121 parsed.and_then(|h| match h.host_str() {
122 Some(_host) => Some(RequestUrl {
123 url: h.url_str().to_owned(),
124 schema_end: h.scheme_end,
125 hostname_pos: (h.host_start, h.host_end),
126 domain: get_host_domain(&h.url_str()[h.host_start..h.host_end]),
127 }),
128 _ => None,
129 })
130 }
131
132 #[cfg(all(test, feature = "embedded-domain-resolver"))]
133 mod embedded_domain_resolver_tests {
134 use super::*;
135
136 #[test]
137 fn test_get_host_domain() {
138 fn domain(host: &str) -> &str {
139 let resolver = DefaultResolver;
140 let (a, b) = resolver.get_host_domain(host);
141 &host[a..b]
142 }
143 assert_eq!(domain("www.google.com"), "google.com");
144 assert_eq!(domain("google.com."), "google.com.");
145 assert_eq!(domain("a.b.co.uk"), "b.co.uk");
146 assert_eq!(domain("foo.bar"), "foo.bar");
147 }
148 }