1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: AGPL-3.0-or-later
3 // There is NO WARRANTY.
5 use hippotat::prelude::*;
6 use hippotat_macros::into_crlfs;
8 type OutstandingRequest<'r> = Pin<Box<
9 dyn Future<Output=Option<Bytes>> + Send + 'r
12 impl<T> HCC for T where
13 T: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
14 trait HCC: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
16 struct ClientContext<'c,C> {
17 ic: &'c InstanceConfig,
18 hclient: &'c Arc<hyper::Client<C>>,
19 reporter: &'c parking_lot::Mutex<Reporter<'c>>,
23 fn submit_request<'r, 'c:'r, C:HCC>(
24 c: &'c ClientContext<C>,
25 reqs: &mut Vec<OutstandingRequest<'r>>,
28 let show_timeout = c.ic.http_timeout
29 .saturating_add(Duration::from_nanos(999_999_999))
32 let time_t = SystemTime::now()
33 .duration_since(UNIX_EPOCH)
34 .unwrap_or_else(|_| Duration::default()) // clock is being weird
36 let time_t = format!("{:x}", time_t);
37 let hmac = token_hmac(c.ic.secret.0.as_bytes(), time_t.as_bytes());
38 let mut token = time_t;
39 write!(token, " ").unwrap();
40 base64::encode_config_buf(&hmac, BASE64_CONFIG, &mut token);
42 let prefix1 = format!(into_crlfs!(
44 Content-Type: text/plain; charset="utf-8"
45 Content-Disposition: form-data; name="m"
53 c.ic.target_requests_outstanding,
57 let prefix2 = format!(into_crlfs!(
60 Content-Type: application/octet-stream
61 Content-Disposition: form-data; name="d"
65 let suffix = format!(into_crlfs!(
71 macro_rules! content { {
77 array::IntoIter::new([
81 if upbound.is_empty() { 1 } else { 2 }
83 Itertools::intersperse(
84 upbound.$iter().map(|u| { let out: $out = u.$into(); out }),
85 SLIP_END_SLICE.$into()
91 let body_len: usize = content!(
95 ).map(|b| b.len()).sum();
97 let body = hyper::body::Body::wrap_stream(
98 futures::stream::iter(
103 ).map(Ok::<Bytes,Void>)
107 let req = hyper::Request::post(&c.ic.url)
108 .header("Content-Type", r#"multipart/form-data; boundary="b""#)
109 .header("Content-Length", body_len)
111 .context("construct request")?;
113 let resp = c.hclient.request(req);
114 let fut = Box::pin(async move {
115 let r = async { tokio::time::timeout( c.ic.http_timeout, async {
116 let resp = resp.await.context("make request")?;
117 let status = resp.status();
118 let resp = resp.into_body();
119 // xxx: some size limit to avoid mallocing the universe
120 let resp = hyper::body::to_bytes(resp).await
121 .context("HTTP error fetching response body")?;
123 if ! status.is_success() {
124 // xxx get body and log it
125 throw!(anyhow!("HTTP error status={} body={:?}",
126 &status, String::from_utf8_lossy(&resp)));
132 let r = c.reporter.lock().report(r);
135 tokio::time::sleep(c.ic.http_retry).await;
142 #[allow(unused_variables)] // xxx
143 #[allow(unused_mut)] // xxx
144 #[allow(dead_code)] // xxx
145 async fn run_client<C:HCC>(
147 hclient: Arc<hyper::Client<C>>
148 ) -> Result<Void, AE>
150 debug!("{}: config: {:?}", &ic, &ic);
152 let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
154 let c = ClientContext {
160 let mut ipif = tokio::process::Command::new("sh")
161 .args(&["-c", &ic.ipif])
162 .stdin (process::Stdio::piped())
163 .stdout(process::Stdio::piped())
164 .stderr(process::Stdio::piped())
166 .spawn().context("spawn ipif")?;
168 let stderr = ipif.stderr.take().unwrap();
169 let ic_name = ic.to_string();
170 let _ = task::spawn(async move {
171 let mut stderr = tokio::io::BufReader::new(stderr).lines();
172 while let Some(l) = stderr.next_line().await? {
173 error!("{}: ipif stderr: {}", &ic_name, l.trim_end());
175 Ok::<_,io::Error>(())
178 let tx_stream = ipif.stdout.take().unwrap();
179 let rx_stream = ipif.stdin .take().unwrap();
181 let mut tx_stream = tokio::io::BufReader::new(tx_stream).split(SLIP_END);
182 let mut packets: VecDeque<Box<[u8]>> = default();
183 let mut upbound = Frames::default();
185 let mut reqs: Vec<OutstandingRequest>
186 = Vec::with_capacity(ic.max_requests_outstanding.sat());
188 let mut rx_queue: VecDeque<Box<[u8]>> = default();
191 Frame(Cursor<Box<u8>>),
194 let mut rx_current: Option<RxState> = None;
196 // xxx check that ic settings are all honoured
201 data = tx_stream.next_segment(),
202 if packets.is_empty() =>
205 data.context("read from ipif")?
206 .ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
207 //eprintln!("data={:?}", DumpHex(&data));
210 ::<_,_,_,Slip2Mime>(ic.mtu, &data, &mut packets, |header| {
211 let addr = ip_packet_addr::<false>(header)?;
212 if addr != ic.link.client.0 { throw!(PE::Src(addr)) }
216 e@ PE::Src(_) => debug!("{}: tx: discarding: {}", &ic, e),
217 e => error!("{}: tx: discarding: {}", &ic, e),
222 if ! upbound.tried_full() &&
223 ! packets.is_empty() =>
225 while let Some(packet) = packets.pop_front() {
226 match upbound.add(ic.max_batch_up, packet.into()/*xxx*/) {
227 Err(packet) => { packets.push_front(packet.into()/*xxx*/); break; }
234 if reqs.len() < ic.target_requests_outstanding.sat() ||
235 (reqs.len() < ic.max_requests_outstanding.sat() &&
236 ! upbound.is_empty())
237 // xxx backpressure, if too much in rx_queue
240 submit_request(&c, &mut reqs, mem::take(&mut upbound).into())?;
243 (got, goti, _) = async { future::select_all(&mut reqs).await },
244 if ! reqs.is_empty() =>
246 reqs.swap_remove(goti);
248 if let Some(got) = got {
249 //eprintln!("got={:?}", DumpHex(&got));
251 ::<_,_,_,SlipNoConv>(ic.mtu, &got, &mut rx_queue, |header| {
252 let addr = ip_packet_addr::<true>(header)?;
253 if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
255 }, |e| error!("{}: rx: discarding: {}", &ic, e));
257 dbg!(&rx_queue.len());
258 rx_queue = default(); // xxx
267 async fn main() -> Result<(), AE> {
268 let ics = config::read(LinkEnd::Client)?;
269 if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
273 let https = HttpsConnector::new();
274 let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
275 let hclient = Arc::new(hclient);
278 let () = future::select_all(
279 ics.into_iter().map(|ic| Box::pin(async {
280 let assocname = ic.to_string();
281 info!("{} starting", &assocname);
282 let hclient = hclient.clone();
283 let join = task::spawn(async {
284 run_client(ic, hclient).await.void_unwrap_err()
288 error!("{} failed: {:?}", &assocname, e);
291 error!("{} panicked!", &assocname);
292 panic::resume_unwind(je.into_panic());
298 error!("quitting because one of your client connections crashed");