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 = time_t_now();
49 let time_t = format!("{:x}", time_t);
50 let hmac = token_hmac(c.ic.secret.0.as_bytes(), time_t.as_bytes());
51 let mut token = time_t;
52 write!(token, " ").unwrap();
53 base64::encode_config_buf(&hmac, BASE64_CONFIG, &mut token);
55 let req_num = { *req_num += 1; *req_num };
57 let prefix1 = format!(into_crlfs!(
59 Content-Type: text/plain; charset="utf-8"
60 Content-Disposition: form-data; name="m"
70 c.ic.target_requests_outstanding,
76 let prefix2 = format!(into_crlfs!(
79 Content-Type: application/octet-stream
80 Content-Disposition: form-data; name="d"
84 let suffix = format!(into_crlfs!(
90 macro_rules! content { {
96 array::IntoIter::new([
100 if upbound.is_empty() { 1 } else { 2 }
102 Itertools::intersperse(
103 upbound.$iter().map(|u| { let out: $out = u.$into(); out }),
104 SLIP_END_SLICE.$into()
110 let body_len: usize = content!(
114 ).map(|b| b.len()).sum();
116 trace!("{} #{}: req; tx body_len={} frames={}",
117 &c.ic, req_num, body_len, upbound.len());
119 let body = hyper::body::Body::wrap_stream(
120 futures::stream::iter(
125 ).map(Ok::<Bytes,Void>)
129 let req = hyper::Request::post(&c.ic.url)
130 .header("Content-Type", r#"multipart/form-data; boundary="b""#)
131 .header("Content-Length", body_len)
133 .context("construct request")?;
135 let resp = c.hclient.request(req);
136 let fut = Box::pin(async move {
137 let r = async { tokio::time::timeout( c.ic.effective_http_timeout, async {
138 let resp = resp.await.context("make request")?;
139 let status = resp.status();
140 let mut resp = resp.into_body();
141 let max_body = c.ic.max_batch_down.sat() + MAX_OVERHEAD;
142 let resp = read_limited_bytes(max_body, &mut resp).await
143 .discard_data().context("fetching response body")?;
145 if ! status.is_success() {
146 throw!(anyhow!("HTTP error status={} body={:?}",
147 &status, String::from_utf8_lossy(&resp)));
153 let r = c.reporter.lock().filter(Some(req_num), r);
155 if let Some(r) = &r {
156 trace!("{} #{}: rok; rx bytes={}", &c.ic, req_num, r.len());
158 tokio::time::sleep(c.ic.http_retry).await;
165 async fn run_client<C:HCC>(
167 hclient: Arc<hyper::Client<C>>
168 ) -> Result<Void, AE>
170 debug!("{}: config: {:?}", &ic, &ic);
172 let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
174 let c = ClientContext {
180 let mut ipif = Ipif::start(&ic.ipif, Some(ic.to_string()))?;
182 let mut req_num: ReqNum = 0;
184 let mut tx_queue: VecDeque<TxQueued> = default();
185 let mut upbound = Frames::default();
187 let mut reqs: Vec<OutstandingRequest>
188 = Vec::with_capacity(ic.max_requests_outstanding.sat());
190 let mut rx_queue: FrameQueue = default();
192 let trouble = async {
195 if rx_queue.remaining() < ic.max_batch_down.sat() {
204 y = ipif.rx.write_all_buf(&mut rx_queue),
205 if ! rx_queue.is_empty() =>
207 let () = y.context("write rx data to ipif")?;
211 let expires = tx_queue.front().unwrap().expires;
212 tokio::time::sleep_until(expires).await
214 if ! tx_queue.is_empty() =>
216 let _ = tx_queue.pop_front();
219 data = ipif.tx.next_segment(),
220 if tx_queue.is_empty() =>
223 data?.ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))
224 })().context("read from ipif")?;
225 //eprintln!("data={:?}", DumpHex(&data));
227 match check1(Slip2Mime, ic.mtu, &data, |header| {
228 let addr = ip_packet_addr::<false>(header)?;
229 if addr != ic.link.client.0 { throw!(PE::Src(addr)) }
232 Ok(data) => tx_queue.push_back(TxQueued {
234 expires: Instant::now() + ic.max_queue_time
236 Err(PE::Empty) => { },
237 Err(e@ PE::Src(_)) => debug!("{}: tx discarding: {}", &ic, e),
238 Err(e) => error!("{}: tx discarding: {}", &ic, e),
243 if ! upbound.tried_full() &&
244 ! tx_queue.is_empty() =>
246 while let Some(TxQueued { data, expires }) = tx_queue.pop_front() {
247 match upbound.add(ic.max_batch_up, data.into()/*todo:504*/) {
249 tx_queue.push_front(TxQueued { data: data.into(), expires });
258 if rx_queue_space.is_ok() &&
259 (reqs.len() < ic.target_requests_outstanding.sat() ||
260 (reqs.len() < ic.max_requests_outstanding.sat() &&
261 ! upbound.is_empty()))
264 submit_request(&c, &mut req_num, &mut reqs,
265 mem::take(&mut upbound).into())?;
268 (got, goti, _) = async { future::select_all(&mut reqs).await },
269 if ! reqs.is_empty() =>
271 reqs.swap_remove(goti);
273 if let Some(got) = got {
275 //eprintln!("got={:?}", DumpHex(&got));
276 match checkn(SlipNoConv,ic.mtu, &got, &mut rx_queue, |header| {
277 let addr = ip_packet_addr::<true>(header)?;
278 if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
280 }, |e| error!("{} #{}: rx discarding: {}", &ic, req_num, e)) {
281 Ok(()) => reporter.lock().success(),
282 Err(ErrorOnlyBad) => {
283 reqs.push(Box::pin(async {
284 tokio::time::sleep(ic.http_retry).await;
292 _ = tokio::time::sleep(c.ic.effective_http_timeout),
293 if rx_queue_space.is_err() =>
295 reporter.lock().filter(None, Err::<Void,_>(
296 anyhow!("rx queue full, blocked")
303 ipif.quitting(Some(&ic)).await;
309 let opts = Opts::from_args();
310 let (ics,) = config::startup("hippotat", LinkEnd::Client,
311 &opts.config, &opts.log, |ics|Ok((ics,)));
313 let https = HttpsConnector::new();
314 let hclient = hyper::Client::builder()
315 .http1_preserve_header_case(true)
316 .build::<_, hyper::Body>(https);
317 let hclient = Arc::new(hclient);
320 let () = future::select_all(
321 ics.into_iter().map(|ic| Box::pin(async {
322 let assocname = ic.to_string();
323 info!("{} starting", &assocname);
324 let hclient = hclient.clone();
325 let join = task::spawn(async {
326 run_client(ic, hclient).await.void_unwrap_err()
330 error!("{} failed: {}", &assocname, e);
333 error!("{} panicked!", &assocname);
334 panic::resume_unwind(je.into_panic());
340 error!("quitting because one of your client connections crashed");