chiark / gitweb /
eyre: wip experiment, needs some work
[hippotat.git] / src / bin / client.rs
1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 // There is NO WARRANTY.
4
5 use hippotat::prelude::*;
6 use hippotat_macros::into_crlfs;
7
8 const MAX_BATCH_DOWN_RESP_OVERHEAD: usize = 10_000;
9
10 #[derive(StructOpt,Debug)]
11 pub struct Opts {
12   #[structopt(flatten)]
13   log: LogOpts,
14
15   #[structopt(flatten)]
16   config: config::Opts,
17 }
18
19 type OutstandingRequest<'r> = Pin<Box<
20     dyn Future<Output=Option<Box<[u8]>>> + Send + 'r
21     >>;
22
23 impl<T> HCC for T where
24         T: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
25 trait HCC: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
26
27 struct ClientContext<'c,C> {
28   ic: &'c InstanceConfig,
29   hclient: &'c Arc<hyper::Client<C>>,
30   reporter: &'c parking_lot::Mutex<Reporter<'c>>,
31 }
32
33 #[derive(Debug)]
34 struct TxQueued {
35   expires: Instant,
36   data: Box<[u8]>,
37 }
38
39 #[throws(AE)]
40 fn submit_request<'r, 'c:'r, C:HCC>(
41   c: &'c ClientContext<C>,
42   req_num: &mut ReqNum,
43   reqs: &mut Vec<OutstandingRequest<'r>>,
44   upbound: FramesData,
45 ) {
46   let show_timeout = c.ic.http_timeout
47     .saturating_add(Duration::from_nanos(999_999_999))
48     .as_secs();
49
50   let time_t = SystemTime::now()
51     .duration_since(UNIX_EPOCH)
52     .unwrap_or_else(|_| Duration::default()) // clock is being weird
53     .as_secs();
54   let time_t = format!("{:x}", time_t);
55   let hmac = token_hmac(c.ic.secret.0.as_bytes(), time_t.as_bytes());
56   let mut token = time_t;
57   write!(token, " ").unwrap();
58   base64::encode_config_buf(&hmac, BASE64_CONFIG, &mut token);
59
60   let req_num = { *req_num += 1; *req_num };
61
62   let prefix1 = format!(into_crlfs!(
63     r#"--b
64        Content-Type: text/plain; charset="utf-8"
65        Content-Disposition: form-data; name="m"
66
67        {}
68        {}
69        {}
70        {}
71        {}"#),
72                        &c.ic.link.client,
73                        token,
74                        c.ic.target_requests_outstanding,
75                        show_timeout,
76                        c.ic.max_batch_down,
77   );
78
79   let prefix2 = format!(into_crlfs!(
80     r#"
81        --b
82        Content-Type: application/octet-stream
83        Content-Disposition: form-data; name="d"
84
85        "#),
86   );
87   let suffix = format!(into_crlfs!(
88     r#"
89        --b--
90        "#),
91   );
92
93   macro_rules! content { {
94     $out:ty,
95     $iter:ident,
96     $into:ident,
97   } => {
98     itertools::chain![
99       array::IntoIter::new([
100         prefix1.$into(),
101         prefix2.$into(),
102       ]).take(
103         if upbound.is_empty() { 1 } else { 2 }
104       ),
105       Itertools::intersperse(
106         upbound.$iter().map(|u| { let out: $out = u.$into(); out }),
107         SLIP_END_SLICE.$into()
108       ),
109       [ suffix.$into() ],
110     ]
111   }}
112
113   let body_len: usize = content!(
114     &[u8],
115     iter,
116     as_ref,
117   ).map(|b| b.len()).sum();
118
119   trace!("{} #{}: req; tx bytes={} frames={}",
120          &c.ic, req_num, body_len, upbound.len());
121
122   let body = hyper::body::Body::wrap_stream(
123     futures::stream::iter(
124       content!(
125         Bytes,
126         into_iter,
127         into,
128       ).map(Ok::<Bytes,Void>)
129     )
130   );
131
132   let req = hyper::Request::post(&c.ic.url)
133     .header("Content-Type", r#"multipart/form-data; boundary="b""#)
134     .header("Content-Length", body_len)
135     .body(body)
136     .context("construct request")?;
137
138   let resp = c.hclient.request(req);
139   let fut = Box::pin(async move {
140     let r = async { tokio::time::timeout( c.ic.effective_http_timeout, async {
141       let resp = resp.await.context("make request")?;
142       let status = resp.status();
143       let resp = resp.into_body();
144       let max_body = c.ic.max_batch_down.sat() + MAX_BATCH_DOWN_RESP_OVERHEAD;
145       let resp = read_limited_body(max_body, resp).await?;
146
147       if ! status.is_success() {
148         throw!(anyhow!("HTTP error status={} body={:?}",
149                        &status, String::from_utf8_lossy(&resp)));
150       }
151
152       Ok::<_,AE>(resp)
153     }).await? }.await;
154
155     let r = c.reporter.lock().filter(Some(req_num), r);
156
157     if let Some(r) = &r {
158       trace!("{} #{}: rok; rx bytes={}", &c.ic, req_num, r.len());
159     } else {
160       tokio::time::sleep(c.ic.http_retry).await;
161     }
162     r
163   });
164   reqs.push(fut);
165 }
166
167 async fn run_client<C:HCC>(
168   ic: InstanceConfig,
169   hclient: Arc<hyper::Client<C>>
170 ) -> Result<Void, AE>
171 {
172   debug!("{}: config: {:?}", &ic, &ic);
173
174   let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
175
176   let c = ClientContext {
177     reporter: &reporter,
178     hclient: &hclient,
179     ic: &ic,
180   };
181
182   let mut ipif = tokio::process::Command::new("sh")
183     .args(&["-c", &ic.ipif])
184     .stdin (process::Stdio::piped())
185     .stdout(process::Stdio::piped())
186     .stderr(process::Stdio::piped())
187     .kill_on_drop(true)
188     .spawn().context("spawn ipif")?;
189   
190   let stderr = ipif.stderr.take().unwrap();
191   let ic_name = ic.to_string();
192   let stderr_task = task::spawn(async move {
193     let mut stderr = tokio::io::BufReader::new(stderr).lines();
194     while let Some(l) = stderr.next_line().await? {
195       error!("{}: ipif stderr: {}", &ic_name, l.trim_end());
196     }
197     Ok::<_,io::Error>(())
198   });
199
200   let mut req_num: ReqNum = 0;
201
202   let tx_stream = ipif.stdout.take().unwrap();
203   let mut rx_stream = ipif.stdin .take().unwrap();
204
205   let mut tx_stream = tokio::io::BufReader::new(tx_stream).split(SLIP_END);
206   let mut tx_queue: VecDeque<TxQueued> = default();
207   let mut upbound = Frames::default();
208
209   let mut reqs: Vec<OutstandingRequest>
210     = Vec::with_capacity(ic.max_requests_outstanding.sat());
211
212   let mut rx_queue: FrameQueue = default();
213
214   let trouble = async {
215     loop {
216       let rx_queue_space = 
217         if rx_queue.remaining() < ic.max_batch_down.sat() {
218           Ok(())
219         } else {
220           Err(())
221         };
222       
223       select! {
224         biased;
225
226         y = rx_stream.write_all_buf(&mut rx_queue),
227         if ! rx_queue.is_empty() =>
228         {
229           let () = y.context("write rx data to ipif")?;
230         },
231
232         () = async {
233           let expires = tx_queue.front().unwrap().expires;
234           tokio::time::sleep_until(expires).await
235         },
236         if ! tx_queue.is_empty() =>
237         {
238           let _ = tx_queue.pop_front();
239         },
240
241         data = tx_stream.next_segment(),
242         if tx_queue.is_empty() =>
243         {
244           let data = (||{
245             data?.ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))
246           })().context("read from ipif")?;
247           //eprintln!("data={:?}", DumpHex(&data));
248
249           match check1(Slip2Mime, ic.mtu, &data, |header| {
250             let addr = ip_packet_addr::<false>(header)?;
251             if addr != ic.link.client.0 { throw!(PE::Src(addr)) }
252             Ok(())
253           }) {
254             Ok(data) => tx_queue.push_back(TxQueued {
255               data,
256               expires: Instant::now() + ic.max_queue_time
257             }),
258             Err(PE::Empty) => { },
259             Err(e@ PE::Src(_)) => debug!("{}: tx discarding: {}", &ic, e),
260             Err(e) => error!("{}: tx discarding: {}", &ic, e),
261           };
262         },
263
264         _ = async { },
265         if ! upbound.tried_full() &&
266            ! tx_queue.is_empty() =>
267         {
268           while let Some(TxQueued { data, expires }) = tx_queue.pop_front() {
269             match upbound.add(ic.max_batch_up, data.into()/*todo:504*/) {
270               Err(data) => { tx_queue.push_front(TxQueued { data: data.into(), expires }); break; }
271               Ok(()) => { },
272             }
273           }
274         },
275
276         _ = async { },
277         if rx_queue_space.is_ok() &&
278           (reqs.len() < ic.target_requests_outstanding.sat() ||
279            (reqs.len() < ic.max_requests_outstanding.sat() &&
280             ! upbound.is_empty()))
281           =>
282         {
283           submit_request(&c, &mut req_num, &mut reqs,
284                          mem::take(&mut upbound).into())?;
285         },
286
287         (got, goti, _) = async { future::select_all(&mut reqs).await },
288           if ! reqs.is_empty() =>
289         {
290           reqs.swap_remove(goti);
291
292           if let Some(got) = got {
293             reporter.lock().success();
294             //eprintln!("got={:?}", DumpHex(&got));
295             checkn(SlipNoConv,ic.mtu, &got, &mut rx_queue, |header| {
296               let addr = ip_packet_addr::<true>(header)?;
297               if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
298               Ok(())
299             }, |e| error!("{} #{}: rx discarding: {}", &ic, req_num, e));
300           
301           }
302         },
303
304         _ = tokio::time::sleep(c.ic.effective_http_timeout),
305         if rx_queue_space.is_err() =>
306         {
307           reporter.lock().filter(None, Err::<Void,_>(
308             anyhow!("rx queue full, blocked")
309           ));
310         },
311       }
312     }
313   }.await;
314
315   drop(tx_stream);
316
317   match ipif.wait().await {
318     Err(e) => error!("{}: also, failed to await ipif child: {}", &ic, e),
319     Ok(st) => {
320       let stderr_timeout = Duration::from_millis(1000);
321       match tokio::time::timeout(stderr_timeout, stderr_task).await {
322         Err::<_,tokio::time::error::Elapsed>(_)
323           => warn!("{}: ipif stderr task continues!", &ic),
324         Ok(Err(e)) => error!("{}: ipif stderr task crashed: {}", &ic, e),
325         Ok(Ok(Err(e))) => error!("{}: ipif stderr read failed: {}", &ic, e),
326         Ok(Ok(Ok(()))) => { },
327       }
328       if ! st.success() {
329         error!("{}: ipif process failed: {}", &ic, st);
330       }
331     }
332   }
333
334   trouble
335 }
336
337 #[tokio::main]
338 async fn main() -> Result<(), AE> {
339   dedup_eyre_setup()?;
340   let opts = Opts::from_args();
341
342   let ics = config::read(&opts.config, LinkEnd::Client)?;
343   if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
344
345   opts.log.log_init()?;
346
347   let https = HttpsConnector::new();
348   let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
349   let hclient = Arc::new(hclient);
350
351   info!("starting");
352   let () = future::select_all(
353     ics.into_iter().map(|ic| Box::pin(async {
354       let assocname = ic.to_string();
355       info!("{} starting", &assocname);
356       let hclient = hclient.clone();
357       let join = task::spawn(async {
358         run_client(ic, hclient).await.void_unwrap_err()
359       });
360       match join.await {
361         Ok(e) => {
362           error!("{} failed: {:?}", &assocname, e);
363         },
364         Err(je) => {
365           error!("{} panicked!", &assocname);
366           panic::resume_unwind(je.into_panic());
367         },
368       }
369     }))
370   ).await.0;
371
372   error!("quitting because one of your client connections crashed");
373   process::exit(16);
374 }