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 #[derive(StructOpt,Debug)]
17 type OutstandingRequest<'r> = Pin<Box<
18 dyn Future<Output=Option<Box<[u8]>>> + Send + 'r
21 impl<T> HCC for T where
22 T: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
23 trait HCC: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
25 struct ClientContext<'c,C> {
26 ic: &'c InstanceConfig,
27 hclient: &'c Arc<hyper::Client<C>>,
28 reporter: &'c parking_lot::Mutex<Reporter<'c>>,
38 fn submit_request<'r, 'c:'r, C:HCC>(
39 c: &'c ClientContext<C>,
41 reqs: &mut Vec<OutstandingRequest<'r>>,
44 let show_timeout = c.ic.http_timeout
45 .saturating_add(Duration::from_nanos(999_999_999))
48 let time_t = SystemTime::now()
49 .duration_since(UNIX_EPOCH)
50 .unwrap_or_else(|_| Duration::default()) // clock is being weird
52 let time_t = format!("{:x}", time_t);
53 let hmac = token_hmac(c.ic.secret.0.as_bytes(), time_t.as_bytes());
54 let mut token = time_t;
55 write!(token, " ").unwrap();
56 base64::encode_config_buf(&hmac, BASE64_CONFIG, &mut token);
58 let req_num = { *req_num += 1; *req_num };
60 let prefix1 = format!(into_crlfs!(
62 Content-Type: text/plain; charset="utf-8"
63 Content-Disposition: form-data; name="m"
73 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 body_len={} 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 mut resp = resp.into_body();
144 let max_body = c.ic.max_batch_down.sat() + MAX_OVERHEAD;
145 let resp = read_limited_bytes(max_body, &mut resp).await
146 .discard_data().context("fetching response body")?;
148 if ! status.is_success() {
149 throw!(anyhow!("HTTP error status={} body={:?}",
150 &status, String::from_utf8_lossy(&resp)));
156 let r = c.reporter.lock().filter(Some(req_num), r);
158 if let Some(r) = &r {
159 trace!("{} #{}: rok; rx bytes={}", &c.ic, req_num, r.len());
161 tokio::time::sleep(c.ic.http_retry).await;
168 async fn run_client<C:HCC>(
170 hclient: Arc<hyper::Client<C>>
171 ) -> Result<Void, AE>
173 debug!("{}: config: {:?}", &ic, &ic);
175 let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
177 let c = ClientContext {
183 let mut ipif = Ipif::start(&ic.ipif, Some(ic.to_string()))?;
185 let mut req_num: ReqNum = 0;
187 let mut tx_queue: VecDeque<TxQueued> = default();
188 let mut upbound = Frames::default();
190 let mut reqs: Vec<OutstandingRequest>
191 = Vec::with_capacity(ic.max_requests_outstanding.sat());
193 let mut rx_queue: FrameQueue = default();
195 let trouble = async {
198 if rx_queue.remaining() < ic.max_batch_down.sat() {
207 y = ipif.rx.write_all_buf(&mut rx_queue),
208 if ! rx_queue.is_empty() =>
210 let () = y.context("write rx data to ipif")?;
214 let expires = tx_queue.front().unwrap().expires;
215 tokio::time::sleep_until(expires).await
217 if ! tx_queue.is_empty() =>
219 let _ = tx_queue.pop_front();
222 data = ipif.tx.next_segment(),
223 if tx_queue.is_empty() =>
226 data?.ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))
227 })().context("read from ipif")?;
228 //eprintln!("data={:?}", DumpHex(&data));
230 match check1(Slip2Mime, ic.mtu, &data, |header| {
231 let addr = ip_packet_addr::<false>(header)?;
232 if addr != ic.link.client.0 { throw!(PE::Src(addr)) }
235 Ok(data) => tx_queue.push_back(TxQueued {
237 expires: Instant::now() + ic.max_queue_time
239 Err(PE::Empty) => { },
240 Err(e@ PE::Src(_)) => debug!("{}: tx discarding: {}", &ic, e),
241 Err(e) => error!("{}: tx discarding: {}", &ic, e),
246 if ! upbound.tried_full() &&
247 ! tx_queue.is_empty() =>
249 while let Some(TxQueued { data, expires }) = tx_queue.pop_front() {
250 match upbound.add(ic.max_batch_up, data.into()/*todo:504*/) {
252 tx_queue.push_front(TxQueued { data: data.into(), expires });
261 if rx_queue_space.is_ok() &&
262 (reqs.len() < ic.target_requests_outstanding.sat() ||
263 (reqs.len() < ic.max_requests_outstanding.sat() &&
264 ! upbound.is_empty()))
267 submit_request(&c, &mut req_num, &mut reqs,
268 mem::take(&mut upbound).into())?;
271 (got, goti, _) = async { future::select_all(&mut reqs).await },
272 if ! reqs.is_empty() =>
274 reqs.swap_remove(goti);
276 if let Some(got) = got {
278 //eprintln!("got={:?}", DumpHex(&got));
279 match checkn(SlipNoConv,ic.mtu, &got, &mut rx_queue, |header| {
280 let addr = ip_packet_addr::<true>(header)?;
281 if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
283 }, |e| error!("{} #{}: rx discarding: {}", &ic, req_num, e)) {
284 Ok(()) => reporter.lock().success(),
285 Err(ErrorOnlyBad) => {
286 reqs.push(Box::pin(async {
287 tokio::time::sleep(ic.http_retry).await;
295 _ = tokio::time::sleep(c.ic.effective_http_timeout),
296 if rx_queue_space.is_err() =>
298 reporter.lock().filter(None, Err::<Void,_>(
299 anyhow!("rx queue full, blocked")
306 ipif.quitting(Some(&ic)).await;
312 let opts = Opts::from_args();
313 let (ics,) = config::startup("hippotat", LinkEnd::Client,
314 &opts.config, &opts.log, |ics|Ok((ics,)));
316 let https = HttpsConnector::new();
317 let hclient = hyper::Client::builder()
318 .http1_preserve_header_case(true)
319 .build::<_, hyper::Body>(https);
320 let hclient = Arc::new(hclient);
323 let () = future::select_all(
324 ics.into_iter().map(|ic| Box::pin(async {
325 let assocname = ic.to_string();
326 info!("{} starting", &assocname);
327 let hclient = hclient.clone();
328 let join = task::spawn(async {
329 run_client(ic, hclient).await.void_unwrap_err()
333 error!("{} failed: {}", &assocname, e);
336 error!("{} panicked!", &assocname);
337 panic::resume_unwind(je.into_panic());
343 error!("quitting because one of your client connections crashed");