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