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 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>,
26 reqs: &mut Vec<OutstandingRequest<'r>>,
29 let show_timeout = c.ic.http_timeout
30 .saturating_add(Duration::from_nanos(999_999_999))
33 let time_t = SystemTime::now()
34 .duration_since(UNIX_EPOCH)
35 .unwrap_or_else(|_| Duration::default()) // clock is being weird
37 let time_t = format!("{:x}", time_t);
38 let hmac = token_hmac(c.ic.secret.0.as_bytes(), time_t.as_bytes());
39 let mut token = time_t;
40 write!(token, " ").unwrap();
41 base64::encode_config_buf(&hmac, BASE64_CONFIG, &mut token);
43 let req_num = { *req_num += 1; *req_num };
45 let prefix1 = format!(into_crlfs!(
47 Content-Type: text/plain; charset="utf-8"
48 Content-Disposition: form-data; name="m"
56 c.ic.target_requests_outstanding,
60 let prefix2 = format!(into_crlfs!(
63 Content-Type: application/octet-stream
64 Content-Disposition: form-data; name="d"
68 let suffix = format!(into_crlfs!(
74 macro_rules! content { {
80 array::IntoIter::new([
84 if upbound.is_empty() { 1 } else { 2 }
86 Itertools::intersperse(
87 upbound.$iter().map(|u| { let out: $out = u.$into(); out }),
88 SLIP_END_SLICE.$into()
94 let body_len: usize = content!(
98 ).map(|b| b.len()).sum();
100 trace!("{} #{}: frames={} bytes={}",
101 &c.ic, req_num, upbound.len(), body_len);
103 let body = hyper::body::Body::wrap_stream(
104 futures::stream::iter(
109 ).map(Ok::<Bytes,Void>)
113 let req = hyper::Request::post(&c.ic.url)
114 .header("Content-Type", r#"multipart/form-data; boundary="b""#)
115 .header("Content-Length", body_len)
117 .context("construct request")?;
119 let resp = c.hclient.request(req);
120 let fut = Box::pin(async move {
121 let r = async { tokio::time::timeout( c.ic.http_timeout, async {
122 let resp = resp.await.context("make request")?;
123 let status = resp.status();
124 let resp = resp.into_body();
125 // xxx: some size limit to avoid mallocing the universe
126 let resp = hyper::body::to_bytes(resp).await
127 .context("HTTP error fetching response body")?;
129 if ! status.is_success() {
130 // xxx get body and log it
131 throw!(anyhow!("HTTP error status={} body={:?}",
132 &status, String::from_utf8_lossy(&resp)));
138 let r = c.reporter.lock().filter(Some(req_num), r);
141 tokio::time::sleep(c.ic.http_retry).await;
148 #[allow(unused_variables)] // xxx
149 #[allow(unused_mut)] // xxx
150 #[allow(dead_code)] // xxx
151 async fn run_client<C:HCC>(
153 hclient: Arc<hyper::Client<C>>
154 ) -> Result<Void, AE>
156 debug!("{}: config: {:?}", &ic, &ic);
158 let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
160 let c = ClientContext {
166 let mut ipif = tokio::process::Command::new("sh")
167 .args(&["-c", &ic.ipif])
168 .stdin (process::Stdio::piped())
169 .stdout(process::Stdio::piped())
170 .stderr(process::Stdio::piped())
172 .spawn().context("spawn ipif")?;
174 let stderr = ipif.stderr.take().unwrap();
175 let ic_name = ic.to_string();
176 let _ = task::spawn(async move {
177 let mut stderr = tokio::io::BufReader::new(stderr).lines();
178 while let Some(l) = stderr.next_line().await? {
179 error!("{}: ipif stderr: {}", &ic_name, l.trim_end());
181 Ok::<_,io::Error>(())
184 let mut req_num: ReqNum = 0;
186 let tx_stream = ipif.stdout.take().unwrap();
187 let mut rx_stream = ipif.stdin .take().unwrap();
189 let mut tx_stream = tokio::io::BufReader::new(tx_stream).split(SLIP_END);
190 let mut packets: VecDeque<Box<[u8]>> = default();
191 let mut upbound = Frames::default();
193 let mut reqs: Vec<OutstandingRequest>
194 = Vec::with_capacity(ic.max_requests_outstanding.sat());
196 let mut rx_queue: FrameQueue = default();
198 // xxx check that ic settings are all honoured
203 y = rx_stream.write_all_buf(&mut rx_queue),
204 if ! rx_queue.is_empty() =>
206 let () = y.context("write rx data to ipif")?;
209 data = tx_stream.next_segment(),
210 if packets.is_empty() =>
213 data.context("read from ipif")?
214 .ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
215 //eprintln!("data={:?}", DumpHex(&data));
217 match check1(Slip2Mime, ic.mtu, &data, |header| {
218 let addr = ip_packet_addr::<false>(header)?;
219 if addr != ic.link.client.0 { throw!(PE::Src(addr)) }
222 Ok(packet) => packets.push_back(packet),
223 Err(PE::Empty) => { },
224 Err(e@ PE::Src(_)) => debug!("{}: tx discarding: {}", &ic, e),
225 Err(e) => error!("{}: tx discarding: {}", &ic, e),
230 if ! upbound.tried_full() &&
231 ! packets.is_empty() =>
233 while let Some(packet) = packets.pop_front() {
234 match upbound.add(ic.max_batch_up, packet.into()/*xxx*/) {
235 Err(packet) => { packets.push_front(packet.into()/*xxx*/); break; }
242 if reporter.lock().filter(None, {
243 if rx_queue.remaining() < ic.max_batch_down.sat() * 3 /* xxx */ {
244 // xxx make this separate option ? docs say server only
247 Err(anyhow!("rx queue full"))
250 (reqs.len() < ic.target_requests_outstanding.sat() ||
251 (reqs.len() < ic.max_requests_outstanding.sat() &&
252 ! upbound.is_empty()))
253 // xxx backpressure, if too much in rx_queue
256 submit_request(&c, &mut req_num, &mut reqs,
257 mem::take(&mut upbound).into())?;
260 (got, goti, _) = async { future::select_all(&mut reqs).await },
261 if ! reqs.is_empty() =>
263 reqs.swap_remove(goti);
265 if let Some(got) = got {
266 reporter.lock().success();
267 //eprintln!("got={:?}", DumpHex(&got));
268 checkn(SlipNoConv,ic.mtu, &got, &mut rx_queue, |header| {
269 let addr = ip_packet_addr::<true>(header)?;
270 if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
272 }, |e| error!("{} #{}: rx discarding: {}", &ic, req_num, e));
282 async fn main() -> Result<(), AE> {
283 let ics = config::read(LinkEnd::Client)?;
284 if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
288 let https = HttpsConnector::new();
289 let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
290 let hclient = Arc::new(hclient);
293 let () = future::select_all(
294 ics.into_iter().map(|ic| Box::pin(async {
295 let assocname = ic.to_string();
296 info!("{} starting", &assocname);
297 let hclient = hclient.clone();
298 let join = task::spawn(async {
299 run_client(ic, hclient).await.void_unwrap_err()
303 error!("{} failed: {:?}", &assocname, e);
306 error!("{} panicked!", &assocname);
307 panic::resume_unwind(je.into_panic());
313 error!("quitting because one of your client connections crashed");