chiark / gitweb /
new max_batch_down protocol, define
[hippotat.git] / src / bin / client.rs
index ba311965fc67c097b0b6474074f4321d1cb2f19c..70fe9b96af78e000903f16e3108435121ecddc55 100644 (file)
@@ -1,10 +1,20 @@
 // 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 hippotat::prelude::*;
 use hippotat_macros::into_crlfs;
 
+#[derive(StructOpt,Debug)]
+pub struct Opts {
+  /// Increase debug level
+  #[structopt(long, short="D", parse(from_occurrences))]
+  debug: usize,
+
+  #[structopt(flatten)]
+  config: config::Opts,
+}
+
 type OutstandingRequest<'r> = Pin<Box<
     dyn Future<Output=Option<Bytes>> + Send + 'r
     >>;
@@ -15,6 +25,7 @@ trait HCC: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
 
 struct ClientContext<'c,C> {
   ic: &'c InstanceConfig,
+  effective_http_timeout: Duration,
   hclient: &'c Arc<hyper::Client<C>>,
   reporter: &'c parking_lot::Mutex<Reporter<'c>>,
 }
@@ -22,6 +33,7 @@ struct ClientContext<'c,C> {
 #[throws(AE)]
 fn submit_request<'r, 'c:'r, C:HCC>(
   c: &'c ClientContext<C>,
