1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 // There is NO WARRANTY.
7 pub static SLIP_END_SLICE: &[u8] = &[SLIP_END];
9 #[derive(Error,Debug,Copy,Clone,Eq,PartialEq)]
10 pub enum PacketError {
11 #[error("empty packet")] Empty,
12 #[error("MTU exceeded ({len} > {mtu})")] MTU { len: usize, mtu: u32 },
13 #[error("Invalid SLIP escape sequence")] SLIP,
14 #[error("unexpected src addr {0:?}")] Src(IpAddr),
15 #[error("unexpected dst addr {0:?}")] Dst(IpAddr),
16 #[error("bad, IPv{vsn}, len={len}")] Bad { len: usize, vsn: u8 },
19 pub trait SlipMime { const CONV_TO: Option<bool>; }
20 #[derive(Copy,Clone,Debug)] pub struct Slip2Mime;
21 #[derive(Copy,Clone,Debug)] pub struct Mime2Slip;
22 #[derive(Copy,Clone,Debug)] pub struct SlipNoConv;
23 impl SlipMime for Slip2Mime { const CONV_TO: Option<bool> = Some(true); }
24 impl SlipMime for Mime2Slip { const CONV_TO: Option<bool> = Some(false); }
25 impl SlipMime for SlipNoConv { const CONV_TO: Option<bool> = None; }
27 pub fn checkn<AC, EH, OUT, M: SlipMime+Copy>(
34 ) where OUT: Extend<Box<[u8]>>,
35 AC: Fn(&[u8]) -> Result<(), PacketError> + Copy,
36 EH: FnMut(PacketError),
38 // eprintln!("before: {:?}", DumpHex(data));
39 for packet in data.split(|&c| c == SLIP_END) {
40 match check1(mime, mtu, packet, addr_chk) {
41 Err(e) => error_handler(e),
42 Ok(packet) => out.extend(iter::once(packet)),
45 // eprintln!(" after: {:?}", DumpHex(data));
48 #[throws(PacketError)]
49 pub fn check1<AC, M: SlipMime>(
55 where AC: Fn(&[u8]) -> Result<(), PacketError>,
57 if packet.len() == 0 {
58 throw!(PacketError::Empty)
60 if packet.len() > mtu.sat() {
61 throw!(PacketError::MTU { len: packet.len(), mtu });
64 let mut packet: Box<[u8]> = packet.to_owned().into();
65 let mut walk: &mut [u8] = &mut packet;
66 let mut header = [0u8; HEADER_FOR_ADDR];
67 let mut wheader = &mut header[..];
69 while let Some((i, was_mime)) = walk.iter().enumerate().find_map(
71 SLIP_ESC => Some((i,false)),
72 SLIP_MIME_ESC if M::CONV_TO.is_some() => Some((i,true)),
76 let _ = wheader.write(&walk[0..i]);
77 if M::CONV_TO.is_some() {
78 walk[i] = if was_mime { SLIP_ESC } else { SLIP_MIME_ESC };
80 if Some(was_mime) != M::CONV_TO {
81 let c = match walk.get(i+1) {
82 Some(&SLIP_ESC_ESC) => SLIP_ESC,
83 Some(&SLIP_ESC_END) => SLIP_END,
84 _ => throw!(PacketError::SLIP),
86 let _ = wheader.write(&[c]);
87 walk = &mut walk[i+2 ..];
89 let _ = wheader.write(&[SLIP_MIME_ESC]);
90 walk = &mut walk[i+1 ..];
93 let _ = wheader.write(walk);
100 pub type Frame = Vec<u8>;
101 pub type FramesData = Vec<Vec<u8>>;
102 //pub type Frame = Box<[u8]>;
103 //pub type FramesData = Vec<Frame>;
104 // `From<Box<[u8]>>` is not implemented for `Bytes`
114 impl Debug for Frames {
115 #[throws(fmt::Error)]
116 fn fmt(&self, f: &mut fmt::Formatter) {
117 write!(f, "Frames{{n={},len={}}}", &self.frames.len(), &self.total_len)?;
123 pub fn add(&mut self, max: u32, frame: Frame) {
124 if frame.len() == 0 { return }
125 let new_total = self.total_len + frame.len() + 1;
126 if new_total > max.sat() { self.tried_full = true; throw!(frame); }
127 self.total_len = new_total;
128 self.frames.push(frame);
131 #[inline] pub fn tried_full(&self) -> bool { self.tried_full }
132 #[inline] pub fn is_empty(&self) -> bool { self.frames.is_empty() }
135 impl From<Frames> for FramesData {
136 fn from(frames: Frames) -> FramesData { frames.frames }
139 const HEADER_FOR_ADDR: usize = 40;
141 #[throws(PacketError)]
142 pub fn ip_packet_addr<const DST: bool>(packet: &[u8]) -> IpAddr {
143 let vsn = (packet.get(0).ok_or_else(|| PE::Empty)? & 0xf0) >> 4;
145 4 if packet.len() >= 20 => {
146 let slice = &packet[if DST { 16 } else { 12 }..][0..4];
147 Ipv4Addr::from(*<&[u8;4]>::try_from(slice).unwrap()).into()
150 6 if packet.len() >= 40 => {
151 let slice = &packet[if DST { 24 } else { 8 }..][0..16];
152 Ipv6Addr::from(*<&[u8;16]>::try_from(slice).unwrap()).into()
155 _ => throw!(PE::Bad{ vsn, len: packet.len() }),
159 #[derive(Copy,Clone,Eq,PartialEq,Ord,PartialOrd,Hash)]
160 pub struct DumpHex<'b>(pub &'b [u8]);
161 impl Debug for DumpHex<'_> {
162 #[throws(fmt::Error)]
163 fn fmt(&self, f: &mut fmt::Formatter) {
164 for v in self.0 { write!(f, "{:02x}", v)?; }
169 fn mime_slip_to_mime() {
170 use PacketError as PE;
173 fn chk<M: SlipMime>(i: &[u8], exp_p: &[&[u8]], exp_e: &[PacketError]) {
174 dbg!(M::CONV_TO, DumpHex(i));
175 let mut got_e = vec![];
176 let mut got_p = vec![];
177 check::<_,_,_,M>(MTU, i, &mut got_p, |_|Ok(()), |e| got_e.push(e));
178 assert_eq!( got_p.iter().map(|b| DumpHex(b)).collect_vec(),
179 exp_p.iter().map(|b| DumpHex(b)).collect_vec() );
185 ( &[ SLIP_END, SLIP_ESC, SLIP_ESC_END, b'-', b'X' ],
186 &[ &[ b'-', SLIP_ESC_END, SLIP_ESC, b'X' ] ],
190 ( &[ SLIP_END, SLIP_ESC, b'y' ], &[],
191 &[ PE::Empty, PE::SLIP ]);
194 ( &[ SLIP_END, b'-', b'y' ],
195 &[ &[ SLIP_ESC, b'y' ] ],
201 &[ PE::MTU { len: 20, mtu: MTU } ]);
204 ( &[ SLIP_END, SLIP_ESC, SLIP_ESC_END, b'-', b'X' ],
205 &[ &[ SLIP_ESC, SLIP_ESC_END, b'-', b'X' ] ],