1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: AGPL-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 address {0:?}")] UnexpectedAddr(IpAddr),
17 pub fn check<AC, EH, const TO_MIME: bool>
18 (mtu: u32, data: &[u8], mut addr_chk: AC, mut error_handler: EH)
20 where AC: FnMut(&[u8]) -> Result<(), IpAddr>,
21 EH: FnMut(PacketError),
23 // eprintln!("before: {:?}", DumpHex(data));
27 for packet in data.split(|&c| c == SLIP_END) {
29 if packet.len() == 0 {
30 throw!(PacketError::Empty)
32 if packet.len() > mtu.sat() {
33 throw!(PacketError::MTU { len: packet.len(), mtu });
36 let mut packet: Box<[u8]> = packet.to_owned().into();
37 let mut walk: &mut [u8] = &mut packet;
38 let mut header = [0u8; HEADER_FOR_ADDR];
39 let mut wheader = &mut header[..];
41 while let Some((i, was_mime)) = walk.iter().enumerate().find_map(
43 SLIP_MIME_ESC => Some((i,true)),
44 SLIP_ESC => Some((i,false)),
48 let _ = wheader.write(&walk[0..i]);
49 walk[i] = if was_mime { SLIP_ESC } else { SLIP_MIME_ESC };
50 if was_mime != TO_MIME {
51 let c = match walk.get(i+1) {
52 Some(&SLIP_ESC_END) => SLIP_ESC,
53 Some(&SLIP_ESC_ESC) => SLIP_END,
54 _ => throw!(PacketError::SLIP),
56 let _ = wheader.write(&[c]);
57 walk = &mut walk[i+2 ..];
59 let _ = wheader.write(&[SLIP_MIME_ESC]);
60 walk = &mut walk[i+1 ..];
63 let _ = wheader.write(walk);
65 addr_chk(&header).map_err(PacketError::UnexpectedAddr)?;
69 Err(e) => error_handler(e),
70 Ok(packet) => out.push(packet),
74 // eprintln!(" after: {:?}", DumpHex(data));
77 pub type Frame = Vec<u8>;
78 pub type FramesData = Vec<Vec<u8>>;
79 //pub type Frame = Box<[u8]>;
80 //pub type FramesData = Vec<Frame>;
81 // `From<Box<[u8]>>` is not implemented for `Bytes`
91 impl Debug for Frames {
93 fn fmt(&self, f: &mut fmt::Formatter) {
94 write!(f, "Frames{{n={},len={}}}", &self.frames.len(), &self.total_len)?;
100 pub fn add(&mut self, max: u32, frame: Frame) {
101 if frame.len() == 0 { return }
102 let new_total = self.total_len + frame.len() + 1;
103 if new_total > max.sat() { self.tried_full = true; throw!(frame); }
104 self.total_len = new_total;
105 self.frames.push(frame);
108 #[inline] pub fn tried_full(&self) -> bool { self.tried_full }
109 #[inline] pub fn is_empty(&self) -> bool { self.frames.is_empty() }
112 impl From<Frames> for FramesData {
113 fn from(frames: Frames) -> FramesData { frames.frames }
116 const HEADER_FOR_ADDR: usize = 40;
118 pub fn ip_packet_addr<const DST: bool>(packet: &[u8]) -> Option<IpAddr> {
119 Some(match packet.get(0)? & 0xf0 {
120 4 if packet.len() >= 20 => {
121 let slice = &packet[if DST { 16 } else { 12 }..][0..4];
122 Ipv4Addr::from(*<&[u8;4]>::try_from(slice).unwrap()).into()
125 6 if packet.len() >= 40 => {
126 let slice = &packet[if DST { 24 } else { 8 }..][0..16];
127 Ipv6Addr::from(*<&[u8;16]>::try_from(slice).unwrap()).into()
134 #[derive(Copy,Clone,Eq,PartialEq,Ord,PartialOrd,Hash)]
135 pub struct DumpHex<'b>(pub &'b [u8]);
136 impl Debug for DumpHex<'_> {
137 #[throws(fmt::Error)]
138 fn fmt(&self, f: &mut fmt::Formatter) {
139 for v in self.0 { write!(f, "{:02x}", v)?; }
144 fn mime_slip_to_mime() {
145 use PacketError as PE;
148 fn chk(i: &[u8], exp_p: &[&[u8]], exp_e: &[PacketError]) {
149 let mut got_e = vec![];
150 let got_p = check::<_,_,true>(MTU, i, |_|Ok(()), |e| got_e.push(e));
151 assert_eq!( got_p.iter().map(|b| DumpHex(b)).collect_vec(),
152 exp_p.iter().map(|b| DumpHex(b)).collect_vec() );
157 chk( &[ SLIP_END, SLIP_ESC, SLIP_ESC_END, b'-', b'X' ],
158 &[ &[ b'-', SLIP_ESC_END, SLIP_ESC, b'X' ] ],
161 chk( &[ SLIP_END, SLIP_ESC, b'y' ], &[],
162 &[ PE::Empty, PE::SLIP ]);
164 chk( &[ SLIP_END, b'-', b'y' ],
165 &[ &[ SLIP_ESC, b'y' ] ],
170 &[ PE::MTU { len: 20, mtu: MTU } ]);