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