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