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)]
19 type OutstandingRequest<'r> = Pin<Box<
20 dyn Future<Output=Option<Box<[u8]>>> + Send + 'r
23 impl<T> HCC for T where
24 T: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
25 trait HCC: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
27 struct ClientContext<'c,C> {
28 ic: &'c InstanceConfig,
29 hclient: &'c Arc<hyper::Client<C>>,
30 reporter: &'c parking_lot::Mutex<Reporter<'c>>,
40 fn submit_request<'r, 'c:'r, C:HCC>(
41 c: &'c ClientContext<C>,
43 reqs: &mut Vec<OutstandingRequest<'r>>,
46 let show_timeout = c.ic.http_timeout
47 .saturating_add(Duration::from_nanos(999_999_999))
50 let time_t = SystemTime::now()
51 .duration_since(UNIX_EPOCH)
52 .unwrap_or_else(|_| Duration::default()) // clock is being weird
54 let time_t = format!("{:x}", time_t);
55 let hmac = token_hmac(c.ic.secret.0.as_bytes(), time_t.as_bytes());
56 let mut token = time_t;
57 write!(token, " ").unwrap();
58 base64::encode_config_buf(&hmac, BASE64_CONFIG, &mut token);
60 let req_num = { *req_num += 1; *req_num };
62 let prefix1 = format!(into_crlfs!(
64 Content-Type: text/plain; charset="utf-8"
65 Content-Disposition: form-data; name="m"
74 c.ic.target_requests_outstanding,
79 let prefix2 = format!(into_crlfs!(
82 Content-Type: application/octet-stream
83 Content-Disposition: form-data; name="d"
87 let suffix = format!(into_crlfs!(
93 macro_rules! content { {
99 array::IntoIter::new([
103 if upbound.is_empty() { 1 } else { 2 }
105 Itertools::intersperse(
106 upbound.$iter().map(|u| { let out: $out = u.$into(); out }),
107 SLIP_END_SLICE.$into()
113 let body_len: usize = content!(
117 ).map(|b| b.len()).sum();
119 trace!("{} #{}: req; tx bytes={} frames={}",
120 &c.ic, req_num, body_len, upbound.len());
122 let body = hyper::body::Body::wrap_stream(
123 futures::stream::iter(
128 ).map(Ok::<Bytes,Void>)
132 let req = hyper::Request::post(&c.ic.url)
133 .header("Content-Type", r#"multipart/form-data; boundary="b""#)
134 .header("Content-Length", body_len)
136 .context("construct request")?;
138 let resp = c.hclient.request(req);
139 let fut = Box::pin(async move {
140 let r = async { tokio::time::timeout( c.ic.effective_http_timeout, async {
141 let resp = resp.await.context("make request")?;
142 let status = resp.status();
143 let resp = resp.into_body();
144 let max_body = c.ic.max_batch_down.sat() + MAX_BATCH_DOWN_RESP_OVERHEAD;
145 let resp = read_limited_body(max_body, resp).await?;
147 if ! status.is_success() {
148 throw!(anyhow!("HTTP error status={} body={:?}",
149 &status, String::from_utf8_lossy(&resp)));
155 let r = c.reporter.lock().filter(Some(req_num), r);
157 if let Some(r) = &r {
158 trace!("{} #{}: rok; rx bytes={}", &c.ic, req_num, r.len());
160 tokio::time::sleep(c.ic.http_retry).await;
167 async fn run_client<C:HCC>(
169 hclient: Arc<hyper::Client<C>>
170 ) -> Result<Void, AE>
172 debug!("{}: config: {:?}", &ic, &ic);
174 let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
176 let c = ClientContext {
182 let mut ipif = Ipif::start(&ic.ipif, ic.to_string())?;
184 let mut req_num: ReqNum = 0;
186 let mut tx_queue: VecDeque<TxQueued> = default();
187 let mut upbound = Frames::default();
189 let mut reqs: Vec<OutstandingRequest>
190 = Vec::with_capacity(ic.max_requests_outstanding.sat());
192 let mut rx_queue: FrameQueue = default();
194 let trouble = async {
197 if rx_queue.remaining() < ic.max_batch_down.sat() {
206 y = ipif.rx_stream.write_all_buf(&mut rx_queue),
207 if ! rx_queue.is_empty() =>
209 let () = y.context("write rx data to ipif")?;
213 let expires = tx_queue.front().unwrap().expires;
214 tokio::time::sleep_until(expires).await
216 if ! tx_queue.is_empty() =>
218 let _ = tx_queue.pop_front();
221 data = ipif.tx_stream.next_segment(),
222 if tx_queue.is_empty() =>
225 data?.ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))
226 })().context("read from ipif")?;
227 //eprintln!("data={:?}", DumpHex(&data));
229 match check1(Slip2Mime, ic.mtu, &data, |header| {
230 let addr = ip_packet_addr::<false>(header)?;
231 if addr != ic.link.client.0 { throw!(PE::Src(addr)) }
234 Ok(data) => tx_queue.push_back(TxQueued {
236 expires: Instant::now() + ic.max_queue_time
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 ! tx_queue.is_empty() =>
248 while let Some(TxQueued { data, expires }) = tx_queue.pop_front() {
249 match upbound.add(ic.max_batch_up, data.into()/*todo:504*/) {
250 Err(data) => { tx_queue.push_front(TxQueued { data: data.into(), expires }); break; }
257 if rx_queue_space.is_ok() &&
258 (reqs.len() < ic.target_requests_outstanding.sat() ||
259 (reqs.len() < ic.max_requests_outstanding.sat() &&
260 ! upbound.is_empty()))
263 submit_request(&c, &mut req_num, &mut reqs,
264 mem::take(&mut upbound).into())?;
267 (got, goti, _) = async { future::select_all(&mut reqs).await },
268 if ! reqs.is_empty() =>
270 reqs.swap_remove(goti);
272 if let Some(got) = got {
273 reporter.lock().success();
274 //eprintln!("got={:?}", DumpHex(&got));
275 checkn(SlipNoConv,ic.mtu, &got, &mut rx_queue, |header| {
276 let addr = ip_packet_addr::<true>(header)?;
277 if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
279 }, |e| error!("{} #{}: rx discarding: {}", &ic, req_num, e));
284 _ = tokio::time::sleep(c.ic.effective_http_timeout),
285 if rx_queue_space.is_err() =>
287 reporter.lock().filter(None, Err::<Void,_>(
288 anyhow!("rx queue full, blocked")
295 ipif.quitting(&ic).await;
301 let opts = Opts::from_args();
302 let (ics,) = config::startup("hippotat", LinkEnd::Client,
303 &opts.config, &opts.log);
305 let https = HttpsConnector::new();
306 let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
307 let hclient = Arc::new(hclient);
310 let () = future::select_all(
311 ics.into_iter().map(|ic| Box::pin(async {
312 let assocname = ic.to_string();
313 info!("{} starting", &assocname);
314 let hclient = hclient.clone();
315 let join = task::spawn(async {
316 run_client(ic, hclient).await.void_unwrap_err()
320 error!("{} failed: {:?}", &assocname, e);
323 error!("{} panicked!", &assocname);
324 panic::resume_unwind(je.into_panic());
330 error!("quitting because one of your client connections crashed");