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)]
10 /// Increase debug level
11 #[structopt(long, short="D", parse(from_occurrences))]
18 type OutstandingRequest<'r> = Pin<Box<
19 dyn Future<Output=Option<Bytes>> + Send + 'r
22 impl<T> HCC for T where
23 T: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
24 trait HCC: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
26 struct ClientContext<'c,C> {
27 ic: &'c InstanceConfig,
28 hclient: &'c Arc<hyper::Client<C>>,
29 reporter: &'c parking_lot::Mutex<Reporter<'c>>,
33 fn submit_request<'r, 'c:'r, C:HCC>(
34 c: &'c ClientContext<C>,
36 reqs: &mut Vec<OutstandingRequest<'r>>,
39 let show_timeout = c.ic.http_timeout
40 .saturating_add(Duration::from_nanos(999_999_999))
43 let time_t = SystemTime::now()
44 .duration_since(UNIX_EPOCH)
45 .unwrap_or_else(|_| Duration::default()) // clock is being weird
47 let time_t = format!("{:x}", time_t);
48 let hmac = token_hmac(c.ic.secret.0.as_bytes(), time_t.as_bytes());
49 let mut token = time_t;
50 write!(token, " ").unwrap();
51 base64::encode_config_buf(&hmac, BASE64_CONFIG, &mut token);
53 let req_num = { *req_num += 1; *req_num };
55 let prefix1 = format!(into_crlfs!(
57 Content-Type: text/plain; charset="utf-8"
58 Content-Disposition: form-data; name="m"
66 c.ic.target_requests_outstanding,
70 let prefix2 = format!(into_crlfs!(
73 Content-Type: application/octet-stream
74 Content-Disposition: form-data; name="d"
78 let suffix = format!(into_crlfs!(
84 macro_rules! content { {
90 array::IntoIter::new([
94 if upbound.is_empty() { 1 } else { 2 }
96 Itertools::intersperse(
97 upbound.$iter().map(|u| { let out: $out = u.$into(); out }),
98 SLIP_END_SLICE.$into()
104 let body_len: usize = content!(
108 ).map(|b| b.len()).sum();
110 trace!("{} #{}: frames={} bytes={}",
111 &c.ic, req_num, upbound.len(), body_len);
113 let body = hyper::body::Body::wrap_stream(
114 futures::stream::iter(
119 ).map(Ok::<Bytes,Void>)
123 let req = hyper::Request::post(&c.ic.url)
124 .header("Content-Type", r#"multipart/form-data; boundary="b""#)
125 .header("Content-Length", body_len)
127 .context("construct request")?;
129 let resp = c.hclient.request(req);
130 let fut = Box::pin(async move {
131 let r = async { tokio::time::timeout( c.ic.http_timeout, async {
132 let resp = resp.await.context("make request")?;
133 let status = resp.status();
134 let resp = resp.into_body();
135 // xxx: some size limit to avoid mallocing the universe
136 let resp = hyper::body::to_bytes(resp).await
137 .context("HTTP error fetching response body")?;
139 if ! status.is_success() {
140 throw!(anyhow!("HTTP error status={} body={:?}",
141 &status, String::from_utf8_lossy(&resp)));
147 let r = c.reporter.lock().filter(Some(req_num), r);
150 tokio::time::sleep(c.ic.http_retry).await;
157 async fn run_client<C:HCC>(
159 hclient: Arc<hyper::Client<C>>
160 ) -> Result<Void, AE>
162 debug!("{}: config: {:?}", &ic, &ic);
164 let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
166 let c = ClientContext {
172 let mut ipif = tokio::process::Command::new("sh")
173 .args(&["-c", &ic.ipif])
174 .stdin (process::Stdio::piped())
175 .stdout(process::Stdio::piped())
176 .stderr(process::Stdio::piped())
178 .spawn().context("spawn ipif")?;
180 let stderr = ipif.stderr.take().unwrap();
181 let ic_name = ic.to_string();
182 let _ = task::spawn(async move {
183 let mut stderr = tokio::io::BufReader::new(stderr).lines();
184 while let Some(l) = stderr.next_line().await? {
185 error!("{}: ipif stderr: {}", &ic_name, l.trim_end());
187 Ok::<_,io::Error>(())
190 let mut req_num: ReqNum = 0;
192 let tx_stream = ipif.stdout.take().unwrap();
193 let mut rx_stream = ipif.stdin .take().unwrap();
195 let mut tx_stream = tokio::io::BufReader::new(tx_stream).split(SLIP_END);
196 let mut packets: VecDeque<Box<[u8]>> = default();
197 let mut upbound = Frames::default();
199 let mut reqs: Vec<OutstandingRequest>
200 = Vec::with_capacity(ic.max_requests_outstanding.sat());
202 let mut rx_queue: FrameQueue = default();
204 // xxx check that ic settings are all honoured
209 y = rx_stream.write_all_buf(&mut rx_queue),
210 if ! rx_queue.is_empty() =>
212 let () = y.context("write rx data to ipif")?;
215 data = tx_stream.next_segment(),
216 if packets.is_empty() =>
219 data.context("read from ipif")?
220 .ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
221 //eprintln!("data={:?}", DumpHex(&data));
223 match check1(Slip2Mime, ic.mtu, &data, |header| {
224 let addr = ip_packet_addr::<false>(header)?;
225 if addr != ic.link.client.0 { throw!(PE::Src(addr)) }
228 Ok(packet) => packets.push_back(packet),
229 Err(PE::Empty) => { },
230 Err(e@ PE::Src(_)) => debug!("{}: tx discarding: {}", &ic, e),
231 Err(e) => error!("{}: tx discarding: {}", &ic, e),
236 if ! upbound.tried_full() &&
237 ! packets.is_empty() =>
239 while let Some(packet) = packets.pop_front() {
240 match upbound.add(ic.max_batch_up, packet.into()/*xxx*/) {
241 Err(packet) => { packets.push_front(packet.into()/*xxx*/); break; }
248 if reporter.lock().filter(None, {
249 if rx_queue.remaining() < ic.max_batch_down.sat() * 3 /* xxx */ {
250 // xxx make this separate option ? docs say server only
253 Err(anyhow!("rx queue full"))
256 (reqs.len() < ic.target_requests_outstanding.sat() ||
257 (reqs.len() < ic.max_requests_outstanding.sat() &&
258 ! upbound.is_empty()))
261 submit_request(&c, &mut req_num, &mut reqs,
262 mem::take(&mut upbound).into())?;
265 (got, goti, _) = async { future::select_all(&mut reqs).await },
266 if ! reqs.is_empty() =>
268 reqs.swap_remove(goti);
270 if let Some(got) = got {
271 reporter.lock().success();
272 //eprintln!("got={:?}", DumpHex(&got));
273 checkn(SlipNoConv,ic.mtu, &got, &mut rx_queue, |header| {
274 let addr = ip_packet_addr::<true>(header)?;
275 if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
277 }, |e| error!("{} #{}: rx discarding: {}", &ic, req_num, e));
287 async fn main() -> Result<(), AE> {
288 let opts = Opts::from_args();
290 let ics = config::read(&opts.config, LinkEnd::Client)?;
291 if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
294 let env = env_logger::Env::new()
295 .filter("HIPPOTAT_LOG")
296 .write_style("HIPPOTAT_LOG_STYLE");
298 let mut logb = env_logger::Builder::new();
299 logb.filter(Some("hippotat"),
300 *[ log::LevelFilter::Info,
301 log::LevelFilter::Debug ]
304 &log::LevelFilter::Trace
310 let https = HttpsConnector::new();
311 let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
312 let hclient = Arc::new(hclient);
315 let () = future::select_all(
316 ics.into_iter().map(|ic| Box::pin(async {
317 let assocname = ic.to_string();
318 info!("{} starting", &assocname);
319 let hclient = hclient.clone();
320 let join = task::spawn(async {
321 run_client(ic, hclient).await.void_unwrap_err()
325 error!("{} failed: {:?}", &assocname, e);
328 error!("{} panicked!", &assocname);
329 panic::resume_unwind(je.into_panic());
335 error!("quitting because one of your client connections crashed");