chiark / gitweb /
forward
[hippotat.git] / server / slocal.rs
index 919c33882cb8a123bcb64d09aa091e8faeb9e86f..eaa7adaa4ef5819a8e0ce39061cdb333ca372cb3 100644 (file)
@@ -5,8 +5,79 @@
 use super::*;
 
 #[allow(dead_code)] // xxx
-#[throws(PacketError)]
-pub async fn run(_global: &Global,
-                 _rx: mpsc::Receiver<RoutedPacket>) {
-  
+#[allow(unused_variables)] // xxx
+pub async fn run(global: Arc<Global>,
+                 mut rx: mpsc::Receiver<RoutedPacket>,
+                 mut ipif: Ipif) -> Result<Void,AE> {
+  let r = async {
+    let mut goodness: i32 = 0;
+    const GOODNESS_SHIFT: u8 = 8;
+    const GOODNESS_MIN: i32 = -16;
+
+    loop {
+      select!{
+        biased;
+
+        data = rx.recv() =>
+        {
+          let data = data.ok_or_else(|| anyhow!("rx stream end!"))?;
+          let mut data = &*data.data;
+          let mut slip_end = &[SLIP_END][..];
+          let mut buf = Buf::chain(&mut data, &mut slip_end);
+          ipif.rx.write_all_buf(&mut buf).await
+            .context("write to ipif")?;
+        },
+
+        data = Ipif::next_frame(&mut ipif.tx) =>
+        {
+          let data = data?;
+          let may_route = MayRoute::came_from_outside_hippotatd();
+
+          goodness -= goodness >> GOODNESS_SHIFT;
+
+          match checkn(SlipNoConv, global.config.mtu, &data, |header|{
+            let saddr = ip_packet_addr::<false>(header)?;
+            let daddr = ip_packet_addr::<true>(header)?;
+            Ok((saddr,daddr))
+          }, |(data, (saddr, daddr))| {
+            let global = &global;
+            let may_route = &may_route;
+            async move {
+              if ! global.config.vnetwork.iter().any(|n| n.contains(&saddr)) {
+                // pretent as if this came from route
+                trace!(
+                  target: "hippotatd",
+ "discard to={:?} via=ipif user=local from-outside-vnets-={:?}",
+                  daddr, saddr);
+                return Ok(())
+              }
+
+              route_packet(
+                &global, "ipif", None,
+                data, daddr, may_route.clone()
+              ).await;
+
+              Ok(())
+            }
+          }, |pe| Ok(match pe {
+            PE::Empty => { },
+            other => throw!(other),
+          })).await {
+            Ok(()) => goodness += 1,
+            Err(e) => {
+              goodness -= 1;
+              error!("[good={}] invalid data from local tx ipif {}",
+                     goodness, e);
+              if goodness < GOODNESS_MIN {
+                throw!(anyhow!("too many bad packets, too few good ones!"))
+              }
+            },
+          }
+        },
+      }
+    }
+  }.await;
+
+  ipif.quitting(None).await;
+  r
 }