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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;
use std::net::{AddrParseError, IpAddr, Ipv4Addr};
use std::str::FromStr;
use multistr::StringVec;
use multistr::Iter as SVIter;

/// Characters which aren't allowed in URLs.
static INVALID_CHARS: &[char] = &[
    '\0',
    '\u{0009}',
    '\u{000a}',
    '\u{000d}',
    '\u{0020}',
    '#',
    '%',
    '/',
    ':',
    '?',
    '@',
    '[',
    '\\',
    ']',
];

/// Data from a line in `/etc/hosts`.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct DataLine {
    ip: IpAddr,
    hosts: StringVec,
}
impl DataLine {
    /// Creates a new line from its raw parts.
    pub fn from_raw<'a, I: IntoIterator<Item = &'a str>>(ip: IpAddr, hosts: I) -> DataLine {
        DataLine {
            ip: ip,
            hosts: hosts.into_iter().collect(),
        }
    }

    /// Gets the IP for this line.
    pub fn ip(&self) -> IpAddr {
        self.ip
    }

    /// Iterates over the hosts on this line.
    pub fn hosts(&self) -> Hosts {
        Hosts { inner: Some(self.hosts.iter()) }
    }

    /// Expands this line, iterating over its host/IP pairs.
    pub fn pairs(&self) -> LinePairs {
        LinePairs {
            ip: self.ip,
            hosts: self.hosts.iter(),
        }
    }

    /// Expands this line, iterating over its host/IP pairs. (owned version)
    pub fn into_pairs(self) -> IntoPairs {
        IntoPairs {
            ip: self.ip,
            hosts: self.hosts,
        }
    }
}

/// Minifies a list of data lines.`
pub fn minify_lines(lines: &mut Vec<DataLine>) {
    let mut min = BTreeMap::new();
    for line in lines.drain(..) {
        min.entry(line.ip()).or_insert_with(Vec::new).extend(
            line.hosts().map(ToOwned::to_owned),
        );
    }
    for (ip, mut hosts) in min {
        hosts.sort();
        hosts.dedup();
        lines.push(DataLine::from_raw(ip, hosts.iter().map(|s| &**s)));
    }
}

/// Not actually made public; hack to get `Line::hosts` to work.
pub fn empty_hosts() -> Hosts<'static> {
    Hosts { inner: None }
}
pub fn empty_pairs() -> IntoPairs {
    IntoPairs {
        ip: IpAddr::from([0, 0, 0, 0]),
        hosts: StringVec::new(),
    }
}

/// Iterator over the hosts on a line.
pub struct Hosts<'a> {
    inner: Option<SVIter<'a, str>>,
}
impl<'a> Iterator for Hosts<'a> {
    type Item = &'a str;
    fn next(&mut self) -> Option<&'a str> {
        self.inner.as_mut().and_then(|inner| inner.next())
    }
}

/// Iterator over the host/IP pairs on a line.
pub struct LinePairs<'a> {
    ip: IpAddr,
    hosts: SVIter<'a, str>,
}
impl<'a> Iterator for LinePairs<'a> {
    type Item = (&'a str, IpAddr);
    fn next(&mut self) -> Option<(&'a str, IpAddr)> {
        self.hosts.next().map(|h| (h, self.ip))
    }
}

/// Iterator over the host/IP pairs on a line. (owned version)
pub struct IntoPairs {
    ip: IpAddr,
    hosts: StringVec,
}
impl Iterator for IntoPairs {
    type Item = (String, IpAddr);
    fn next(&mut self) -> Option<(String, IpAddr)> {
        self.hosts.pop_off().map(|h| (h, self.ip))
    }
}

/// Error parsing a line in `/etc/hosts`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DataParseError {
    /// The line didn't have a space between the host and IP.
    ///
    /// This includes any line that doesn't have an internal space; the host and IP are not actually
    /// checked.
    NoInternalSpace,

    /// The given host was actually an IPv4 address.
    HostWasIp(Ipv4Addr),

    /// The given host had an invalid character.
    BadHost(char, String),

