chiark / gitweb /
make route_packet async
[hippotat.git] / src / bin / server.rs
index 15b5161c9203df0e7a6ea4d6579d4c14edf1727c..57f9bc75caa6b813365234c4f9c8e79f85a53c80 100644 (file)
@@ -15,13 +15,20 @@ pub struct Opts {
 
 const METADATA_MAX_LEN: usize = MAX_OVERHEAD;
 
-type AllClients = HashMap<ClientName, ClientHandles>;
+#[derive(Debug)]
+pub struct Global {
+  config: config::InstanceConfigGlobal,
+  all_clients: HashMap<ClientName, Client>,
+}
 
-struct ClientHandles {
+#[derive(Debug)]
+pub struct Client {
   ic: Arc<InstanceConfig>,
-  web: tokio::sync::mpsc::Sender<WebRequest>,
+  web: mpsc::Sender<WebRequest>,
 }
 
+pub type RoutedPacket = Box<[u8]>; // not MIME data
+
 /// Sent from hyper worker pool task to client task
 #[allow(dead_code)] // xxx
 #[derive(Debug)]
@@ -34,8 +41,9 @@ struct WebRequest {
   length_hint: usize,
   body: hyper::body::Body,
   boundary_finder: multipart::BoundaryFinder,
-  reply_to: tokio::sync::oneshot::Sender<WebResponse>,
+  reply_to: oneshot::Sender<WebResponse>,
   warnings: Warnings,
+  conn: Arc<String>,
 }
 
 /// Reply from client task to hyper worker pool task
@@ -49,13 +57,28 @@ struct WebResponse {
 type WebResponseData = Vec<u8>;
 
 #[throws(PacketError)]
-pub fn route_packet(packet: Box<[u8]>, daddr: IpAddr) {
-  trace!("xxx discarding packet daddr={:?} len={}", daddr, packet.len());
+pub async fn route_packet(global: &Global,
+                          conn: &str, link: &(dyn Display + Sync),
+                          packet: RoutedPacket, daddr: IpAddr)
+{
+  let c = &global.config;
+  let trace = |how| trace!("{} {} route {} daddr={:?} len={}",
+                           conn, link, how, daddr, packet.len());
+
+  if daddr == c.vaddr || ! c.vnetwork.iter().any(|n| n.contains(&daddr)) {
+    trace("ipif inbound xxx discarding");
+  } else if daddr == c.vrelay {
+    trace("discard (relay)");
+  } else if let Some(_client) = global.all_clients.get(&ClientName(daddr)) {
+    trace("ipif route xxx discarding");
+  } else {
+    trace("discard (no client)");
+  }
 }
 
 async fn handle(
   conn: Arc<String>,
-  all_clients: Arc<AllClients>,
+  global: Arc<Global>,
   req: hyper::Request<hyper::Body>
 ) -> Result<hyper::Response<hyper::Body>, hyper::http::Error> {
   if req.method() == Method::GET {
@@ -152,7 +175,7 @@ async fn handle(
     let hmac_got = &hmac_got[0..hmac_got_l];
 
     let client_name = client;
-    let client = all_clients.get(&client_name);
+    let client = global.all_clients.get(&client_name);
 
     // We attempt to hide whether the client exists we don't try to
     // hide the hash lookup computationgs, but we do try to hide the
@@ -198,8 +221,9 @@ async fn handle(
     //eprintln!("boundary={:?} start={} name={:?} client={}",
     // boundary, start, &comp.name, &client.ic);
 
-    let (reply_to, reply_recv) = tokio::sync::oneshot::channel();
-    trace!("{} request xxx={}", &client.ic, initial.len());
+    let (reply_to, reply_recv) = oneshot::channel();
+    trace!("{} {} request, Content-Length={}",
+           &conn, &client_name, length_hint);
     let wreq = WebRequest {
       initial,
       initial_remaining,
@@ -207,7 +231,8 @@ async fn handle(
       boundary_finder: boundary_finder.into_owned(),
       body,
       warnings: mem::take(&mut warnings),
-      reply_to
+      reply_to,
+      conn: conn.clone(),
     };
 
     client.web.try_send(wreq)
@@ -217,9 +242,13 @@ async fn handle(
     warnings = reply.warnings;
     let data = reply.data?;
 
-    if ! warnings.warnings.is_empty()
-    && log::log_enabled!(log::Level::Trace) {
-      trace!("{} {}: warnings {:?}", &conn, &client_name, &warnings.warnings);
+    if warnings.warnings.is_empty() {
+      trace!("{} {} responding, {}",
+             &conn, &client_name, data.len());
+    } else {
+      debug!("{} {} responding, {} warnings={:?}",
+             &conn, &client_name, data.len(),
+             &warnings.warnings);
     }
 
     let data = hyper::Body::from(data);
@@ -243,12 +272,13 @@ async fn handle(
 
 #[allow(unused_variables)] // xxx
 #[allow(unused_mut)] // xxx
-async fn run_client(ic: Arc<InstanceConfig>,
+async fn run_client(global: Arc<Global>,
+                    ic: Arc<InstanceConfig>,
                     mut web: mpsc::Receiver<WebRequest>)
                     -> Result<Void, AE>
 {
   struct Outstanding {
-    reply_to: tokio::sync::oneshot::Sender<WebResponse>,
+    reply_to: oneshot::Sender<WebResponse>,
     oi: OutstandingInner,
   }
   #[derive(Debug)]
@@ -259,7 +289,7 @@ async fn run_client(ic: Arc<InstanceConfig>,
   let  downbound: VecDeque<(/*xxx*/)> = default();
 
   let try_send_response = |
-    reply_to: tokio::sync::oneshot::Sender<WebResponse>,
+    reply_to: oneshot::Sender<WebResponse>,
     response: WebResponse
   | {
     reply_to.send(response)
@@ -283,7 +313,6 @@ async fn run_client(ic: Arc<InstanceConfig>,
         warnings: default(),
       };
 
-      dbg!(&response);
       try_send_response(ret.reply_to, response);
     }
 
@@ -293,7 +322,7 @@ async fn run_client(ic: Arc<InstanceConfig>,
         let WebRequest {
           initial, initial_remaining, length_hint, mut body,
           boundary_finder,
-          reply_to, mut warnings,
+          reply_to, conn, mut warnings,
         } = req.ok_or_else(|| anyhow!("webservers all shut down!"))?;
 
         match async {
@@ -330,7 +359,7 @@ async fn run_client(ic: Arc<InstanceConfig>,
                 )?
                 Ok::<_,AE>($ret)
               })().context(stringify!($v))?;
-              dbg!(&$v);
+              //dbg!(&$v);
             }
           }
 
@@ -368,9 +397,11 @@ async fn run_client(ic: Arc<InstanceConfig>,
               if saddr != ic.link.client.0 { throw!(PE::Src(saddr)) }
               let daddr = ip_packet_addr::<true>(header)?;
               Ok(daddr)
-            }, |(daddr,packet)| route_packet(daddr,packet),
-               |e| Ok::<_,SlipFramesError<_>>({ warnings.add(&e)?; })
-            )?;
+            }, |(daddr,packet)| route_packet(
+              &global, &conn, &ic.link.client, daddr,packet
+            ),
+              |e| Ok::<_,SlipFramesError<_>>({ warnings.add(&e)?; })
+            ).await?;
           }
 
           let oi = OutstandingInner {
@@ -404,41 +435,57 @@ async fn main() {
     "hippotatd", LinkEnd::Server,
     &opts.config, &opts.log, |ics|
   {
-    let global = config::InstanceConfigGlobal::from(&ics);
-    let ipif = Ipif::start(&global.ipif, None)?;
+    let global_config = config::InstanceConfigGlobal::from(&ics);
 
-    let all_clients: AllClients = ics.into_iter().map(|ic| {
-      let ic = Arc::new(ic);
+    let ipif = Ipif::start(&global_config.ipif, None)?;
 
-      let (web_send, web_recv) = mpsc::channel(
+    let ics = ics.into_iter().map(Arc::new).collect_vec();
+    let (client_handles_send, client_handles_recv) = ics.iter()
+      .map(|_ic| mpsc::channel(
         5 // xxx should me max_requests_outstanding but that's
-          // marked client-only so needs rework
-      );
-
-      let ic_ = ic.clone();
-      tasks.push((tokio::spawn(async move {
-        run_client(ic_, web_recv).await.void_unwrap_err()
-      }), format!("client {}", &ic)));
+        // marked client-only so needs rework
+      )).unzip::<_,_,Vec<_>,Vec<_>>();
 
+    let all_clients = izip!(
+      &ics,
+      client_handles_send,
+    ).map(|(ic, web_send)| {
       (ic.link.client,
-       ClientHandles {
-         ic,
+       Client {
+         ic: ic.clone(),
          web: web_send,
        })
     }).collect();
-    let all_clients = Arc::new(all_clients);
-
-    for addr in &global.addrs {
-      let all_clients_ = all_clients.clone();
-      let make_service = hyper::service::make_service_fn(move |conn| {
-        let all_clients_ = all_clients_.clone();
-        let conn = Arc::new(format!("[conn:{:?}]", conn));
-        async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
-          handle(conn.clone(), all_clients_.clone(), req)
-        }) ) } }
+
+    let global = Arc::new(Global {
+      config: global_config,
+      all_clients,
+    });
+
+    for (ic, web_recv) in izip!(
+      ics,
+      client_handles_recv,
+    ) {
+      let global_ = global.clone();
+      let ic_ = ic.clone();
+      tasks.push((tokio::spawn(async move {
+        run_client(global_, ic_, web_recv).await.void_unwrap_err()
+      }), format!("client {}", &ic)));
+    }
+
+    for addr in &global.config.addrs {
+      let global_ = global.clone();
+      let make_service = hyper::service::make_service_fn(
+        move |conn: &hyper::server::conn::AddrStream| {
+          let global_ = global_.clone();
+          let conn = Arc::new(format!("[{}]", conn.remote_addr()));
+          async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
+            handle(conn.clone(), global_.clone(), req)
+          }) ) }
+        }
       );
 
-      let addr = SocketAddr::new(*addr, global.port);
+      let addr = SocketAddr::new(*addr, global.config.port);
       let server = hyper::Server::try_bind(&addr)
         .context("bind")?
         .http1_preserve_header_case(true)