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