chiark / gitweb /
sort out error handling for server rx slip frames
[hippotat.git] / src / slip.rs
1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 // There is NO WARRANTY.
4
5 use crate::prelude::*;
6
7 pub static SLIP_END_SLICE: &[u8] = &[SLIP_END];
8
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 },
17 }
18
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; }
26
27 #[derive(Debug,Error)]
28 pub enum SlipFramesError<E> where E: std::error::Error + 'static {
29   #[error("only bad IP datagrams")] ErrorOnlyBad,
30   #[error("{0}")] Other(#[from] E),
31 }
32   
33 #[throws(SlipFramesError<EHE>)]
34 pub fn checkn<AC, EH, EHE, OUT, ACR, M: SlipMime+Copy>(
35   mime: M,
36   mtu: u32,
37   data: &[u8],
38   addr_chk: AC,
39   mut out: OUT,
40   mut error_handler: EH
41 ) where AC: Fn(&[u8]) -> Result<ACR, PacketError> + Copy,
42         OUT: FnMut((Box<[u8]>, ACR)) -> Result<(), PacketError>,
43         EH: FnMut(PacketError) -> Result<(), SlipFramesError<EHE>>,
44         EHE: std::error::Error + 'static,
45 {
46   //  eprintln!("before: {:?}", DumpHex(data));
47   if data.is_empty() { return }
48   let mut ok = false;
49   let mut err = false;
50   for packet in data.split(|&c| c == SLIP_END) {
51     match (||{
52       let checked = check1(mime, mtu, packet, addr_chk);
53       if matches!(checked, Err(PacketError::Empty)) { return Ok::<_,PE>(()) }
54       out(checked?)?;
55       ok = true;
56       Ok::<_,PE>(())
57     })() {
58       Ok(()) => { },
59       Err(e) => { err=true; error_handler(e)?; },
60     }
61   }
62 //  eprintln!(" after: {:?}", DumpHex(data));
63   if err && !ok { throw!(SlipFramesError::ErrorOnlyBad) }
64 }
65
66 #[throws(PacketError)]
67 pub fn check1<AC, M: SlipMime, ACR>(
68   _mime: M,
69   mtu: u32,
70   packet: &[u8],
71   addr_chk: AC,
72 ) -> (Box<[u8]>, ACR)
73 where AC: Fn(&[u8]) -> Result<ACR, PacketError>,
74 {
75   if packet.len() == 0 {
76     throw!(PacketError::Empty)
77   }
78
79   let mut packet: Box<[u8]> = packet.to_owned().into();
80   let mut walk: &mut [u8] = &mut packet;
81   let mut header = [0u8; HEADER_FOR_ADDR];
82   let mut wheader = &mut header[..];
83   let mut escapes = 0;
84
85   while let Some((i, was_mime)) = walk.iter().enumerate().find_map(
86     |(i,&c)| match c {
87       SLIP_ESC                               => Some((i,false)),
88       SLIP_MIME_ESC if M::CONV_TO.is_some()  => Some((i,true)),
89       _ => None,
90     }
91   ) {
92     let _ = wheader.write(&walk[0..i]);
93     if M::CONV_TO.is_some() {
94       walk[i] = if was_mime { SLIP_ESC } else { SLIP_MIME_ESC };
95     }
96     if Some(was_mime) != M::CONV_TO {
97       let c = match walk.get(i+1) {
98         Some(&SLIP_ESC_ESC) => SLIP_ESC,
99         Some(&SLIP_ESC_END) => SLIP_END,
100         _ => throw!(PacketError::SLIP),
101       };
102       let _ = wheader.write(&[c]);
103       walk = &mut walk[i+2 ..];
104       escapes += 1;
105     } else {
106       let _ = wheader.write(&[SLIP_MIME_ESC]);
107       walk = &mut walk[i+1 ..];
108     }
109   }
110   let _ = wheader.write(walk);
111   let wheader_len = wheader.len();
112   let header = &header[0.. header.len() - wheader_len];
113
114   let decoded_len = packet.len() - escapes;
115   if decoded_len > mtu.sat() {
116     throw!(PacketError::MTU { len: decoded_len, mtu });
117   }
118
119   let acr = addr_chk(&header)?;
120
121   (packet, acr)
122 }
123
124 pub type Frame = Vec<u8>;
125 pub type FramesData = Vec<Vec<u8>>;
126 // todo: https://github.com/tokio-rs/bytes/pull/504
127 //   pub type Frame = Box<[u8]>;
128 //   pub type FramesData = Vec<Frame>;
129 //       `From<Box<[u8]>>` is not implemented for `Bytes`
130 // when this is fixed, there are two `into`s in client.rs which 
131 // become redundant (search for todo:504)
132
133
134 #[derive(Default)]
135 pub struct Frames {
136   frames: FramesData,
137   total_len: usize,
138   tried_full: bool,
139 }
140
141 impl Debug for Frames {
142   #[throws(fmt::Error)]
143   fn fmt(&self, f: &mut fmt::Formatter) {
144     write!(f, "Frames{{n={},len={}}}", &self.frames.len(), &self.total_len)?;
145   }
146 }
147
148 impl Frames {
149   #[throws(Frame)]
150   pub fn add(&mut self, max: u32, frame: Frame) {
151     if frame.len() == 0 { return }
152     let new_total = self.total_len + frame.len() + 1;
153     if new_total > max.sat() { self.tried_full = true; throw!(frame); }
154     self.total_len = new_total;
155     self.frames.push(frame);
156   }
157
158   #[inline] pub fn tried_full(&self) -> bool { self.tried_full }
159   #[inline] pub fn is_empty(&self) -> bool { self.frames.is_empty() }
160 }
161
162 impl From<Frames> for FramesData {
163   fn from(frames: Frames) -> FramesData { frames.frames }
164 }
165
166 const HEADER_FOR_ADDR: usize = 40;
167
168 #[throws(PacketError)]
169 pub fn ip_packet_addr<const DST: bool>(packet: &[u8]) -> IpAddr {
170   let vsn = (packet.get(0).ok_or_else(|| PE::Empty)? & 0xf0) >> 4;
171   match vsn {
172     4 if packet.len() >= 20 => {
173       let slice = &packet[if DST { 16 } else { 12 }..][0..4];
174       Ipv4Addr::from(*<&[u8;4]>::try_from(slice).unwrap()).into()
175     },
176
177     6 if packet.len() >= 40 => {
178       let slice = &packet[if DST { 24 } else { 8 }..][0..16];
179       Ipv6Addr::from(*<&[u8;16]>::try_from(slice).unwrap()).into()
180     },
181
182     _ => throw!(PE::Truncated{ vsn, len: packet.len() }),
183   }
184 }
185
186 #[derive(Copy,Clone,Eq,PartialEq,Ord,PartialOrd,Hash)]
187 pub struct DumpHex<'b>(pub &'b [u8]);
188 impl Debug for DumpHex<'_> {
189   #[throws(fmt::Error)]
190   fn fmt(&self, f: &mut fmt::Formatter) {
191     for v in self.0 { write!(f, "{:02x}", v)?; }
192     match str::from_utf8(self.0) {
193       Ok(s) => write!(f, "={:?}", s)?,
194       Err(x) => write!(f, "={:?}..",
195                        str::from_utf8(&self.0[0..x.valid_up_to()]).unwrap()
196       )?,
197     }
198   }
199 }
200
201 #[test]
202 fn mime_slip_to_mime() {
203   use PacketError as PE;
204   const MTU: u32 = 10;
205
206   fn chk<M: SlipMime>(i: &[u8], exp_p: &[&[u8]], exp_e: &[PacketError]) {
207     dbg!(M::CONV_TO, DumpHex(i));
208     let mut got_e = vec![];
209     let mut got_p = vec![];
210     check::<_,_,_,M>(MTU, i, &mut got_p, |_|Ok(()), |e| got_e.push(e));
211     assert_eq!( got_p.iter().map(|b| DumpHex(b)).collect_vec(),
212                 exp_p.iter().map(|b| DumpHex(b)).collect_vec() );
213     assert_eq!( got_e,
214                 exp_e );
215   }
216
217   chk::<Slip2Mime>
218      ( &[ SLIP_END, SLIP_ESC, SLIP_ESC_END, b'-',     b'X' ],
219     &[           &[ b'-',     SLIP_ESC_END, SLIP_ESC, b'X' ] ],
220     &[ PE::Empty ]);
221
222   chk::<Slip2Mime>
223      ( &[ SLIP_END, SLIP_ESC, b'y' ], &[],
224     &[ PE::Empty,   PE::SLIP ]);
225
226   chk::<Slip2Mime>
227      ( &[ SLIP_END, b'-',     b'y' ],
228     &[           &[ SLIP_ESC, b'y' ] ],
229     &[ PE::Empty ]);
230
231   chk::<Slip2Mime>
232      ( &[b'x'; 20],
233     &[             ],
234     &[ PE::MTU { len: 20, mtu: MTU } ]);
235
236   chk::<SlipNoConv>
237      ( &[ SLIP_END, SLIP_ESC, SLIP_ESC_END, b'-',     b'X' ],
238     &[           &[ SLIP_ESC, SLIP_ESC_END, b'-',     b'X' ] ],
239     &[ PE::Empty, ]);
240 }
241
242