    /// The IP failed to parse.
    BadIp(AddrParseError, String),
}
impl Error for DataParseError {
    fn description(&self) -> &str {
        match *self {
            DataParseError::NoInternalSpace => "line had no space between IP and hosts",
            DataParseError::HostWasIp(_) => "an IP was given where a domain should have been",
            DataParseError::BadHost(_, _) => {
                "a host was invalid because it contains an invalid character"
            }
            DataParseError::BadIp(_, _) => "could not parse IP",
        }
    }
    fn cause(&self) -> Option<&Error> {
        if let DataParseError::BadIp(ref err, _) = *self {
            Some(err)
        } else {
            None
        }
    }
}
impl fmt::Display for DataParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            DataParseError::NoInternalSpace => write!(f, "line had no space between IP and hosts"),
            DataParseError::HostWasIp(ref ip) => {
                write!(f, "the IP {} was given instead of a domain", ip)
            }
            DataParseError::BadHost(ref ch, ref host) => {
                write!(
                    f,
                    "the host {:?} is invalid because it contains {:?}",
                    host,
                    ch
                )
            }
            DataParseError::BadIp(_, ref ip) => write!(f, "could not parse {:?} as an IP", ip),
        }
    }
}

impl FromStr for DataLine {
    type Err = DataParseError;
    fn from_str(s: &str) -> Result<DataLine, DataParseError> {
        let s = s.trim();
        if let Some(idx) = s.find(char::is_whitespace) {
            let ip = s[..idx].parse().map_err(|err| {
                DataParseError::BadIp(err, s[..idx].to_owned())
            })?;
            let mut hosts = StringVec::new();
            for host in s[idx..].split_whitespace() {
                // https://url.spec.whatwg.org/#host-parsing
                if let Some(idx) = host.find(INVALID_CHARS) {
                    return Err(DataParseError::BadHost(
                        host[idx..].chars().next().unwrap(),
                        host.to_owned(),
                    ));
                } else if let Ok(ipv4) = host.parse::<Ipv4Addr>() {
                    return Err(DataParseError::HostWasIp(ipv4));
                } else {
                    hosts.push(host);
                }
            }
            Ok(DataLine {
                ip: ip,
                hosts: hosts,
            })
        } else {
            Err(DataParseError::NoInternalSpace)
        }
    }
}

impl fmt::Display for DataLine {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} ", self.ip())?;
        for host in self.hosts() {
            write!(f, " {}", host)?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
    use super::*;

    #[test]
    fn only_ip() {
        let line: Result<DataLine, _> = "   ::1   ".parse();
        assert_eq!(line, Err(DataParseError::NoInternalSpace))
    }

    #[test]
    fn wrong_order() {
        let line: Result<DataLine, _> = "localhost ::1".parse();
        if let Err(DataParseError::BadIp(_, ip)) = line {
            assert_eq!(ip, "localhost");
        } else {
            panic!("not a bad IP: {:?}", line);
        }
    }

    #[test]
    fn two_ipv4() {
        let line: Result<DataLine, _> = "127.0.0.1 0.0.0.0".parse();
        if let Err(DataParseError::HostWasIp(ip)) = line {
            assert_eq!(ip, Ipv4Addr::new(0, 0, 0, 0));
        } else {
            panic!("not host-was-IP: {:?}", line);
        }
    }

    #[test]
    fn two_ipv6() {
        let line: Result<DataLine, _> = "::1 localhost ::1".parse();
        if let Err(DataParseError::BadHost(':', host)) = line {
            assert_eq!(host, "::1");
        } else {
            panic!("not a bad host: {:?}", line);
        }
    }

    #[test]
    fn good() {
        let line: DataLine = "::1 localhost localhost.localdomain lh".parse().unwrap();
        assert_eq!(line.ip(), IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)));
        let hosts: Vec<&str> = line.hosts().collect();
        assert_eq!(hosts, &["localhost", "localhost.localdomain", "lh"]);
    }

    #[test]
    fn ascii_host() {
        let line: DataLine = "::1 the-quick-brown-fox-jumped-over-the-lazy-dog-0123456789.com"
            .parse()
            .unwrap();
        assert_eq!(line.ip(), IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)));
        let hosts: Vec<&str> = line.hosts().collect();
        assert_eq!(
            hosts,
            &[
                "the-quick-brown-fox-jumped-over-the-lazy-dog-0123456789.com",
            ]
        );
    }
}