// 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 {
+ #[structopt(flatten)]
+ log: LogOpts,
+
+ #[structopt(flatten)]
+ config: config::Opts,
+}
type OutstandingRequest<'r> = Pin<Box<
- dyn Future<Output=Result<Bytes,AE>> + Send + 'r
+ dyn Future<Output=Option<Box<[u8]>>> + Send + 'r
>>;
impl<T> HCC for T where
T: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
trait HCC: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
+struct ClientContext<'c,C> {
+ ic: &'c InstanceConfig,
+ hclient: &'c Arc<hyper::Client<C>>,
+ reporter: &'c parking_lot::Mutex<Reporter<'c>>,
+}
+
+#[derive(Debug)]
+struct TxQueued {
+ expires: Instant,
+ data: Box<[u8]>,
+}
+
#[throws(AE)]
-fn submit_request<'r, 'ic:'r, 'hc:'r, C:HCC>(
- ic: &'ic InstanceConfig,
- hclient: &'hc Arc<hyper::Client<C>>,
+fn submit_request<'r, 'c:'r, C:HCC>(
+ c: &'c ClientContext<C>,
+ req_num: &mut ReqNum,
reqs: &mut Vec<OutstandingRequest<'r>>,
- upbound: Vec<Vec<u8>>
+ upbound: FramesData,
) {
+ let show_timeout = c.ic.http_timeout
+ .saturating_add(Duration::from_nanos(999_999_999))
+ .as_secs();
+
+ let time_t = time_t_now();
+ let time_t = format!("{:x}", time_t);
+ let hmac = token_hmac(c.ic.secret.0.as_bytes(), time_t.as_bytes());
+ //dbg!(DumpHex(&hmac));
+ 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,
+ token,
+ c.ic.target_requests_outstanding,
+ show_timeout,
+ c.ic.mtu,
+ c.ic.max_batch_down,
+ c.ic.max_batch_up,
+ );
+
+ let prefix2 = format!(into_crlfs!(
+ r#"
+ --b
+ Content-Type: application/octet-stream
+ Content-Disposition: form-data; name="d"
+
+ "#),
+ );
+ let suffix = format!(into_crlfs!(
+ r#"
+ --b--
+ "#),
+ );
+
+ 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!("{} #{}: req; tx body_len={} frames={}",
+ &c.ic, req_num, body_len, upbound.len());
+
let body = hyper::body::Body::wrap_stream(
futures::stream::iter(
- Itertools::intersperse(
- upbound.into_iter().map(|u| Bytes::from(u)),
- slip::SLIP_END_SLICE.into()
- ).map(Ok::<_,Void>)
+ content!(
+ Bytes,
+ into_iter,
+ into,
+ ).map(Ok::<Bytes,Void>)
)
);
- let req = hyper::Request::post(&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 = hclient.request(req);
+ let resp = c.hclient.request(req);
let fut = Box::pin(async move {
- let r = async { tokio::time::timeout( ic.http_timeout, async {
+ let r = async { tokio::time::timeout( c.ic.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 mut resp = resp.into_body();
+ let max_body = c.ic.max_batch_down.sat() + MAX_OVERHEAD;
+ let resp = read_limited_bytes(
+ max_body, default(), default(), &mut resp
+ ).await
+ .discard_data().context("fetching response body")?;
+
+ if ! status.is_success() {
+ throw!(anyhow!("HTTP error status={} body={:?}",
+ &status, String::from_utf8_lossy(&resp)));
}
- 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")?;
+
Ok::<_,AE>(resp)
}).await? }.await;
- if r.is_err() {
- tokio::time::sleep(ic.http_retry).await;
+
+ let r = c.reporter.lock().filter(Some(req_num), r);
+
+ if let Some(r) = &r {
+ trace!("{} #{}: rok; rx bytes={}", &c.ic, req_num, r.len());
+ } else {
+ tokio::time::sleep(c.ic.http_retry).await;
}
r
});
reqs.push(fut);
}
-#[allow(unused_variables)] // xxx
async fn run_client<C:HCC>(
ic: InstanceConfig,
hclient: Arc<hyper::Client<C>>
{
debug!("{}: config: {:?}", &ic, &ic);
- let mut reporter = Reporter { };
-
- let mut ipif = tokio::process::Command::new("sh")
- .args(&["-c", &ic.ipif])
- .stdin (process::Stdio::piped())
- .stdout(process::Stdio::piped())
- .stderr(process::Stdio::piped())
- .kill_on_drop(true)
- .spawn().context("spawn ipif")?;
-
- let stderr = ipif.stderr.take().unwrap();
- let ic_name = ic.to_string();
- let _ = task::spawn(async move {
- let mut stderr = tokio::io::BufReader::new(stderr).lines();
- while let Some(l) = stderr.next_line().await? {
- error!("{}: ipif stderr: {}", &ic_name, l.trim_end());
- }
- Ok::<_,io::Error>(())
- });
+ let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
+
+ let c = ClientContext {
+ reporter: &reporter,
+ hclient: &hclient,
+ ic: &ic,
+ };
- 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 ipif = Ipif::start(&ic.ipif, Some(ic.to_string()))?;
- let stream_for_rx = ipif.stdin .take().unwrap();
+ let mut req_num: ReqNum = 0;
+
+ let mut tx_queue: VecDeque<TxQueued> = default();
+ let mut upbound = Frames::default();
let mut reqs: Vec<OutstandingRequest>
= Vec::with_capacity(ic.max_requests_outstanding.sat());
- // xxx check that ic settings are all honoured
+ let mut rx_queue: FrameQueue = default();
- async {
+ let trouble = async {
loop {
+ let rx_queue_space =
+ if rx_queue.remaining() < ic.max_batch_down.sat() {
+ Ok(())
+ } else {
+ Err(())
+ };
+
select! {
- packet = tx_stream.next_segment(),
- if tx_defer.is_none() &&
- reqs.len() < ic.max_requests_outstanding.sat() =>
+ biased;
+
+ y = ipif.rx.write_all_buf(&mut rx_queue),
+ if ! rx_queue.is_empty() =>
+ {
+ let () = y.context("write rx data to ipif")?;
+ },
+
+ () = async {
+ let expires = tx_queue.front().unwrap().expires;
+ tokio::time::sleep_until(expires).await
+ },
+ if ! tx_queue.is_empty() =>
+ {
+ let _ = tx_queue.pop_front();
+ },
+
+ data = ipif.tx.next_segment(),
+ if tx_queue.is_empty() =>
+ {
+ let data = (||{
+ data?.ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))
+ })().context("read from ipif")?;
+ //eprintln!("data={:?}", DumpHex(&data));
+
+ match check1(Slip2Mime, ic.mtu, &data, |header| {
+ let saddr = ip_packet_addr::<false>(header)?;
+ if saddr != ic.link.client.0 { throw!(PE::Src(saddr)) }
+ Ok(())
+ }) {
+ Ok((data, ())) => tx_queue.push_back(TxQueued {
+ data,
+ expires: Instant::now() + ic.max_queue_time
+ }),
+ Err(PE::Empty) => { },
+ Err(e@ PE::Src(_)) => debug!("{}: tx discarding: {}", &ic, e),
+ Err(e) => error!("{}: tx discarding: {}", &ic, e),
+ };
+ },
+
+ _ = async { },
+ if ! upbound.tried_full() &&
+ ! tx_queue.is_empty() =>
{
- let mut upbound_total = 0;
- let mut upbound: Vec<Vec<u8>> = vec![];
- 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(()) = slip::check_checkmtu_mimeify(&mut packet, &ic) {
- let new_upbound_total = packet.len() + upbound_total + 1;
- if new_upbound_total > ic.max_batch_up.sat() {
- tx_defer = Some(packet);
+ while let Some(TxQueued { data, expires }) = tx_queue.pop_front() {
+ match upbound.add(ic.max_batch_up, data.into()/*todo:504*/) {
+ Err(data) => {
+ tx_queue.push_front(TxQueued { data: data.into(), expires });
break;
}
- upbound_total = new_upbound_total;
- upbound.push(packet);
- // 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,
- };
+ Ok(()) => { },
}
}
- assert!( to_process.is_none() );
- dbg!(&reqs.len(), &upbound_total, &upbound.len());
+ },
- //: impl futures::Stream<Cow<&[u8]>>
- submit_request(&ic, &hclient, &mut reqs, upbound)?;
- }
+ _ = async { },
+ if rx_queue_space.is_ok() &&
+ (reqs.len() < ic.target_requests_outstanding.sat() ||
+ (reqs.len() < ic.max_requests_outstanding.sat() &&
+ ! upbound.is_empty()))
+ =>
+ {
+ 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) = reporter.report(got) {
- dbg!(&got.remaining()); // xxx
+
+ if let Some(got) = got {
+
+ //eprintln!("got={:?}", DumpHex(&got));
+ match checkn(SlipNoConv,ic.mtu, &got, |header| {
+ let addr = ip_packet_addr::<true>(header)?;
+ if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
+ Ok(())
+ },
+ |(o,())| Ok({ rx_queue.push(o); }),
+ |e| Ok::<_,SlipFramesError<Void>>( {
+ error!("{} #{}: rx discarding: {}", &ic, req_num, e);
+ }))
+ {
+ Ok(()) => reporter.lock().success(),
+ Err(SlipFramesError::ErrorOnlyBad) => {
+ reqs.push(Box::pin(async {
+ tokio::time::sleep(ic.http_retry).await;
+ None
+ }));
+ },
+ Err(SlipFramesError::Other(v)) => unreachable!(v),
+ }
}
- }
+ },
+
+ _ = tokio::time::sleep(c.ic.effective_http_timeout),
+ if rx_queue_space.is_err() =>
+ {
+ reporter.lock().filter(None, Err::<Void,_>(
+ anyhow!("rx queue full, blocked")
+ ));
+ },
}
}
- }.await
+ }.await;
+
+ ipif.quitting(Some(&ic)).await;
+ trouble
}
#[tokio::main]
-async fn main() -> Result<(), AE> {
- let ics = config::read(LinkEnd::Client)?;
- if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
-
- env_logger::init();
+async fn main() {
+ let opts = Opts::from_args();
+ let (ics,) = config::startup("hippotat", LinkEnd::Client,
+ &opts.config, &opts.log, |ics|Ok((ics,)));
let https = HttpsConnector::new();
- let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
+ let hclient = hyper::Client::builder()
+ .http1_preserve_header_case(true)
+ .build::<_, hyper::Body>(https);
let hclient = Arc::new(hclient);
info!("starting");
});
match join.await {
Ok(e) => {
- error!("{} failed: {:?}", &assocname, e);
+ error!("{} failed: {}", &assocname, e);
},
Err(je) => {
error!("{} panicked!", &assocname);