~nickbp/kapiti

ref: 41895a73626b9e101ebd940b9de825c18ceb27f1 kapiti/src/filter/filter.rs -rw-r--r-- 7.9 KiB
41895a73Nick Parker Only build binary in docker build 5 months ago
                                                                                
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
228
229
230
231
232
233
234
235
236
237
use std::path::{Path, PathBuf};
use std::vec::Vec;

use anyhow::{Context, Result};
use hyper::Client;
use sha2::{Digest, Sha256};

use crate::filter::{downloader, path, reader};
use crate::{http, hyper_smol};

/// An iterator that goes over the parent domains of a provided child domain.
/// For example, www.domain.com => [www.domain.com, domain.com, com]
struct DomainParentIter<'a> {
    domain: &'a String,
    start_idx: usize,
}

impl<'a> DomainParentIter<'a> {
    fn new(domain: &'a String) -> DomainParentIter<'a> {
        DomainParentIter {
            domain,
            start_idx: 0,
        }
    }
}

impl<'a> Iterator for DomainParentIter<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<&'a str> {
        if self.start_idx >= self.domain.len() {
            // Seeked past end of domain string, nothing left
            None
        } else {
            // Collect this result: everything from start_idx
            let remainder = &self.domain[self.start_idx..];
            // Update start for next result
            match remainder.find('.') {
                Some(idx) => {
                    // idx is within remainder's address space, which starts at start_idx
                    // add 1 to seek past the '.' itself
                    self.start_idx += idx + 1;
                }
                None => {
                    self.start_idx = self.domain.len();
                }
            }
            Some(remainder)
        }
    }
}

pub struct Filter {
    overrides: Vec<reader::FilterEntries>,
    blocks: Vec<reader::FilterEntries>,
}

impl Filter {
    pub fn new() -> Filter {
        Filter {
            overrides: vec![],
            blocks: vec![],
        }
    }

    pub fn update_entries(self: &mut Filter, entrieses: Vec<reader::FilterEntries>) {
        for entries in entrieses {
            match entries.filter_type {
                reader::FilterType::BLOCK => upsert_entries(&mut self.blocks, entries),
                reader::FilterType::OVERRIDE => upsert_entries(&mut self.overrides, entries),
            }
        }
    }

    pub fn set_hardcoded_block(self: &mut Filter, block_names: &[&str]) -> Result<()> {
        let hardcoded_entries = reader::block_hardcoded(block_names)?;
        upsert_entries(&mut self.blocks, hardcoded_entries);
        Ok(())
    }

    pub fn check(self: &Filter, host: &String) -> Option<(&Option<reader::FileInfo>, &reader::FilterEntry)> {
        // Go over domains in ancestor order, checking all blocks for each ancestor.
        // For example check all files for 'www.example.com', then each again for 'example.com'.
        // This allows file B with 'www.example.com' to take precedence over file A with 'example.com'

        // Meanwhile if two files mention the exact same domain then the first file in the list wins.
        // So if file A says "127.0.0.1" and file B says "172.16.0.1" then "127.0.0.1" wins.

        for domain_str in DomainParentIter::new(&host) {
            let domain = domain_str.to_string();
            for override_entry in &self.overrides {
                match override_entry.get(&domain) {
                    // Found in an override file: Tell upstream to let it through or use provided override value
                    Some(entry) => return Some((&override_entry.info, entry)),
                    None => {}
                }
            }
            for block in &self.blocks {
                match block.get(&domain) {
                    // Found in block: Tell upstream to block it or use filter-provided override
                    Some(entry) => return Some((&block.info, entry)),
                    None => {}
                }
            }
        }

        return None;
    }
}

