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
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
use crate::errors::*;

use chrootable_https::Client;
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::lazy::LazyInit;


#[derive(Debug, PartialEq)]
pub struct DnsName {
    pub fulldomain: Option<String>,
    pub root: String,
    pub suffix: String,
}

#[derive(Debug)]
pub enum PslReader {
    Reader(File),
    String(String),
}

impl PslReader {
    pub fn open_or_download<F>(cache_dir: &Path, indicator: F) -> Result<PslReader>
        where
            F: Fn(Box<dyn Fn() -> Result<PslReader>>) -> Result<PslReader>
    {
        let path = Self::path(cache_dir)?;
        let reader = match Self::open_from(&path) {
            Ok(r) => r,
            Err(_) => indicator(Box::new(move || {
                PslReader::download(&path, publicsuffix::LIST_URL)?;
                Self::open_from(&path)
            }))?,
        };
        Ok(reader)
    }

    pub fn open(cache_dir: &Path) -> Result<PslReader> {
        let path = Self::path(cache_dir)?;
        Self::open_from(&path)
    }

    pub fn open_from(path: &Path) -> Result<PslReader> {
        let file = File::open(path)?;
        Ok(PslReader::Reader(file))
    }

    pub fn path(cache_dir: &Path) -> Result<PathBuf> {
        // use system path if exists
        let path = Path::new("/usr/share/publicsuffix/public_suffix_list.dat");
        if path.exists() {
            return Ok(path.to_path_buf());
        }

        // else, use local cache
        let path = cache_dir
            .join("public_suffix_list.dat");
        Ok(path)
    }

    pub fn download(path: &Path, url: &str) -> Result<()> {
        let client = Client::with_system_resolver_v4()?;
        let resp = client.get(url)
            .wait_for_response()
            .context("http request failed")?;
        fs::write(path, &resp.body)?;
        Ok(())
    }
}

impl LazyInit<Arc<Psl>> for PslReader {
    fn initialize(self) -> Result<Arc<Psl>> {
        let list = match self {
            PslReader::Reader(file) => publicsuffix::List::from_reader(file),
            PslReader::String(s) => publicsuffix::List::from_str(&s),
        };

        let list = list
            .map_err(|e| format_err!("Failed to load public suffix list: {}", e))?;

        Ok(Arc::new(Psl {
            list,
        }))
    }
}

#[derive(Debug)]
pub struct Psl {
    list: publicsuffix::List,
}

impl Psl {
    pub fn parse_dns_name(&self, name: &str) -> Result<DnsName> {
        let dns_name = self.list.parse_dns_name(name)
            .map_err(|e| format_err!("Failed to parse dns_name: {}", e))?;

        let (root, suffix) = if let Some(domain) = dns_name.domain() {
            let root = domain.to_string();
            if let Some(suffix) = domain.suffix() {
                (root, suffix.to_string())
            } else {
                // XXX: not sure if this is reachable
                (root.clone(), root)
            }
        } else {
            // this is technically a tld, but support eg. a.prod.fastly.net anyway
            // XXX: consider forcing domain to be in self.list.private()
            (name.to_string(), name.to_string())
        };

        let fulldomain = if root.as_str() != name {
            Some(name.to_string())
        } else {
            None
        };

        Ok(DnsName {
            fulldomain,
            root,
            suffix,
        })
    }
}


#[cfg(test)]
mod tests {
    use super::*;

    fn init() -> Arc<Psl> {
        PslReader::String(r#"
// ===BEGIN ICANN DOMAINS===
com
// ===END ICANN DOMAINS===
// ===BEGIN PRIVATE DOMAINS===
a.prod.fastly.net
// ===END PRIVATE DOMAINS===
"#.into()).initialize().unwrap()
    }

    #[test]
    fn test_psl_example_com() {
        let x = init().parse_dns_name("example.com").expect("parse_dns_name");
        assert_eq!(x, DnsName {
            fulldomain: None,
            root: "example.com".into(),
            suffix: "com".into(),
        });
    }

    #[test]
    fn test_psl_www_example_com() {
        let x = init().parse_dns_name("www.example.com").expect("parse_dns_name");
        assert_eq!(x, DnsName {
            fulldomain: Some("www.example.com".into()),
            root: "example.com".into(),
            suffix: "com".into(),
        });
    }

    #[test]
    fn test_psl_com() {
        let x = init().parse_dns_name("com").expect("parse_dns_name");
        assert_eq!(x, DnsName {
            fulldomain: None,
            root: "com".into(),
            suffix: "com".into(),
        });
    }

    #[test]
    fn test_psl_a_b_c_d_e_f_g_com() {
        let x = init().parse_dns_name("a.b.c.d.e.f.g.com").expect("parse_dns_name");
        assert_eq!(x, DnsName {
            fulldomain: Some("a.b.c.d.e.f.g.com".into()),
            root: "g.com".into(),
            suffix: "com".into(),
        });
    }

    #[test]
    fn test_psl_empty() {
        let x = init().parse_dns_name("").is_err();
        assert!(x);
    }

    #[test]
    fn test_psl_asdfinvalid() {
        let x = init().parse_dns_name("asdfinvalid").expect("parse_dns_name");
        assert_eq!(x, DnsName {
            fulldomain: None,
            root: "asdfinvalid".into(),
            suffix: "asdfinvalid".into(),
        });
    }

    #[test]
    fn test_psl_www_example_asdfinvalid() {
        let x = init().parse_dns_name("www.example.asdfinvalid").expect("parse_dns_name");
        assert_eq!(x, DnsName {
            fulldomain: Some("www.example.asdfinvalid".into()),
            root: "example.asdfinvalid".into(),
            suffix: "asdfinvalid".into(),
        });
    }

    #[test]
    fn test_psl_a_prod_fastly_net() {
        let x = init().parse_dns_name("a.prod.fastly.net").expect("parse_dns_name");
        assert_eq!(x, DnsName {
            fulldomain: None,
            root: "a.prod.fastly.net".into(),
            suffix: "a.prod.fastly.net".into(),
        });
    }

    #[test]
    fn test_psl_www_a_prod_fastly_net() {
        let x = init().parse_dns_name("www.a.prod.fastly.net").expect("parse_dns_name");
        assert_eq!(x, DnsName {
            fulldomain: None,
            root: "www.a.prod.fastly.net".into(),
            suffix: "a.prod.fastly.net".into(),
        });
    }
}