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 const MAX_BATCH_DOWN_RESP_OVERHEAD: usize = 10_000;
10 #[derive(StructOpt,Debug)]
12 /// Increase debug level
13 #[structopt(long, short="D", parse(from_occurrences))]
20 type OutstandingRequest<'r> = Pin<Box<
21 dyn Future<Output=Option<Box<[u8]>>> + Send + 'r
24 impl<T> HCC for T where
25 T: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
26 trait HCC: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
28 struct ClientContext<'c,C> {
29 ic: &'c InstanceConfig,
30 hclient: &'c Arc<hyper::Client<C>>,
31 reporter: &'c parking_lot::Mutex<Reporter<'c>>,
35 fn submit_request<'r, 'c:'r, C:HCC>(
36 c: &'c ClientContext<C>,
38 reqs: &mut Vec<OutstandingRequest<'r>>,
41 let show_timeout = c.ic.http_timeout
42 .saturating_add(Duration::from_nanos(999_999_999))
45 let time_t = SystemTime::now()
46 .duration_since(UNIX_EPOCH)
47 .unwrap_or_else(|_| Duration::default()) // clock is being weird
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"
69 c.ic.target_requests_outstanding,
74 let prefix2 = format!(into_crlfs!(
77 Content-Type: application/octet-stream
78 Content-Disposition: form-data; name="d"
82 let suffix = format!(into_crlfs!(
88 macro_rules! content { {
94 array::IntoIter::new([
98 if upbound.is_empty() { 1 } else { 2 }
100 Itertools::intersperse(
101 upbound.$iter().map(|u| { let out: $out = u.$into(); out }),
102 SLIP_END_SLICE.$into()
108 let body_len: usize = content!(
112 ).map(|b| b.len()).sum();
114 trace!("{} #{}: req; tx bytes={} frames={}",
115 &c.ic, req_num, body_len, upbound.len());
117 let body = hyper::body::Body::wrap_stream(
118 futures::stream::iter(
123 ).map(Ok::<Bytes,Void>)
127 let req = hyper::Request::post(&c.ic.url)
128 .header("Content-Type", r#"multipart/form-data; boundary="b""#)
129 .header("Content-Length", body_len)
131 .context("construct request")?;
133 let resp = c.hclient.request(req);
134 let fut = Box::pin(async move {
135 let r = async { tokio::time::timeout( c.ic.effective_http_timeout, async {
136 let resp = resp.await.context("make request")?;
137 let status = resp.status();
138 let resp = resp.into_body();
139 let max_body = c.ic.max_batch_down.sat() + MAX_BATCH_DOWN_RESP_OVERHEAD;
140 let resp = read_limited_body(max_body, resp).await?;
142 if ! status.is_success() {
143 throw!(anyhow!("HTTP error status={} body={:?}",
144 &status, String::from_utf8_lossy(&resp)));
150 let r = c.reporter.lock().filter(Some(req_num), r);
152 if let Some(r) = &r {
153 trace!("{} #{}: rok; rx bytes={}", &c.ic, req_num, r.len());
155 tokio::time::sleep(c.ic.http_retry).await;
162 async fn run_client<C:HCC>(
164 hclient: Arc<hyper::Client<C>>
165 ) -> Result<Void, AE>
167 debug!("{}: config: {:?}", &ic, &ic);
169 let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
171 let c = ClientContext {
177 let mut ipif = tokio::process::Command::new("sh")
178 .args(&["-c", &ic.ipif])
179 .stdin (process::Stdio::piped())
180 .stdout(process::Stdio::piped())
181 .stderr(process::Stdio::piped())
183 .spawn().context("spawn ipif")?;
185 let stderr = ipif.stderr.take().unwrap();
186 let ic_name = ic.to_string();
187 let _ = task::spawn(async move {
188 let mut stderr = tokio::io::BufReader::new(stderr).lines();
189 while let Some(l) = stderr.next_line().await? {
190 error!("{}: ipif stderr: {}", &ic_name, l.trim_end());
192 Ok::<_,io::Error>(())
195 let mut req_num: ReqNum = 0;
197 let tx_stream = ipif.stdout.take().unwrap();
198 let mut rx_stream = ipif.stdin .take().unwrap();
200 let mut tx_stream = tokio::io::BufReader::new(tx_stream).split(SLIP_END);
201 let mut packets: VecDeque<Box<[u8]>> = default();
202 let mut upbound = Frames::default();
204 let mut reqs: Vec<OutstandingRequest>
205 = Vec::with_capacity(ic.max_requests_outstanding.sat());
207 let mut rx_queue: FrameQueue = default();
209 // xxx check that ic settings are all honoured
214 if rx_queue.remaining() < ic.max_batch_down.sat() {
221 y = rx_stream.write_all_buf(&mut rx_queue),
222 if ! rx_queue.is_empty() =>
224 let () = y.context("write rx data to ipif")?;
227 data = tx_stream.next_segment(),
228 if packets.is_empty() =>
231 data.context("read from ipif")?
232 .ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
233 //eprintln!("data={:?}", DumpHex(&data));
235 match check1(Slip2Mime, ic.mtu, &data, |header| {
236 let addr = ip_packet_addr::<false>(header)?;
237 if addr != ic.link.client.0 { throw!(PE::Src(addr)) }
240 Ok(packet) => packets.push_back(packet),
241 Err(PE::Empty) => { },
242 Err(e@ PE::Src(_)) => debug!("{}: tx discarding: {}", &ic, e),
243 Err(e) => error!("{}: tx discarding: {}", &ic, e),
248 if ! upbound.tried_full() &&
249 ! packets.is_empty() =>
251 while let Some(packet) = packets.pop_front() {
252 match upbound.add(ic.max_batch_up, packet.into()/*xxx*/) {
253 Err(packet) => { packets.push_front(packet.into()/*xxx*/); break; }
260 if rx_queue_space.is_ok() &&
261 (reqs.len() < ic.target_requests_outstanding.sat() ||
262 (reqs.len() < ic.max_requests_outstanding.sat() &&
263 ! upbound.is_empty()))
266 submit_request(&c, &mut req_num, &mut reqs,
267 mem::take(&mut upbound).into())?;
270 (got, goti, _) = async { future::select_all(&mut reqs).await },
271 if ! reqs.is_empty() =>
273 reqs.swap_remove(goti);
275 if let Some(got) = got {
276 reporter.lock().success();
277 //eprintln!("got={:?}", DumpHex(&got));
278 checkn(SlipNoConv,ic.mtu, &got, &mut rx_queue, |header| {
279 let addr = ip_packet_addr::<true>(header)?;
280 if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
282 }, |e| error!("{} #{}: rx discarding: {}", &ic, req_num, e));
287 _ = tokio::time::sleep(c.ic.effective_http_timeout),
288 if rx_queue_space.is_err() =>
290 reporter.lock().filter(None, Err::<Void,_>(
291 anyhow!("rx queue full, blocked")
300 async fn main() -> Result<(), AE> {
301 let opts = Opts::from_args();
303 let ics = config::read(&opts.config, LinkEnd::Client)?;
304 if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
307 let env = env_logger::Env::new()
308 .filter("HIPPOTAT_LOG")
309 .write_style("HIPPOTAT_LOG_STYLE");
311 let mut logb = env_logger::Builder::new();
312 logb.filter(Some("hippotat"),
313 *[ log::LevelFilter::Info,
314 log::LevelFilter::Debug ]
317 &log::LevelFilter::Trace
323 let https = HttpsConnector::new();
324 let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
325 let hclient = Arc::new(hclient);
328 let () = future::select_all(
329 ics.into_iter().map(|ic| Box::pin(async {
330 let assocname = ic.to_string();
331 info!("{} starting", &assocname);
332 let hclient = hclient.clone();
333 let join = task::spawn(async {
334 run_client(ic, hclient).await.void_unwrap_err()
338 error!("{} failed: {:?}", &assocname, e);
341 error!("{} panicked!", &assocname);
342 panic::resume_unwind(je.into_panic());
348 error!("quitting because one of your client connections crashed");