/// Returns the local path where the file was downloaded,
/// and whether the file was updated (true) or the update was skipped (false)
pub async fn update_url(
    fetch_client: &Client<hyper_smol::SmolConnector>,
    filters_dir: &PathBuf,
    uri_string: &String,
    timeout_ms: u64,
) -> Result<(String, bool)> {
    let fetcher = http::Fetcher::new(10 * 1024 * 1024, None);
    // We download files to the exact SHA of the URL string we were provided.
    // This is an easy way to avoid filename collisions in URLs: example1.com/hosts vs example2.com/hosts
    // If the user changes the URL string then that changes the SHA, perfect for "cache invalidation" purposes.
    let hosts_path_sha = Sha256::digest(uri_string.as_bytes());
    let download_path = Path::new(filters_dir).join(format!(
        "{:x}.sha256.{}",
        hosts_path_sha,
        path::ZSTD_EXTENSION
    ));
    let downloaded = downloader::update_file(
        fetch_client,
        &fetcher,
        uri_string,
        download_path.as_path(),
        timeout_ms,
    )
        .await?;
    Ok((
        download_path
            .to_str()
            .with_context(|| format!("busted download path: {:?}", download_path))?
        .to_string(),
        downloaded
    ))
}

fn upsert_entries(entries: &mut Vec<reader::FilterEntries>, new_entry: reader::FilterEntries) {
    if let Some(new_file_info) = &new_entry.info {
        // Before adding a new file entry, check for an existing file entry to be replaced/updated.
        for i in 0..entries.len() {
            let entry = entries.get(i).expect("incoherent vector size");
            if let Some(existing_file_info) = &entry.info {
                if existing_file_info.local_path == new_file_info.local_path {
                    // Delete or replace existing version
                    if new_entry.is_empty() {
                        entries.remove(i);
                    } else {
                        entries.insert(i, new_entry);
                    }
                    return;
                }
            }
        }
    }
    // Add new entry
    if !new_entry.is_empty() {
        entries.push(new_entry);
    }
}

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

    #[test]
    fn iter_empty() {
        let domain = "".to_string();
        let mut iter = DomainParentIter::new(&domain);
        assert_eq!(None, iter.next());
    }

    #[test]
    fn iter_com() {
        let domain = "com".to_string();
        let mut iter = DomainParentIter::new(&domain);
        assert_eq!(Some("com"), iter.next());
        assert_eq!(None, iter.next());
    }

    #[test]
    fn iter_domaincom() {
        let domain = "domain.com".to_string();
        let mut iter = DomainParentIter::new(&domain);
        assert_eq!(Some("domain.com"), iter.next());
        assert_eq!(Some("com"), iter.next());
        assert_eq!(None, iter.next());
    }

    #[test]
    fn iter_wwwdomaincom() {
        let domain = "www.domain.com".to_string();
        let mut iter = DomainParentIter::new(&domain);
        assert_eq!(Some("www.domain.com"), iter.next());
        assert_eq!(Some("domain.com"), iter.next());
        assert_eq!(Some("com"), iter.next());
        assert_eq!(None, iter.next());
    }

    #[test]
    fn iter_wwwngeeknz() {
        let domain = "www.n.geek.nz".to_string();
        let mut iter = DomainParentIter::new(&domain);
        assert_eq!(Some("www.n.geek.nz"), iter.next());
        assert_eq!(Some("n.geek.nz"), iter.next());
        assert_eq!(Some("geek.nz"), iter.next());
        assert_eq!(Some("nz"), iter.next());
        assert_eq!(None, iter.next());
    }

    #[test]
    fn iter_averylongteststringwithmanysegments() {
        let domain = "a.very-long.test.string.with-many.segments".to_string();
        let mut iter = DomainParentIter::new(&domain);
        assert_eq!(
            Some("a.very-long.test.string.with-many.segments"),
            iter.next()
        );
        assert_eq!(
            Some("very-long.test.string.with-many.segments"),
            iter.next()
        );
        assert_eq!(Some("test.string.with-many.segments"), iter.next());
        assert_eq!(Some("string.with-many.segments"), iter.next());
        assert_eq!(Some("with-many.segments"), iter.next());
        assert_eq!(Some("segments"), iter.next());
        assert_eq!(None, iter.next());
    }
}