1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 // There is NO WARRANTY.
5 use hippotat::prelude::*;
6 use hippotat_macros::into_crlfs;
8 const MAX_BATCH_DOWN_RESP_OVERHEAD: usize = 10_000;
10 #[derive(StructOpt,Debug)]
12 /// Increase debug level
13 #[structopt(long, short="D", parse(from_occurrences))]
20 type OutstandingRequest<'r> = Pin<Box<
21 dyn Future<Output=Option<Box<[u8]>>> + Send + 'r
24 impl<T> HCC for T where
25 T: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
26 trait HCC: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
28 struct ClientContext<'c,C> {
29 ic: &'c InstanceConfig,
30 effective_http_timeout: Duration,
31 hclient: &'c Arc<hyper::Client<C>>,
32 reporter: &'c parking_lot::Mutex<Reporter<'c>>,
36 fn submit_request<'r, 'c:'r, C:HCC>(
37 c: &'c ClientContext<C>,
39 reqs: &mut Vec<OutstandingRequest<'r>>,
42 let show_timeout = c.ic.http_timeout
43 .saturating_add(Duration::from_nanos(999_999_999))
46 let time_t = SystemTime::now()
47 .duration_since(UNIX_EPOCH)
48 .unwrap_or_else(|_| Duration::default()) // clock is being weird
50 let time_t = format!("{:x}", time_t);
51 let hmac = token_hmac(c.ic.secret.0.as_bytes(), time_t.as_bytes());
52 let mut token = time_t;
53 write!(token, " ").unwrap();
54 base64::encode_config_buf(&hmac, BASE64_CONFIG, &mut token);
56 let req_num = { *req_num += 1; *req_num };
58 let prefix1 = format!(into_crlfs!(
60 Content-Type: text/plain; charset="utf-8"
61 Content-Disposition: form-data; name="m"
70 c.ic.target_requests_outstanding,
75 let prefix2 = format!(into_crlfs!(
78 Content-Type: application/octet-stream
79 Content-Disposition: form-data; name="d"
83 let suffix = format!(into_crlfs!(
89 macro_rules! content { {
95 array::IntoIter::new([
99 if upbound.is_empty() { 1 } else { 2 }
101 Itertools::intersperse(
102 upbound.$iter().map(|u| { let out: $out = u.$into(); out }),
103 SLIP_END_SLICE.$into()
109 let body_len: usize = content!(
113 ).map(|b| b.len()).sum();
115 trace!("{} #{}: req; tx bytes={} frames={}",
116 &c.ic, req_num, body_len, upbound.len());
118 let body = hyper::body::Body::wrap_stream(
119 futures::stream::iter(
124 ).map(Ok::<Bytes,Void>)
128 let req = hyper::Request::post(&c.ic.url)
129 .header("Content-Type", r#"multipart/form-data; boundary="b""#)
130 .header("Content-Length", body_len)
132 .context("construct request")?;
134 let resp = c.hclient.request(req);
135 let fut = Box::pin(async move {
136 let r = async { tokio::time::timeout( c.effective_http_timeout, async {
137 let resp = resp.await.context("make request")?;
138 let status = resp.status();
139 let resp = resp.into_body();
140 let max_body = c.ic.max_batch_down.sat() + MAX_BATCH_DOWN_RESP_OVERHEAD;
141 let resp = read_limited_body(max_body, resp).await?;
143 if ! status.is_success() {
144 throw!(anyhow!("HTTP error status={} body={:?}",
145 &status, String::from_utf8_lossy(&resp)));
151 let r = c.reporter.lock().filter(Some(req_num), r);
153 if let Some(r) = &r {
154 trace!("{} #{}: rok; rx bytes={}", &c.ic, req_num, r.len());
156 tokio::time::sleep(c.ic.http_retry).await;
163 async fn run_client<C:HCC>(
165 hclient: Arc<hyper::Client<C>>
166 ) -> Result<Void, AE>
168 debug!("{}: config: {:?}", &ic, &ic);
170 let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
172 let c = ClientContext {
176 effective_http_timeout: ic.http_timeout.checked_add(ic.http_timeout_grace)
177 .ok_or_else(|| anyhow!("calculate effective http timeout ({:?} + {:?})",
178 ic.http_timeout, ic.http_timeout_grace))?,
181 let mut ipif = tokio::process::Command::new("sh")
182 .args(&["-c", &ic.ipif])
183 .stdin (process::Stdio::piped())
184 .stdout(process::Stdio::piped())
185 .stderr(process::Stdio::piped())
187 .spawn().context("spawn ipif")?;
189 let stderr = ipif.stderr.take().unwrap();
190 let ic_name = ic.to_string();
191 let _ = task::spawn(async move {
192 let mut stderr = tokio::io::BufReader::new(stderr).lines();
193 while let Some(l) = stderr.next_line().await? {
194 error!("{}: ipif stderr: {}", &ic_name, l.trim_end());
196 Ok::<_,io::Error>(())
199 let mut req_num: ReqNum = 0;
201 let tx_stream = ipif.stdout.take().unwrap();
202 let mut rx_stream = ipif.stdin .take().unwrap();
204 let mut tx_stream = tokio::io::BufReader::new(tx_stream).split(SLIP_END);
205 let mut packets: VecDeque<Box<[u8]>> = default();
206 let mut upbound = Frames::default();
208 let mut reqs: Vec<OutstandingRequest>
209 = Vec::with_capacity(ic.max_requests_outstanding.sat());
211 let mut rx_queue: FrameQueue = default();
213 // xxx check that ic settings are all honoured
218 y = rx_stream.write_all_buf(&mut rx_queue),
219 if ! rx_queue.is_empty() =>
221 let () = y.context("write rx data to ipif")?;
224 data = tx_stream.next_segment(),
225 if packets.is_empty() =>
228 data.context("read from ipif")?
229 .ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
230 //eprintln!("data={:?}", DumpHex(&data));
232 match check1(Slip2Mime, ic.mtu, &data, |header| {
233 let addr = ip_packet_addr::<false>(header)?;
234 if addr != ic.link.client.0 { throw!(PE::Src(addr)) }
237 Ok(packet) => packets.push_back(packet),
238 Err(PE::Empty) => { },
239 Err(e@ PE::Src(_)) => debug!("{}: tx discarding: {}", &ic, e),
240 Err(e) => error!("{}: tx discarding: {}", &ic, e),
245 if ! upbound.tried_full() &&
246 ! packets.is_empty() =>
248 while let Some(packet) = packets.pop_front() {
249 match upbound.add(ic.max_batch_up, packet.into()/*xxx*/) {
250 Err(packet) => { packets.push_front(packet.into()/*xxx*/); break; }
257 if reporter.lock().filter(None, {
258 if rx_queue.remaining() < ic.max_batch_down.sat() * 3 /* xxx */ {
259 // xxx make this separate option ? docs say server only
262 Err(anyhow!("rx queue full"))
265 (reqs.len() < ic.target_requests_outstanding.sat() ||
266 (reqs.len() < ic.max_requests_outstanding.sat() &&
267 ! upbound.is_empty()))
270 submit_request(&c, &mut req_num, &mut reqs,
271 mem::take(&mut upbound).into())?;
274 (got, goti, _) = async { future::select_all(&mut reqs).await },
275 if ! reqs.is_empty() =>
277 reqs.swap_remove(goti);
279 if let Some(got) = got {
280 reporter.lock().success();
281 //eprintln!("got={:?}", DumpHex(&got));
282 checkn(SlipNoConv,ic.mtu, &got, &mut rx_queue, |header| {
283 let addr = ip_packet_addr::<true>(header)?;
284 if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
286 }, |e| error!("{} #{}: rx discarding: {}", &ic, req_num, e));
296 async fn main() -> Result<(), AE> {
297 let opts = Opts::from_args();
299 let ics = config::read(&opts.config, LinkEnd::Client)?;
300 if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
303 let env = env_logger::Env::new()
304 .filter("HIPPOTAT_LOG")
305 .write_style("HIPPOTAT_LOG_STYLE");
307 let mut logb = env_logger::Builder::new();
308 logb.filter(Some("hippotat"),
309 *[ log::LevelFilter::Info,
310 log::LevelFilter::Debug ]
313 &log::LevelFilter::Trace
319 let https = HttpsConnector::new();
320 let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
321 let hclient = Arc::new(hclient);
324 let () = future::select_all(
325 ics.into_iter().map(|ic| Box::pin(async {
326 let assocname = ic.to_string();
327 info!("{} starting", &assocname);
328 let hclient = hclient.clone();
329 let join = task::spawn(async {
330 run_client(ic, hclient).await.void_unwrap_err()
334 error!("{} failed: {:?}", &assocname, e);
337 error!("{} panicked!", &assocname);
338 panic::resume_unwind(je.into_panic());
344 error!("quitting because one of your client connections crashed");