mwtitle/ipv6.rs
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
/*
Copyright (C) 2021 Erutuon
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use std::ops::Range;
use tinyvec::ArrayVec;
#[derive(Debug, Clone)]
pub(crate) enum Segment {
Num(Range<usize>),
Colons(Range<usize>),
}
impl Segment {
fn is_colons(&self) -> bool {
matches!(self, Segment::Colons(_))
}
fn range(&self) -> &Range<usize> {
match self {
Segment::Num(range) | Segment::Colons(range) => range,
}
}
fn range_mut(&mut self) -> &mut Range<usize> {
match self {
Segment::Num(range) | Segment::Colons(range) => range,
}
}
}
/// This implementation is solely to allow the use of `ArrayVec`,
/// which requires its item `T` to implement `Default` to avoid
/// having to put unsafe `std::mem::MaybeUninit<T>` in not-yet-filled slots.
/// In the functions that use `Segment`, the default Segment is invalid
/// and it will never be encountered unless we have bugs
/// because `ipv6_split_iter_rev` constructs `Segment`s
/// containing ranges that enclose valid char encodings.
impl Default for Segment {
fn default() -> Self {
Self::Colons(0..0)
}
}
fn ipv6_split_iter_rev(ip: &str) -> impl Iterator<Item = Segment> + '_ {
let mut colons = ip
.bytes()
.enumerate()
.rev()
.map(|(pos, b)| (pos, b == b':'));
let mut last = None::<Segment>;
std::iter::from_fn(move || {
for (pos, is_colon) in colons.by_ref() {
match &mut last {
Some(segment) if is_colon == segment.is_colons() => {
segment.range_mut().start -= 1
}
_ => {
let range = pos..pos + 1;
if let Some(segment) = last.replace(if is_colon {
Segment::Colons(range)
} else {
Segment::Num(range)
}) {
return Some(segment);
}
}
}
}
last.take()
})
}
// TODO: Get rid of this; TitleCodec doesn't care
// why something isn't an IPv6 address.
#[allow(dead_code)]
#[derive(Debug)]
pub(crate) enum Error {
TooManyConsecutiveDigits(Range<usize>),
TooManyConsecutiveColons(Range<usize>),
MoreThanOneDoubleColon,
TooManySegments,
TooFewSegments(usize),
InvalidDigit(Range<usize>),
TrailingColon,
LeadingColon,
}
type SegmentVec = ArrayVec<[Segment; 9]>;
pub(crate) fn parse_ipv6_rev(ip: &str) -> Result<SegmentVec, Error> {
let mut found_double_colon = false;
let mut number_segment_count = 0;
use Error::*;
use Segment::*;
let segments = ipv6_split_iter_rev(ip)
// Skip single colons that are not at the beginning or end.
// Single colons must be between two valid hex u16 numbers.
// Because the hex u16 condition is checked elsewhere,
// we can only need to look at single colons that are
// at the very beginning or very end of the input;
// we can skip any in the middle.
.filter(|segment| {
!matches!(segment, Colons(range) if range.len() == 1 && !(range.start == 0 || range.end == ip.len()))
}).map(|segment| {
match segment {
Num(ref range) => {
if range.len() > 4 {
return Err(TooManyConsecutiveDigits(range.clone()));
} else if !ip[range.clone()]
.bytes()
.all(|b| b.is_ascii_hexdigit())
{
return Err(InvalidDigit(range.clone()));
}
number_segment_count += 1;
}
Colons(ref range) => match range.len() {
1 => {
// Single colons in the middle have already been filtered out.
if range.start == 0 {
return Err(LeadingColon);
} else if range.end == ip.len() {
return Err(TrailingColon);
}
}
2 => {
if found_double_colon {
return Err(MoreThanOneDoubleColon);
} else {
found_double_colon = true;
number_segment_count += 1;
}
}
_ => return Err(TooManyConsecutiveColons(range.clone())),
},
}
Ok(segment)
})
// 8 is the maximum number of segments in a valid IP address,
// when single colons have been filtered out.
// Collect 1 extra so `map` will see leading colons
// and emit `LeadingColon`.
// (Leading and not trailing colon
// because we are iterating from the end to the start.)
// Otherwise the code below would emit `TooManySegments`.
.take(9);
// SAFETY: `collect` won't try to insert more items than the `SegmentVec` can hold
// because take(9) has limited the iterator to 9 items.
let segments = segments.collect::<Result<SegmentVec, _>>()?;
// The address must have exactly 8 Num(_)s or a double colon.
if number_segment_count < 8 && !found_double_colon {
Err(TooFewSegments(number_segment_count))
// Check that we don't have more than 8 numerical segments or double colons
// and that we consumed all the input.
} else if segments.len() > 8
|| segments
.last()
.map(|segment| segment.range().start != 0)
.unwrap_or(false)
{
Err(TooManySegments)
} else {
Ok(segments)
}
}
#[test]
fn parser_rejects_invalid_ipv6_addresses() {
macro_rules! rep {
($thing:expr; $count:expr) => {
vec![$thing; $count].join(":")
};
}
for input in [
// too many colons
":::",
":::1",
"1:::",
"1:::1",
// leading and trailing single colons
&(rep!["01"; 8] + ":"),
&(":".to_string() + &rep!["01"; 8]),
// too few digits
&rep!["01"; 7],
// too many digits or double colons
&rep!["01"; 9],
&("::".to_string() + &rep!["01"; 8]),
&(rep!["1"; 8] + "::"),
// 8 total numbers and double colons, but two or more double colons
&("::".to_string() + &rep!["01"; 6] + "::"),
&("::".to_string() + &rep!["01"; 2] + "::" + &rep!["1"; 3] + "::"),
&(rep!["01"; 2] + "::" + &rep!["1"; 2] + "::" + &rep!["1"; 2]),
// too many digits per number
"00001:1:1:1:1:1:1:1",
"1:1:1:1:1:1:1:00000",
// extraneous characters
&(" ".to_string() + &rep!["01"; 7]),
&(" :".to_string() + &rep!["01"; 8]),
&(rep!["01"; 7] + " "),
&rep!["g"; 8],
] {
let parsed = parse_ipv6_rev(input).map(|vec| {
vec.into_iter()
.map(|segment| input.get(segment.range().clone()))
.collect::<Vec<_>>()
});
assert!(
parsed.is_err(),
"{input:?}\nshould not be successfully parsed, but it yielded the following numerical segments:\n{parsed:?}"
);
}
}