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