chiark / gitweb /
prep for addr chk
[hippotat.git] / src / slip.rs
1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: AGPL-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 address {0:?}")]     UnexpectedAddr(IpAddr),
15 }
16
17 pub fn check<AC, EH, const TO_MIME: bool>
18   (mtu: u32, data: &[u8], mut addr_chk: AC, mut error_handler: EH)
19    -> Vec<Box<[u8]>>
20 where AC: FnMut(&[u8]) -> Result<(), IpAddr>,
21       EH: FnMut(PacketError),
22 {
23 //  eprintln!("before: {:?}", DumpHex(data));
24
25   let mut out = vec![];
26
27   for packet in data.split(|&c| c == SLIP_END) {
28     match (||{
29       if packet.len() == 0 {
30         throw!(PacketError::Empty)
31       }
32       if packet.len() > mtu.sat() {
33         throw!(PacketError::MTU { len: packet.len(), mtu });
34       }
35
36       let mut packet: Box<[u8]> = packet.to_owned().into();
37       let mut walk: &mut [u8] = &mut packet;
38       let mut header = [0u8; HEADER_FOR_ADDR];
39       let mut wheader = &mut header[..];
40
41       while let Some((i, was_mime)) = walk.iter().enumerate().find_map(
42         |(i,&c)| match c {
43           SLIP_MIME_ESC => Some((i,true)),
44           SLIP_ESC      => Some((i,false)),
45           _ => None,
46         }
47       ) {
48         let _ = wheader.write(&walk[0..i]);
49         walk[i] = if was_mime { SLIP_ESC } else { SLIP_MIME_ESC };
50         if was_mime != TO_MIME {
51           let c = match walk.get(i+1) {
52             Some(&SLIP_ESC_END) => SLIP_ESC,
53             Some(&SLIP_ESC_ESC) => SLIP_END,
54             _ => throw!(PacketError::SLIP),
55           };
56           let _ = wheader.write(&[c]);
57           walk = &mut walk[i+2 ..];
58         } else {
59           let _ = wheader.write(&[SLIP_MIME_ESC]);
60           walk = &mut walk[i+1 ..];
61         }
62       }
63       let _ = wheader.write(walk);
64
65       addr_chk(&header).map_err(PacketError::UnexpectedAddr)?;
66
67       Ok(packet)
68     })() {
69       Err(e) => error_handler(e),
70       Ok(packet) => out.push(packet),
71     }
72   }
73   out
74 //  eprintln!(" after: {:?}", DumpHex(data));
75 }
76
77 pub type Frame = Vec<u8>;
78 pub type FramesData = Vec<Vec<u8>>;
79 //pub type Frame = Box<[u8]>;
80 //pub type FramesData = Vec<Frame>;
81 //  `From<Box<[u8]>>` is not implemented for `Bytes`
82
83
84 #[derive(Default)]
85 pub struct Frames {
86   frames: FramesData,
87   total_len: usize,
88   tried_full: bool,
89 }
90
91 impl Debug for Frames {
92   #[throws(fmt::Error)]
93   fn fmt(&self, f: &mut fmt::Formatter) {
94     write!(f, "Frames{{n={},len={}}}", &self.frames.len(), &self.total_len)?;
95   }
96 }
97
98 impl Frames {
99   #[throws(Frame)]
100   pub fn add(&mut self, max: u32, frame: Frame) {
101     if frame.len() == 0 { return }
102     let new_total = self.total_len + frame.len() + 1;
103     if new_total > max.sat() { self.tried_full = true; throw!(frame); }
104     self.total_len = new_total;
105     self.frames.push(frame);
106   }
107
108   #[inline] pub fn tried_full(&self) -> bool { self.tried_full }
109   #[inline] pub fn is_empty(&self) -> bool { self.frames.is_empty() }
110 }
111
112 impl From<Frames> for FramesData {
113   fn from(frames: Frames) -> FramesData { frames.frames }
114 }
115
116 const HEADER_FOR_ADDR: usize = 40;
117
118 pub fn ip_packet_addr<const DST: bool>(packet: &[u8]) -> Option<IpAddr> {
119   Some(match packet.get(0)? & 0xf0 {
120     4 if packet.len() >= 20 => {
121       let slice = &packet[if DST { 16 } else { 12 }..][0..4];
122       Ipv4Addr::from(*<&[u8;4]>::try_from(slice).unwrap()).into()
123     },
124
125     6 if packet.len() >= 40 => {
126       let slice = &packet[if DST { 24 } else { 8 }..][0..16];
127       Ipv6Addr::from(*<&[u8;16]>::try_from(slice).unwrap()).into()
128     },
129
130     _ => None?,
131   })
132 }
133
134 #[derive(Copy,Clone,Eq,PartialEq,Ord,PartialOrd,Hash)]
135 pub struct DumpHex<'b>(pub &'b [u8]);
136 impl Debug for DumpHex<'_> {
137   #[throws(fmt::Error)]
138   fn fmt(&self, f: &mut fmt::Formatter) {
139     for v in self.0 { write!(f, "{:02x}", v)?; }
140   }
141 }
142
143 #[test]
144 fn mime_slip_to_mime() {
145   use PacketError as PE;
146   const MTU: u32 = 10;
147
148   fn chk(i: &[u8], exp_p: &[&[u8]], exp_e: &[PacketError]) {
149     let mut got_e = vec![];
150     let got_p = check::<_,_,true>(MTU, i, |_|Ok(()), |e| got_e.push(e));
151     assert_eq!( got_p.iter().map(|b| DumpHex(b)).collect_vec(),
152                 exp_p.iter().map(|b| DumpHex(b)).collect_vec() );
153     assert_eq!( got_e,
154                 exp_e );
155   }
156
157   chk( &[ SLIP_END, SLIP_ESC, SLIP_ESC_END, b'-',     b'X' ],
158     &[           &[ b'-',     SLIP_ESC_END, SLIP_ESC, b'X' ] ],
159     &[ PE::Empty ]);
160
161   chk( &[ SLIP_END, SLIP_ESC, b'y' ], &[],
162     &[ PE::Empty,   PE::SLIP ]);
163
164   chk( &[ SLIP_END, b'-',     b'y' ],
165     &[           &[ SLIP_ESC, b'y' ] ],
166     &[ PE::Empty ]);
167
168   chk( &[b'x'; 20],
169     &[             ],
170     &[ PE::MTU { len: 20, mtu: MTU } ]);
171 }