chiark / gitweb /
server: improve messages
[hippotat.git] / src / bin / server.rs
index cf0eec1d34425d054a6ea298db5facd97b202836..4b5fc527d25c090d4d34530e88a1abbaed66ddcc 100644 (file)
@@ -36,6 +36,7 @@ struct WebRequest {
   boundary_finder: multipart::BoundaryFinder,
   reply_to: tokio::sync::oneshot::Sender<WebResponse>,
   warnings: Warnings,
+  conn: Arc<String>,
 }
 
 /// Reply from client task to hyper worker pool task
@@ -46,12 +47,22 @@ struct WebResponse {
   data: Result<WebResponseData, AE>,
 }
 
-type WebResponseData = ();
+type WebResponseData = Vec<u8>;
+
+#[throws(PacketError)]
+pub fn route_packet(conn: &str, link: &dyn Display,
+                    packet: Box<[u8]>, daddr: IpAddr)
+{
+  // xxx
+  trace!("{} {} discarding packet daddr={:?} len={}",
+         conn, link, daddr, packet.len());
+}
 
 async fn handle(
+  conn: Arc<String>,
   all_clients: Arc<AllClients>,
   req: hyper::Request<hyper::Body>
-) -> Result<hyper::Response<hyper::Body>, Void> {
+) -> Result<hyper::Response<hyper::Body>, hyper::http::Error> {
   if req.method() == Method::GET {
     let mut resp = hyper::Response::new(hyper::Body::from("hippotat\r\n"));
     resp.headers_mut().insert(
@@ -63,7 +74,7 @@ async fn handle(
 
   let mut warnings: Warnings = default();
 
-  match async {
+  async {
 
     let get_header = |hn: &str| {
       let mut values = req.headers().get_all(hn).iter();
@@ -145,7 +156,8 @@ async fn handle(
     })().context("token")?;
     let hmac_got = &hmac_got[0..hmac_got_l];
 
-    let client = all_clients.get(&client);
+    let client_name = client;
+    let client = 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
@@ -162,7 +174,14 @@ async fn handle(
     //dbg!(DumpHex(&hmac_exp), client.is_some());
     //dbg!(DumpHex(hmac_got), hmac_ok, client_exists);
     if ! bool::from(hmac_ok & client_exists) {
-      throw!(anyhow!("xxx should be a 403 error"));
+      debug!("{} rejected client {}", &conn, &client_name);
+      let body = hyper::Body::from("Not authorised\r\n");
+      return Ok(
+        hyper::Response::builder()
+          .status(hyper::StatusCode::FORBIDDEN)
+          .header("Content-Type", r#"text/plain; charset="utf-8""#)
+          .body(body)
+      )
     }
 
     let client = client.unwrap();
@@ -185,7 +204,8 @@ async fn handle(
     // boundary, start, &comp.name, &client.ic);
 
     let (reply_to, reply_recv) = tokio::sync::oneshot::channel();
-    trace!("{} request xxx={}", &client.ic, initial.len());
+    trace!("{} {} request, Content-Length={}",
+           &conn, &client_name, length_hint);
     let wreq = WebRequest {
       initial,
       initial_remaining,
@@ -193,7 +213,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)
@@ -201,19 +222,34 @@ async fn handle(
 
     let reply: WebResponse = reply_recv.await?;
     warnings = reply.warnings;
-
-    reply.data
-  }.await {
-    Ok(()) => {
-    },
-    Err(e) => {
-      eprintln!("error={}", e);
+    let data = reply.data?;
+
+    if warnings.warnings.is_empty() {
+      trace!("{} {} responding, {}",
+             &conn, &client_name, data.len());
+    } else {
+      debug!("{} {} responding, {} warnings={:?}",
+             &conn, &client_name, data.len(),
+             &warnings.warnings);
     }
-  }
-
-  eprintln!("warnings={:?}", &warnings);
 
-  Ok(hyper::Response::new(hyper::Body::from("Hello World")))
+    let data = hyper::Body::from(data);
+    Ok::<_,AE>(
+      hyper::Response::builder()
+        .header("Content-Type", r#"application/octet-stream"#)
+        .body(data)
+    )
+  }.await.unwrap_or_else(|e| {
+    debug!("{} error {}", &conn, &e);
+    let mut errmsg = format!("ERROR\n\n{:?}\n\n", &e);
+    for w in warnings.warnings {
+      write!(errmsg, "warning: {}\n", w).unwrap();
+    }
+    hyper::Response::builder()
+      .status(hyper::StatusCode::BAD_REQUEST)
+      .header("Content-Type", r#"text/plain; charset="utf-8""#)
+      .body(errmsg.into())
+  })
 }
 
 #[allow(unused_variables)] // xxx
@@ -254,11 +290,10 @@ async fn run_client(ic: Arc<InstanceConfig>,
       }
     } {
       let response = WebResponse {
-        data: Ok(()),
+        data: Ok(vec![ /* xxx */ ]),
         warnings: default(),
       };
 
-      dbg!(&response);
       try_send_response(ret.reply_to, response);
     }
 
@@ -268,7 +303,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 {
@@ -305,7 +340,7 @@ async fn run_client(ic: Arc<InstanceConfig>,
                 )?
                 Ok::<_,AE>($ret)
               })().context(stringify!($v))?;
-              dbg!(&$v);
+              //dbg!(&$v);
             }
           }
 
@@ -319,6 +354,11 @@ async fn run_client(ic: Arc<InstanceConfig>,
             let server, client = Duration::from_secs(meta.need_parse()?);
           }
 
+          meta!{
+            mtu, ( != ), client,
+            let server, client: u32 = meta.parse()?.unwrap_or(server);
+          }
+
           meta!{
             max_batch_down, (), min(client, server),
             let server, client: u32 = meta.parse()?.unwrap_or(server);
@@ -333,7 +373,16 @@ async fn run_client(ic: Arc<InstanceConfig>,
             if comp.name != PartName::d {
               warnings.add(&format_args!("unexpected part {:?}", comp.name))?;
             }
-            dbg!(comp.name, DumpHex(comp.payload));
+            checkn(Mime2Slip, mtu, comp.payload, |header| {
+              let saddr = ip_packet_addr::<false>(header)?;
+              if saddr != ic.link.client.0 { throw!(PE::Src(saddr)) }
+              let daddr = ip_packet_addr::<true>(header)?;
+              Ok(daddr)
+            }, |(daddr,packet)| route_packet(
+              &conn, &ic.link.client, daddr,packet
+            ),
+              |e| Ok::<_,SlipFramesError<_>>({ warnings.add(&e)?; })
+            )?;
           }
 
           let oi = OutstandingInner {
@@ -393,11 +442,14 @@ async fn main() {
 
     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();
-        async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
-          handle(all_clients_.clone(), req)
-        }) ) } }
+      let make_service = hyper::service::make_service_fn(
+        move |conn: &hyper::server::conn::AddrStream| {
+          let all_clients_ = all_clients_.clone();
+          let conn = Arc::new(format!("[{}]", conn.remote_addr()));
+          async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
+            handle(conn.clone(), all_clients_.clone(), req)
+          }) ) }
+        }
       );
 
       let addr = SocketAddr::new(*addr, global.port);