1 // Copyright 2021-2022 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("truncated, IPv{vsn}, len={len}")] Truncated { len: usize, vsn: u8 },
19 pub trait SlipMime: Copy { 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 #[derive(Debug,Error,Eq,PartialEq)]
28 pub enum SlipFramesError<E> where E: std::error::Error + 'static {
29 #[error("only bad IP datagrams")] ErrorOnlyBad,
30 #[error("{0}")] Other(#[from] E),
33 #[throws(SlipFramesError<EHE>)]
34 pub async fn processn<AC, EH, EHE, OUT, FOUT, ACR, M: SlipMime+Copy>(
41 ) where AC: Fn(&[u8]) -> Result<ACR, PacketError> + Copy + Send,
42 OUT: FnMut((Box<[u8]>, ACR)) -> FOUT + Send,
43 FOUT: Future<Output=Result<(), PacketError>> + Send,
44 EH: FnMut(PacketError) -> Result<(), SlipFramesError<EHE>> + Send,
45 EHE: std::error::Error + Send + 'static,
47 // eprintln!("before: {:?}", DumpHex(data));
48 if data.is_empty() { return }
51 for packet in data.split(|&c| c == SLIP_END) {
53 let checked = process1(mime, mtu, packet, addr_chk);
54 if matches!(checked, Err(PacketError::Empty)) { return Ok::<_,PE>(()) }
60 Err(e) => { err=true; error_handler(e)?; },
63 // eprintln!(" after: {:?}", DumpHex(data));
64 if err && !ok { throw!(SlipFramesError::ErrorOnlyBad) }
67 #[throws(PacketError)]
68 pub fn process1<AC, M: SlipMime, ACR>(
74 where AC: Fn(&[u8]) -> Result<ACR, PacketError>,
76 if packet.len() == 0 {
77 throw!(PacketError::Empty)
80 let mut packet: Box<[u8]> = packet.to_owned().into();
81 let mut walk: &mut [u8] = &mut packet;
82 let mut header = [0u8; HEADER_FOR_ADDR];
83 let mut wheader = &mut header[..];
86 while let Some((i, was_mime)) = walk.iter().enumerate().find_map(
88 SLIP_ESC => Some((i,false)),
89 SLIP_MIME_ESC if M::CONV_TO.is_some() => Some((i,true)),
93 let _ = wheader.write(&walk[0..i]);
94 if M::CONV_TO.is_some() {
95 walk[i] = if was_mime { SLIP_ESC } else { SLIP_MIME_ESC };
97 if Some(was_mime) != M::CONV_TO {
98 let c = match walk.get(i+1) {
99 Some(&SLIP_ESC_ESC) => SLIP_ESC,
100 Some(&SLIP_ESC_END) => SLIP_END,
101 _ => throw!(PacketError::SLIP),
103 let _ = wheader.write(&[c]);
104 walk = &mut walk[i+2 ..];
107 let _ = wheader.write(&[SLIP_MIME_ESC]);
108 walk = &mut walk[i+1 ..];
111 let _ = wheader.write(walk);
112 let wheader_len = wheader.len();
113 let header = &header[0.. header.len() - wheader_len];
115 let decoded_len = packet.len() - escapes;
116 if decoded_len > mtu.sat() {
117 throw!(PacketError::MTU { len: decoded_len, mtu });
120 let acr = addr_chk(&header)?;
125 pub type Frame = Vec<u8>;
126 pub type FramesData = Vec<Vec<u8>>;
127 // todo: https://github.com/tokio-rs/bytes/pull/504
128 // pub type Frame = Box<[u8]>;
129 // pub type FramesData = Vec<Frame>;
130 // `From<Box<[u8]>>` is not implemented for `Bytes`
131 // when this is fixed, there are two `into`s in client.rs which
132 // become redundant (search for todo:504)
142 impl Debug for Frames {
143 #[throws(fmt::Error)]
144 fn fmt(&self, f: &mut fmt::Formatter) {
145 write!(f, "Frames{{n={},len={}}}", &self.frames.len(), &self.total_len)?;
151 pub fn add(&mut self, max: u32, frame: Frame) {
152 if frame.len() == 0 { return }
153 let new_total = self.total_len + frame.len() + 1;
154 if new_total > max.sat() { self.tried_full = true; throw!(frame); }
155 self.total_len = new_total;
156 self.frames.push(frame);
159 #[inline] pub fn tried_full(&self) -> bool { self.tried_full }
160 #[inline] pub fn is_empty(&self) -> bool { self.frames.is_empty() }
163 impl From<Frames> for FramesData {
164 fn from(frames: Frames) -> FramesData { frames.frames }
167 const HEADER_FOR_ADDR: usize = 40;
169 #[throws(PacketError)]
170 pub fn ip_packet_addr<const DST: bool>(header: &[u8]) -> IpAddr {
171 let vsn = (header.get(0).ok_or_else(|| PE::Empty)? & 0xf0) >> 4;
173 4 if header.len() >= 20 => {
174 let slice = &header[if DST { 16 } else { 12 }..][0..4];
175 Ipv4Addr::from(*<&[u8;4]>::try_from(slice).unwrap()).into()
178 6 if header.len() >= 40 => {
179 let slice = &header[if DST { 24 } else { 8 }..][0..16];
180 Ipv6Addr::from(*<&[u8;16]>::try_from(slice).unwrap()).into()
183 _ => throw!(PE::Truncated{ vsn, len: header.len() }),
187 #[derive(Copy,Clone,Eq,PartialEq,Ord,PartialOrd,Hash)]
188 pub struct DumpHex<'b>(pub &'b [u8]);
189 impl Debug for DumpHex<'_> {
190 #[throws(fmt::Error)]
191 fn fmt(&self, f: &mut fmt::Formatter) {
192 for v in self.0 { write!(f, "{:02x}", v)?; }
193 match str::from_utf8(self.0) {
194 Ok(s) => write!(f, "={:?}", s)?,
195 Err(x) => write!(f, "={:?}..",
196 str::from_utf8(&self.0[0..x.valid_up_to()]).unwrap()
203 async fn mime_slip_to_mime() {
204 use PacketError as PE;
207 async fn chk<M:SlipMime>(m: M, i: &[u8],
209 exp_e: &[PacketError],
210 exp_r: Result<(),SlipFramesError<Void>>)
212 dbg!(M::CONV_TO, DumpHex(i));
213 let mut got_e = vec![];
214 let mut got_p = vec![];
215 let got_r = processn(
218 |(p,())| { got_p.push(p); async { Ok(()) } },
219 |e| Ok::<_,SlipFramesError<Void>>(got_e.push(e))
221 assert_eq!( got_p.iter().map(|b| DumpHex(b)).collect_vec(),
222 exp_p.iter().map(|b| DumpHex(b)).collect_vec() );
228 use SlipFramesError::ErrorOnlyBad;
231 &[ SLIP_END, SLIP_ESC, SLIP_ESC_END, b'-', b'X' ],
232 &[ &[ b'-', SLIP_ESC_END, SLIP_ESC, b'X' ] ],
237 &[ SLIP_END, SLIP_ESC, b'y' ], &[],
239 Err(ErrorOnlyBad)).await;
242 &[ SLIP_END, b'-', b'y' ],
243 &[ &[ SLIP_ESC, b'y' ] ],
250 &[ PE::MTU { len: 20, mtu: MTU } ],
251 Err(ErrorOnlyBad)).await;
254 &[ SLIP_END, SLIP_ESC, SLIP_ESC_END, b'-', b'X' ],
255 &[ &[ SLIP_ESC, SLIP_ESC_END, b'-', b'X' ] ],