use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::OnceLock;
use php_std::mb;
use crate::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Section {
Icann,
Private,
Other,
}
#[derive(Debug, Default)]
pub struct PublicSuffixList {
rules: HashMap<Box<str>, Section>,
exceptions: HashSet<Box<str>>,
wildcards: HashSet<Box<str>>,
}
static GLOBAL: OnceLock<PublicSuffixList> = OnceLock::new();
impl PublicSuffixList {
pub const EMBEDDED: &'static str = include_str!("../data/public-suffix-list.txt");
pub fn parse(source: &str) -> Result<Self, Error> {
let mut list = PublicSuffixList::default();
for (n, line) in source.split('\n').enumerate() {
if line.is_empty() {
continue;
}
let Some((kind, rule)) = line.split_once('\t') else {
return Err(Error::Data(format!("line {}: expected `<section>\\t<rule>`", n + 1)));
};
let section = match kind {
"#" => continue,
"ICANN" => Section::Icann,
"PRIVATE" => Section::Private,
"-" => Section::Other,
other => return Err(Error::Data(format!("line {}: unknown section `{other}`", n + 1))),
};
if let Some(rest) = rule.strip_prefix('!') {
list.exceptions.insert(rest.into());
}
if let Some(rest) = rule.strip_prefix("*.") {
list.wildcards.insert(rest.into());
}
list.rules.insert(rule.into(), section);
}
Ok(list)
}
pub fn load(path: &Path) -> Result<Self, Error> {
let source = std::fs::read_to_string(path).map_err(|e| Error::Data(format!("{}: {e}", path.display())))?;
Self::parse(&source)
}
pub fn embedded() -> Self {
match Self::parse(Self::EMBEDDED) {
Ok(list) => list,
Err(error) => panic!("the embedded Public Suffix List does not parse: {error}"),
}
}
pub fn install(self) -> bool {
GLOBAL.set(self).is_ok()
}
pub fn global() -> &'static Self {
GLOBAL.get_or_init(Self::embedded)
}
pub fn len(&self) -> usize {
self.rules.len()
}
pub fn is_empty(&self) -> bool {
self.rules.is_empty()
}
pub fn section(&self, rule: &str) -> Option<Section> {
self.rules.get(rule).copied()
}
}
#[derive(Debug, Clone, Copy)]
enum Rule {
None,
Exception(usize),
Exact(usize),
Wildcard(usize),
}
#[derive(Debug, Clone, Copy)]
struct Parts {
suffix: usize,
rule: Rule,
name: (usize, usize),
sub: usize,
}
#[derive(Debug, Clone)]
pub struct Domain<'l> {
domain: String,
list: Option<&'l PublicSuffixList>,
parts: OnceLock<Parts>,
}
fn empty(s: &str) -> bool {
s.is_empty() || s == "0"
}
fn cut_end(s: &str, cut: usize) -> usize {
s.char_indices().rev().nth(cut - 1).map_or(0, |(at, _)| at)
}
impl Domain<'static> {
pub fn new(domain: &(impl AsRef<[u8]> + ?Sized)) -> Result<Self, Error> {
Self::build(domain.as_ref(), None)
}
}
impl<'l> Domain<'l> {
pub fn with_list(domain: &(impl AsRef<[u8]> + ?Sized), list: &'l PublicSuffixList) -> Result<Self, Error> {
Self::build(domain.as_ref(), Some(list))
}
fn build(domain: &[u8], list: Option<&'l PublicSuffixList>) -> Result<Self, Error> {
if domain.starts_with(b"http://") || domain.starts_with(b"https://") {
let shown = String::from_utf8_lossy(domain);
return Err(Error::exception(format!("'{shown}' must be a valid domain or hostname"), 0));
}
let lower = mb::mb_strtolower(domain);
let domain = String::from_utf8(lower).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned());
Ok(Self { domain, list, parts: OnceLock::new() })
}
fn list(&self) -> &'l PublicSuffixList {
match self.list {
Some(list) => list,
None => PublicSuffixList::global(),
}
}
fn find(&self) -> (usize, Rule) {
let d = self.domain.as_str();
let list = self.list();
let mut start = 0;
loop {
let joined = &d[start..];
let next_start = joined.find('.').map(|p| start + p + 1);
let next = next_start.unwrap_or(d.len());
if list.exceptions.contains(joined) {
return (next, Rule::Exception(start));
}
if list.rules.contains_key(joined) {
return (start, Rule::Exact(start));
}
if list.wildcards.contains(&d[next..]) {
return (start, Rule::Wildcard(next));
}
match next_start {
Some(n) => start = n,
None => return (d.len(), Rule::None),
}
}
}
fn parts(&self) -> &Parts {
self.parts.get_or_init(|| {
let d = self.domain.as_str();
let (suffix, rule) = self.find();
let counted = if empty(&d[suffix..]) { self.tld() } else { &d[suffix..] };
let suffix_len = 1 + counted.chars().count();
let end = cut_end(d, suffix_len);
let name = (d[..end].rfind('.').map_or(0, |p| p + 1), end);
let name_text = &d[name.0..name.1];
let name_len = if empty(name_text) { 0 } else { 1 + name_text.chars().count() };
Parts { suffix, rule, name, sub: cut_end(d, name_len + suffix_len) }
})
}
pub fn get(&self) -> &str {
&self.domain
}
pub fn tld(&self) -> &str {
self.domain.rsplit('.').next().unwrap_or("")
}
pub fn suffix(&self) -> &str {
&self.domain[self.parts().suffix..]
}
pub fn rule(&self) -> Cow<'_, str> {
match self.parts().rule {
Rule::None => Cow::Borrowed(""),
Rule::Exception(at) => Cow::Owned(format!("!{}", &self.domain[at..])),
Rule::Exact(at) => Cow::Borrowed(&self.domain[at..]),
Rule::Wildcard(at) => Cow::Owned(format!("*.{}", &self.domain[at..])),
}
}
pub fn name(&self) -> &str {
let (start, end) = self.parts().name;
&self.domain[start..end]
}
pub fn sub(&self) -> &str {
&self.domain[..self.parts().sub]
}
pub fn apex(&self) -> String {
let (name, suffix) = (self.name(), self.suffix());
let mut apex = String::with_capacity(name.len() + 1 + suffix.len());
apex.push_str(name);
apex.push('.');
apex.push_str(suffix);
apex
}
pub fn registerable(&self) -> String {
if !self.is_known() {
return String::new();
}
self.apex()
}
pub fn is_known(&self) -> bool {
self.list().rules.contains_key(&*self.rule())
}
pub fn is_icann(&self) -> bool {
self.list().section(&self.rule()) == Some(Section::Icann)
}
pub fn is_private(&self) -> bool {
self.list().section(&self.rule()) == Some(Section::Private)
}
pub fn is_test(&self) -> bool {
matches!(self.tld(), "test" | "localhost")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn embedded_list_parses_whole() {
let list = PublicSuffixList::parse(PublicSuffixList::EMBEDDED).expect("the embedded list parses");
let rules =
PublicSuffixList::EMBEDDED.lines().filter(|line| !line.is_empty() && !line.starts_with("#\t")).count();
assert_eq!(list.len(), rules);
assert!(rules > 9000, "the embedded list has {rules} rules");
}
fn list() -> PublicSuffixList {
PublicSuffixList::parse("#\tit's\nICANN\tcom\nICANN\tco.uk\nICANN\t*.ck\nICANN\t!www.ck\nPRIVATE\tgithub.io\n")
.unwrap()
}
#[test]
fn parts() {
let list = list();
let d = Domain::with_list("Mail.Sub.Example.CO.UK", &list).unwrap();
assert_eq!(d.get(), "mail.sub.example.co.uk");
assert_eq!((d.suffix(), &*d.rule(), d.tld()), ("co.uk", "co.uk", "uk"));
assert_eq!((d.name(), d.sub(), d.registerable()), ("example", "mail.sub", "example.co.uk".into()));
assert!(d.is_known() && d.is_icann() && !d.is_private());
let d = Domain::with_list("a.b.ck", &list).unwrap();
assert_eq!((d.suffix(), &*d.rule(), d.name()), ("b.ck", "*.ck", "a"));
let d = Domain::with_list("www.ck", &list).unwrap();
assert_eq!((d.suffix(), &*d.rule(), d.name()), ("ck", "!www.ck", "www"));
let d = Domain::with_list("me.github.io", &list).unwrap();
assert!(d.is_private());
let d = Domain::with_list("example.test", &list).unwrap();
assert_eq!((d.suffix(), &*d.rule(), d.name(), d.sub()), ("", "", "example", ""));
assert!(!d.is_known() && d.is_test());
assert_eq!(d.registerable(), "");
let d = Domain::with_list("x.0.com", &list).unwrap();
assert_eq!((d.name(), d.sub()), ("0", "x.0"));
}
#[test]
fn urls() {
let e = Domain::new("http://example.com").unwrap_err();
assert_eq!(e.to_string(), "'http://example.com' must be a valid domain or hostname");
assert_eq!(e.php_class(), "Exception");
}
#[test]
fn embedded() {
let list = PublicSuffixList::embedded();
assert!(list.len() > 9000);
assert_eq!(list.section("com"), Some(Section::Icann));
assert_eq!(list.section("github.io"), Some(Section::Private));
assert!(PublicSuffixList::parse("ICANN com").is_err() && PublicSuffixList::parse("X\tcom").is_err());
}
}