+  req_num: &mut ReqNum,
   reqs: &mut Vec<OutstandingRequest<'r>>,
   upbound: FramesData,
 ) {
@@ -29,24 +41,38 @@ fn submit_request<'r, 'c:'r, C:HCC>(
     .saturating_add(Duration::from_nanos(999_999_999))
     .as_secs();
 
-  let prefix = format!(into_crlfs!(
-    r#"--
+  let time_t = SystemTime::now()
+    .duration_since(UNIX_EPOCH)
+    .unwrap_or_else(|_| Duration::default()) // clock is being weird
+    .as_secs();
+  let time_t = format!("{:x}", time_t);
+  let hmac = token_hmac(c.ic.secret.0.as_bytes(), time_t.as_bytes());
+  let mut token = time_t;
+  write!(token, " ").unwrap();
+  base64::encode_config_buf(&hmac, BASE64_CONFIG, &mut token);
+
+  let req_num = { *req_num += 1; *req_num };
+
+  let prefix1 = format!(into_crlfs!(
+    r#"--b
        Content-Type: text/plain; charset="utf-8"
        Content-Disposition: form-data; name="m"
 
        {}
        {}
        {}
+       {}
        {}"#),
                        &c.ic.link.client,
-                       "xxx token goes here",
+                       token,
                        c.ic.target_requests_outstanding,
                        show_timeout,
+                       c.ic.max_batch_down,
   );
 
   let prefix2 = format!(into_crlfs!(
     r#"
-       --
+       --b
        Content-Type: application/octet-stream
        Content-Disposition: form-data; name="d"
 
@@ -57,36 +83,71 @@ fn submit_request<'r, 'c:'r, C:HCC>(
        --b--
        "#),
   );
-eprintln!(">{}[{}D]{}<", &prefix, &prefix2, &suffix);
+
+  macro_rules! content { {
+    $out:ty,
+    $iter:ident,
+    $into:ident,
+  } => {
+    itertools::chain![
+      array::IntoIter::new([
+        prefix1.$into(),
+        prefix2.$into(),
+      ]).take(
+        if upbound.is_empty() { 1 } else { 2 }
+      ),
+      Itertools::intersperse(
+        upbound.$iter().map(|u| { let out: $out = u.$into(); out }),
+        SLIP_END_SLICE.$into()
+      ),
+      [ suffix.$into() ],
+    ]
+  }}
+
+  let body_len: usize = content!(
+    &[u8],
+    iter,
+    as_ref,
+  ).map(|b| b.len()).sum();
+
+  trace!("{} #{}: frames={} bytes={}",
+         &c.ic, req_num, upbound.len(), body_len);
 
   let body = hyper::body::Body::wrap_stream(
     futures::stream::iter(
-      Itertools::intersperse(
-        upbound.into_iter().map(|u| Bytes::from(u)),
-        SLIP_END_SLICE.into()
-      ).map(Ok::<_,Void>)
+      content!(
+        Bytes,
+        into_iter,
+        into,
+      ).map(Ok::<Bytes,Void>)
     )
   );
 
-  let req = hyper::Request::post(&c.ic.url).body(body)
+  let req = hyper::Request::post(&c.ic.url)
+    .header("Content-Type", r#"multipart/form-data; boundary="b""#)
+    .header("Content-Length", body_len)
+    .body(body)
     .context("construct request")?;
 
   let resp = c.hclient.request(req);
   let fut = Box::pin(async move {
-    let r = async { tokio::time::timeout( c.ic.http_timeout, async {
+    let r = async { tokio::time::timeout( c.effective_http_timeout, async {
       let resp = resp.await.context("make request")?;
-      if ! resp.status().is_success() {
-        throw!(anyhow!("HTTP error status {}", &resp.status()));
-      }
+      let status = resp.status();
       let resp = resp.into_body();
       // xxx: some size limit to avoid mallocing the universe
       let resp = hyper::body::to_bytes(resp).await
         .context("HTTP error fetching response body")?;
 
+      if ! status.is_success() {
+        throw!(anyhow!("HTTP error status={} body={:?}",
+                       &status, String::from_utf8_lossy(&resp)));
+      }
+
       Ok::<_,AE>(resp)
     }).await? }.await;
 
-    let r = c.reporter.lock().report(r);
+    let r = c.reporter.lock().filter(Some(req_num), r);
 
     if r.is_none() {
       tokio::time::sleep(c.ic.http_retry).await;
@@ -96,7 +157,6 @@ eprintln!(">{}[{}D]{}<", &prefix, &prefix2, &suffix);
   reqs.push(fut);
 }
 
-#[allow(unused_variables)] // xxx
 async fn run_client<C:HCC>(
   ic: InstanceConfig,
   hclient: Arc<hyper::Client<C>>
@@ -110,6 +170,9 @@ async fn run_client<C:HCC>(
     reporter: &reporter,
     hclient: &hclient,
     ic: &ic,
+    effective_http_timeout: ic.http_timeout.checked_add(ic.http_timeout_grace)
+      .ok_or_else(|| anyhow!("calculate effective http timeout ({:?} + {:?})",
+                             ic.http_timeout, ic.http_timeout_grace))?,
   };
 
   let mut ipif = tokio::process::Command::new("sh")
@@ -130,81 +193,95 @@ async fn run_client<C:HCC>(
     Ok::<_,io::Error>(())
   });
 
+  let mut req_num: ReqNum = 0;
+
   let tx_stream = ipif.stdout.take().unwrap();
-  let mut tx_stream = tokio::io::BufReader::new(tx_stream).split(SLIP_ESC);
-  let mut tx_defer = None;
+  let mut rx_stream = ipif.stdin .take().unwrap();
 
-  let stream_for_rx = ipif.stdin .take().unwrap();
+  let mut tx_stream = tokio::io::BufReader::new(tx_stream).split(SLIP_END);
+  let mut packets: VecDeque<Box<[u8]>> = default();
+  let mut upbound = Frames::default();
 
   let mut reqs: Vec<OutstandingRequest>
     = Vec::with_capacity(ic.max_requests_outstanding.sat());
 
+  let mut rx_queue: FrameQueue = default();
+
   // xxx check that ic settings are all honoured
 
   async {
     loop {
       select! {
-        packet = async {
-          // cancellation safety: if this future is polled, we might
-          // move out of tx_defer, but then we will be immediately
-          // ready and yield it inot packet
-          if let Some(y) = tx_defer.take() {
-            Ok(Some(y))
-          } else {
-            tx_stream.next_segment().await
-          }
+        y = rx_stream.write_all_buf(&mut rx_queue),
+        if ! rx_queue.is_empty() =>
+        {
+          let () = y.context("write rx data to ipif")?;
+        },
+
+        data = tx_stream.next_segment(),
+        if packets.is_empty() =>
+        {
+          let data =
+            data.context("read from ipif")?
+            .ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
+          //eprintln!("data={:?}", DumpHex(&data));
+
+          match check1(Slip2Mime, ic.mtu, &data, |header| {
+            let addr = ip_packet_addr::<false>(header)?;
+            if addr != ic.link.client.0 { throw!(PE::Src(addr)) }
+            Ok(())
+          }) {
+            Ok(packet) => packets.push_back(packet),
+            Err(PE::Empty) => { },
+            Err(e@ PE::Src(_)) => debug!("{}: tx discarding: {}", &ic, e),
+            Err(e) => error!("{}: tx discarding: {}", &ic, e),
+          };
         },
-        if tx_defer.is_none() &&
-           reqs.len() < ic.max_requests_outstanding.sat() =>
+
+        _ = async { },
+        if ! upbound.tried_full() &&
+           ! packets.is_empty() =>
         {
-          let mut upbound = Frames::default();
-          let mut to_process: Option<Result<Option<Vec<u8>>,_>>
-            = Some(packet);
-          while let Some(packet) = to_process.take() {
-            let mut packet =
-              packet.context("read from ipif")?
-              .ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
-            if let Ok(()) = check_checkmtu_mimeswap
-              ::<true>(&ic, &mut packet)
-            {
-              match upbound.add(ic.max_batch_up, packet) {
-                Err(packet) => {
-                  tx_defer = Some(packet);
-                  break;
-                }
-                Ok(()) => { },
-              };
-              // we rely oin `next_segment` being cancellation-safe,
-              // which isn't documented as true but seems reasonably safe
-              pin!{ let next_segment = tx_stream.next_segment(); }
-              to_process = match poll!(next_segment) {
-                Poll::Ready(p) => Some(p),
-                Poll::Pending => None,
-              };
+          while let Some(packet) = packets.pop_front() {
+            match upbound.add(ic.max_batch_up, packet.into()/*xxx*/) {
+              Err(packet) => { packets.push_front(packet.into()/*xxx*/); break; }
+              Ok(()) => { },
             }
           }
-          assert!( to_process.is_none() );
-          dbg!(&reqs.len(), &upbound);
-
-          //: impl futures::Stream<Cow<&[u8]>>
-          submit_request(&c, &mut reqs, upbound.into())?;
-        }
+        },
 
-        () = async { },
-        if reqs.len() < ic.target_requests_outstanding.sat() ||
-           (tx_defer.is_some() &&
-            reqs.len() < ic.max_requests_outstanding.sat()) =>
+        _ = async { },
+        if reporter.lock().filter(None, {
+          if rx_queue.remaining() < ic.max_batch_down.sat() * 3 /* xxx */ {
+            // xxx make this separate option ? docs say server only
+            Ok(())
+          } else {
+            Err(anyhow!("rx queue full"))
+          }
+        }).is_some() &&
+          (reqs.len() < ic.target_requests_outstanding.sat() ||
+           (reqs.len() < ic.max_requests_outstanding.sat() &&
+            ! upbound.is_empty()))
+          =>
         {
-          let upbound = tx_defer.take().into_iter().collect_vec();
-          submit_request(&c, &mut reqs, upbound)?;
-        }
+          submit_request(&c, &mut req_num, &mut reqs,
+                         mem::take(&mut upbound).into())?;
+        },
 
         (got, goti, _) = async { future::select_all(&mut reqs).await },
           if ! reqs.is_empty() =>
         {
           reqs.swap_remove(goti);
+
           if let Some(got) = got {
-            dbg!(&got.remaining()); // xxx
+            reporter.lock().success();
+            //eprintln!("got={:?}", DumpHex(&got));
+            checkn(SlipNoConv,ic.mtu, &got, &mut rx_queue, |header| {
+              let addr = ip_packet_addr::<true>(header)?;
+              if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
+              Ok(())
+            }, |e| error!("{} #{}: rx discarding: {}", &ic, req_num, e));
+          
           }
         }
       }
@@ -214,10 +291,27 @@ async fn run_client<C:HCC>(
 
 #[tokio::main]
 async fn main() -> Result<(), AE> {
-  let ics = config::read(LinkEnd::Client)?;
+  let opts = Opts::from_args();
+
+  let ics = config::read(&opts.config, LinkEnd::Client)?;
   if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
 
-  env_logger::init();
+  {
+    let env = env_logger::Env::new()
+      .filter("HIPPOTAT_LOG")
+      .write_style("HIPPOTAT_LOG_STYLE");
+  
+    let mut logb = env_logger::Builder::new();
+    logb.filter(Some("hippotat"),
+                *[ log::LevelFilter::Info,
+                   log::LevelFilter::Debug ]
+                .get(opts.debug)
+                .unwrap_or(
+                  &log::LevelFilter::Trace
+                ));
+    logb.parse_env(env);
+    logb.init();
+  }
 
   let https = HttpsConnector::new();
   let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);