chiark / gitweb /
server: wip recv
[hippotat.git] / src / slip.rs
index 269c8fe401423b6737d22076fa3cc018314cd0c7..955c36f624dddd027e0798fe2e7c04947af1d480 100644 (file)
 // Copyright 2021 Ian Jackson and contributors to Hippotat
-// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-License-Identifier: GPL-3.0-or-later
 // There is NO WARRANTY.
 
 use crate::prelude::*;
 
 pub static SLIP_END_SLICE: &[u8] = &[SLIP_END];
 
-#[throws(AE)]
-pub fn check_checkmtu_mimeify(_data: &mut [u8], _ic: &InstanceConfig) {
-  // xxx
+#[derive(Error,Debug,Copy,Clone,Eq,PartialEq)]
+pub enum PacketError {
+  #[error("empty packet")]                 Empty,
+  #[error("MTU exceeded ({len} > {mtu})")] MTU { len: usize, mtu: u32 },
+  #[error("Invalid SLIP escape sequence")] SLIP,
+  #[error("unexpected src addr {0:?}")]    Src(IpAddr),
+  #[error("unexpected dst addr {0:?}")]    Dst(IpAddr),
+  #[error("truncated, IPv{vsn}, len={len}")] Truncated { len: usize, vsn: u8 },
 }
+
+pub trait SlipMime { const CONV_TO: Option<bool>; }
+#[derive(Copy,Clone,Debug)] pub struct Slip2Mime;
+#[derive(Copy,Clone,Debug)] pub struct Mime2Slip;
+#[derive(Copy,Clone,Debug)] pub struct SlipNoConv;
+impl SlipMime for Slip2Mime { const CONV_TO: Option<bool> = Some(true); }
+impl SlipMime for Mime2Slip { const CONV_TO: Option<bool> = Some(false); }
+impl SlipMime for SlipNoConv { const CONV_TO: Option<bool> = None; }
+
+#[derive(Debug)]
+#[derive(Error)]
+#[error("only bad IP datagrams")]
+pub struct ErrorOnlyBad;
+
+#[throws(ErrorOnlyBad)]
+pub fn checkn<AC, EH, OUT, ACR, M: SlipMime+Copy>(
+  mime: M,
+  mtu: u32,
+  data: &[u8],
+  addr_chk: AC,
+  mut out: OUT,
+  mut error_handler: EH
+) where AC: Fn(&[u8]) -> Result<ACR, PacketError> + Copy,
+        OUT: FnMut((Box<[u8]>, ACR)) -> Result<(), PacketError>,
+        EH: FnMut(PacketError),
+{
+  //  eprintln!("before: {:?}", DumpHex(data));
+  if data.is_empty() { return }
+  let mut ok = false;
+  let mut err = false;
+  for packet in data.split(|&c| c == SLIP_END) {
+    match (||{
+      let checked = check1(mime, mtu, packet, addr_chk);
+      if matches!(checked, Err(PacketError::Empty)) { return Ok::<_,PE>(()) }
+      out(checked?)?;
+      ok = true;
+      Ok::<_,PE>(())
+    })() {
+      Ok(()) => { },
+      Err(e) => { err=true; error_handler(e); },
+    }
+  }
+//  eprintln!(" after: {:?}", DumpHex(data));
+  if err && !ok { throw!(ErrorOnlyBad) }
+}
+
+#[throws(PacketError)]
+pub fn check1<AC, M: SlipMime, ACR>(
+  _mime: M,
+  mtu: u32,
+  packet: &[u8],
+  addr_chk: AC,
+) -> (Box<[u8]>, ACR)
+where AC: Fn(&[u8]) -> Result<ACR, PacketError>,
+{
+  if packet.len() == 0 {
+    throw!(PacketError::Empty)
+  }
+
+  let mut packet: Box<[u8]> = packet.to_owned().into();
+  let mut walk: &mut [u8] = &mut packet;
+  let mut header = [0u8; HEADER_FOR_ADDR];
+  let mut wheader = &mut header[..];
+  let mut escapes = 0;
+
+  while let Some((i, was_mime)) = walk.iter().enumerate().find_map(
+    |(i,&c)| match c {
+      SLIP_ESC                               => Some((i,false)),
+      SLIP_MIME_ESC if M::CONV_TO.is_some()  => Some((i,true)),
+      _ => None,
+    }
+  ) {
+    let _ = wheader.write(&walk[0..i]);
+    if M::CONV_TO.is_some() {
+      walk[i] = if was_mime { SLIP_ESC } else { SLIP_MIME_ESC };
+    }
+    if Some(was_mime) != M::CONV_TO {
+      let c = match walk.get(i+1) {
+        Some(&SLIP_ESC_ESC) => SLIP_ESC,
+        Some(&SLIP_ESC_END) => SLIP_END,
+        _ => throw!(PacketError::SLIP),
+      };
+      let _ = wheader.write(&[c]);
+      walk = &mut walk[i+2 ..];
+      escapes += 1;
+    } else {
+      let _ = wheader.write(&[SLIP_MIME_ESC]);
+      walk = &mut walk[i+1 ..];
+    }
+  }
+  let _ = wheader.write(walk);
+  let wheader_len = wheader.len();
+  let header = &header[0.. header.len() - wheader_len];
+
+  let decoded_len = packet.len() - escapes;
+  if decoded_len > mtu.sat() {
+    throw!(PacketError::MTU { len: decoded_len, mtu });
+  }
+
+  let acr = addr_chk(&header)?;
+
+  (packet, acr)
+}
+
+pub type Frame = Vec<u8>;
+pub type FramesData = Vec<Vec<u8>>;
+// todo: https://github.com/tokio-rs/bytes/pull/504
+//   pub type Frame = Box<[u8]>;
+//   pub type FramesData = Vec<Frame>;
+//       `From<Box<[u8]>>` is not implemented for `Bytes`
+// when this is fixed, there are two `into`s in client.rs which 
+// become redundant (search for todo:504)
+
+
+#[derive(Default)]
+pub struct Frames {
+  frames: FramesData,
+  total_len: usize,
+  tried_full: bool,
+}
+
+impl Debug for Frames {
+  #[throws(fmt::Error)]
+  fn fmt(&self, f: &mut fmt::Formatter) {
+    write!(f, "Frames{{n={},len={}}}", &self.frames.len(), &self.total_len)?;
+  }
+}
+
+impl Frames {
+  #[throws(Frame)]
+  pub fn add(&mut self, max: u32, frame: Frame) {
+    if frame.len() == 0 { return }
+    let new_total = self.total_len + frame.len() + 1;
+    if new_total > max.sat() { self.tried_full = true; throw!(frame); }
+    self.total_len = new_total;
+    self.frames.push(frame);
+  }
+
+  #[inline] pub fn tried_full(&self) -> bool { self.tried_full }
+  #[inline] pub fn is_empty(&self) -> bool { self.frames.is_empty() }
+}
+
+impl From<Frames> for FramesData {
+  fn from(frames: Frames) -> FramesData { frames.frames }
+}
+
+const HEADER_FOR_ADDR: usize = 40;
+
+#[throws(PacketError)]
+pub fn ip_packet_addr<const DST: bool>(packet: &[u8]) -> IpAddr {
+  let vsn = (packet.get(0).ok_or_else(|| PE::Empty)? & 0xf0) >> 4;
+  match vsn {
+    4 if packet.len() >= 20 => {
+      let slice = &packet[if DST { 16 } else { 12 }..][0..4];
+      Ipv4Addr::from(*<&[u8;4]>::try_from(slice).unwrap()).into()
+    },
+
+    6 if packet.len() >= 40 => {
+      let slice = &packet[if DST { 24 } else { 8 }..][0..16];
+      Ipv6Addr::from(*<&[u8;16]>::try_from(slice).unwrap()).into()
+    },
+
+    _ => throw!(PE::Truncated{ vsn, len: packet.len() }),
+  }
+}
+
+#[derive(Copy,Clone,Eq,PartialEq,Ord,PartialOrd,Hash)]
+pub struct DumpHex<'b>(pub &'b [u8]);
+impl Debug for DumpHex<'_> {
+  #[throws(fmt::Error)]
+  fn fmt(&self, f: &mut fmt::Formatter) {
+    for v in self.0 { write!(f, "{:02x}", v)?; }
+    match str::from_utf8(self.0) {
+      Ok(s) => write!(f, "={:?}", s)?,
+      Err(x) => write!(f, "={:?}..",
+                       str::from_utf8(&self.0[0..x.valid_up_to()]).unwrap()
+      )?,
+    }
+  }
+}
+
+#[test]
+fn mime_slip_to_mime() {
+  use PacketError as PE;
+  const MTU: u32 = 10;
+
+  fn chk<M: SlipMime>(i: &[u8], exp_p: &[&[u8]], exp_e: &[PacketError]) {
+    dbg!(M::CONV_TO, DumpHex(i));
+    let mut got_e = vec![];
+    let mut got_p = vec![];
+    check::<_,_,_,M>(MTU, i, &mut got_p, |_|Ok(()), |e| got_e.push(e));
+    assert_eq!( got_p.iter().map(|b| DumpHex(b)).collect_vec(),
+                exp_p.iter().map(|b| DumpHex(b)).collect_vec() );
+    assert_eq!( got_e,
+                exp_e );
+  }
+
+  chk::<Slip2Mime>
+     ( &[ SLIP_END, SLIP_ESC, SLIP_ESC_END, b'-',     b'X' ],
+    &[           &[ b'-',     SLIP_ESC_END, SLIP_ESC, b'X' ] ],
+    &[ PE::Empty ]);
+
+  chk::<Slip2Mime>
+     ( &[ SLIP_END, SLIP_ESC, b'y' ], &[],
+    &[ PE::Empty,   PE::SLIP ]);
+
+  chk::<Slip2Mime>
+     ( &[ SLIP_END, b'-',     b'y' ],
+    &[           &[ SLIP_ESC, b'y' ] ],
+    &[ PE::Empty ]);
+
+  chk::<Slip2Mime>
+     ( &[b'x'; 20],
+    &[             ],
+    &[ PE::MTU { len: 20, mtu: MTU } ]);
+
+  chk::<SlipNoConv>
+     ( &[ SLIP_END, SLIP_ESC, SLIP_ESC_END, b'-',     b'X' ],
+    &[           &[ SLIP_ESC, SLIP_ESC_END, b'-',     b'X' ] ],
+    &[ PE::Empty, ]);
+}
+
+