chiark / gitweb /
server: improve messages
[hippotat.git] / src / bin / server.rs
index c3b7b15cd0956e19b07e183ba3b93a502853358a..4b5fc527d25c090d4d34530e88a1abbaed66ddcc 100644 (file)
@@ -24,6 +24,7 @@ struct ClientHandles {
 
 /// Sent from hyper worker pool task to client task
 #[allow(dead_code)] // xxx
+#[derive(Debug)]
 struct WebRequest {
   // initial part of body
   // used up to and including first 2 lines of metadata
@@ -35,21 +36,33 @@ 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
 #[allow(dead_code)] // xxx
+#[derive(Debug)]
 struct WebResponse {
   warnings: Warnings,
   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(
@@ -61,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();
@@ -143,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
@@ -160,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();
@@ -183,6 +204,8 @@ async fn handle(
     // boundary, start, &comp.name, &client.ic);
 
     let (reply_to, reply_recv) = tokio::sync::oneshot::channel();
+    trace!("{} {} request, Content-Length={}",
+           &conn, &client_name, length_hint);
     let wreq = WebRequest {
       initial,
       initial_remaining,
@@ -190,28 +213,43 @@ async fn handle(
       boundary_finder: boundary_finder.into_owned(),
       body,
       warnings: mem::take(&mut warnings),
-      reply_to
+      reply_to,
+      conn: conn.clone(),
     };
-    trace!("{} request", &client.ic);
 
     client.web.try_send(wreq)
       .map_err(|_| anyhow!("client task shut down!"))?;
 
     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
@@ -222,7 +260,11 @@ async fn run_client(ic: Arc<InstanceConfig>,
 {
   struct Outstanding {
     reply_to: tokio::sync::oneshot::Sender<WebResponse>,
-    max_requests_outstanding: u32,
+    oi: OutstandingInner,
+  }
+  #[derive(Debug)]
+  struct OutstandingInner {
+    target_requests_outstanding: u32,
   }
   let mut outstanding: VecDeque<Outstanding> = default();
   let  downbound: VecDeque<(/*xxx*/)> = default();
@@ -240,7 +282,7 @@ async fn run_client(ic: Arc<InstanceConfig>,
       if ! downbound.is_empty() {
         outstanding.pop_front()
       } else if let Some((i,_)) = outstanding.iter().enumerate().find({
-        |(_,o)| outstanding.len() > o.max_requests_outstanding.sat()
+        |(_,o)| outstanding.len() > o.oi.target_requests_outstanding.sat()
       }) {
         Some(outstanding.remove(i).unwrap())
       } else {
@@ -248,7 +290,7 @@ async fn run_client(ic: Arc<InstanceConfig>,
       }
     } {
       let response = WebResponse {
-        data: Ok(()),
+        data: Ok(vec![ /* xxx */ ]),
         warnings: default(),
       };
 
@@ -261,7 +303,7 @@ async fn run_client(ic: Arc<InstanceConfig>,
         let WebRequest {
           initial, initial_remaining, length_hint, mut body,
           boundary_finder,
-          reply_to, warnings,
+          reply_to, conn, mut warnings,
         } = req.ok_or_else(|| anyhow!("webservers all shut down!"))?;
 
         match async {
@@ -275,7 +317,7 @@ async fn run_client(ic: Arc<InstanceConfig>,
             &mut body
           ).await.context("read request body")?;
 
-          let (meta, comps) =
+          let (meta, mut comps) =
             multipart::ComponentIterator::resume_mid_component(
               &whole_request[initial_used..],
               boundary_finder
@@ -298,7 +340,7 @@ async fn run_client(ic: Arc<InstanceConfig>,
                 )?
                 Ok::<_,AE>($ret)
               })().context(stringify!($v))?;
-              dbg!(&$v);
+              //dbg!(&$v);
             }
           }
 
@@ -312,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);
@@ -322,12 +369,28 @@ async fn run_client(ic: Arc<InstanceConfig>,
             let server, client = meta.parse()?.unwrap_or(server);
           }
 
-          Ok::<_,AE>(())
+          while let Some(comp) = comps.next(&mut warnings, PartName::d)? {
+            if comp.name != PartName::d {
+              warnings.add(&format_args!("unexpected part {:?}", comp.name))?;
+            }
+            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 {
+            target_requests_outstanding,
+          };
+          Ok::<_,AE>(oi)
         }.await {
-          Ok(()) => outstanding.push_back(Outstanding {
-            reply_to: reply_to,
-            max_requests_outstanding: 42, // xxx
-          }),
+          Ok(oi) => outstanding.push_back(Outstanding { reply_to, oi }),
           Err(e) => {
             try_send_response(reply_to, WebResponse {
               data: Err(e),
@@ -379,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);