chiark / gitweb /
minor message changes
[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        {}"#),
73                        &c.ic.link.client,
74                        token,
75                        c.ic.target_requests_outstanding,
76                        show_timeout,
77                        c.ic.max_batch_down,
78                        c.ic.max_batch_up,
79   );
80
81   let prefix2 = format!(into_crlfs!(
82     r#"
83        --b
84        Content-Type: application/octet-stream
85        Content-Disposition: form-data; name="d"
86
87        "#),
88   );
89   let suffix = format!(into_crlfs!(
90     r#"
91        --b--
92        "#),
93   );
94
95   macro_rules! content { {
96     $out:ty,
97     $iter:ident,
98     $into:ident,
99   } => {
100     itertools::chain![
101       array::IntoIter::new([
102         prefix1.$into(),
103         prefix2.$into(),
104       ]).take(
105         if upbound.is_empty() { 1 } else { 2 }
106       ),
107       Itertools::intersperse(
108         upbound.$iter().map(|u| { let out: $out = u.$into(); out }),
109         SLIP_END_SLICE.$into()
110       ),
111       [ suffix.$into() ],
112     ]
113   }}
114
115   let body_len: usize = content!(
116     &[u8],
117     iter,
118     as_ref,
119   ).map(|b| b.len()).sum();
120
121   trace!("{} #{}: req; tx body_len={} frames={}",
122          &c.ic, req_num, body_len, upbound.len());
123
124   let body = hyper::body::Body::wrap_stream(
125     futures::stream::iter(
126       content!(
127         Bytes,
128         into_iter,
129         into,
130       ).map(Ok::<Bytes,Void>)
131     )
132   );
133
134   let req = hyper::Request::post(&c.ic.url)
135     .header("Content-Type", r#"multipart/form-data; boundary="b""#)
136     .header("Content-Length", body_len)
137     .body(body)
138     .context("construct request")?;
139
140   let resp = c.hclient.request(req);
141   let fut = Box::pin(async move {
142     let r = async { tokio::time::timeout( c.ic.effective_http_timeout, async {
143       let resp = resp.await.context("make request")?;
144       let status = resp.status();
145       let resp = resp.into_body();
146       let max_body = c.ic.max_batch_down.sat() + MAX_BATCH_DOWN_RESP_OVERHEAD;
147       let resp = read_limited_body(max_body, resp).await?;
148
149       if ! status.is_success() {
150         throw!(anyhow!("HTTP error status={} body={:?}",
151                        &status, String::from_utf8_lossy(&resp)));
152       }
153
154       Ok::<_,AE>(resp)
155     }).await? }.await;
156
157     let r = c.reporter.lock().filter(Some(req_num), r);
158
159     if let Some(r) = &r {
160       trace!("{} #{}: rok; rx bytes={}", &c.ic, req_num, r.len());
161     } else {
162       tokio::time::sleep(c.ic.http_retry).await;
163     }
164     r
165   });
166   reqs.push(fut);
167 }
168
169 async fn run_client<C:HCC>(
170   ic: InstanceConfig,
171   hclient: Arc<hyper::Client<C>>
172 ) -> Result<Void, AE>
173 {
174   debug!("{}: config: {:?}", &ic, &ic);
175
176   let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
177
178   let c = ClientContext {
179     reporter: &reporter,
180     hclient: &hclient,
181     ic: &ic,
182   };
183
184   let mut ipif = Ipif::start(&ic.ipif, Some(ic.to_string()))?;
185
186   let mut req_num: ReqNum = 0;
187
188   let mut tx_queue: VecDeque<TxQueued> = default();
189   let mut upbound = Frames::default();
190
191   let mut reqs: Vec<OutstandingRequest>
192     = Vec::with_capacity(ic.max_requests_outstanding.sat());
193
194   let mut rx_queue: FrameQueue = default();
195
196   let trouble = async {
197     loop {
198       let rx_queue_space = 
199         if rx_queue.remaining() < ic.max_batch_down.sat() {
200           Ok(())
201         } else {
202           Err(())
203         };
204       
205       select! {
206         biased;
207
208         y = ipif.rx.write_all_buf(&mut rx_queue),
209         if ! rx_queue.is_empty() =>
210         {
211           let () = y.context("write rx data to ipif")?;
212         },
213
214         () = async {
215           let expires = tx_queue.front().unwrap().expires;
216           tokio::time::sleep_until(expires).await
217         },
218         if ! tx_queue.is_empty() =>
219         {
220           let _ = tx_queue.pop_front();
221         },
222
223         data = ipif.tx.next_segment(),
224         if tx_queue.is_empty() =>
225         {
226           let data = (||{
227             data?.ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))
228           })().context("read from ipif")?;
229           //eprintln!("data={:?}", DumpHex(&data));
230
231           match check1(Slip2Mime, ic.mtu, &data, |header| {
232             let addr = ip_packet_addr::<false>(header)?;
233             if addr != ic.link.client.0 { throw!(PE::Src(addr)) }
234             Ok(())
235           }) {
236             Ok(data) => tx_queue.push_back(TxQueued {
237               data,
238               expires: Instant::now() + ic.max_queue_time
239             }),
240             Err(PE::Empty) => { },
241             Err(e@ PE::Src(_)) => debug!("{}: tx discarding: {}", &ic, e),
242             Err(e) => error!("{}: tx discarding: {}", &ic, e),
243           };
244         },
245
246         _ = async { },
247         if ! upbound.tried_full() &&
248            ! tx_queue.is_empty() =>
249         {
250           while let Some(TxQueued { data, expires }) = tx_queue.pop_front() {
251             match upbound.add(ic.max_batch_up, data.into()/*todo:504*/) {
252               Err(data) => {
253                 tx_queue.push_front(TxQueued { data: data.into(), expires });
254                 break;
255               }
256               Ok(()) => { },
257             }
258           }
259         },
260
261         _ = async { },
262         if rx_queue_space.is_ok() &&
263           (reqs.len() < ic.target_requests_outstanding.sat() ||
264            (reqs.len() < ic.max_requests_outstanding.sat() &&
265             ! upbound.is_empty()))
266           =>
267         {
268           submit_request(&c, &mut req_num, &mut reqs,
269                          mem::take(&mut upbound).into())?;
270         },
271
272         (got, goti, _) = async { future::select_all(&mut reqs).await },
273           if ! reqs.is_empty() =>
274         {
275           reqs.swap_remove(goti);
276
277           if let Some(got) = got {
278             
279             //eprintln!("got={:?}", DumpHex(&got));
280             match checkn(SlipNoConv,ic.mtu, &got, &mut rx_queue, |header| {
281               let addr = ip_packet_addr::<true>(header)?;
282               if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
283               Ok(())
284             }, |e| error!("{} #{}: rx discarding: {}", &ic, req_num, e)) {
285               Ok(()) => reporter.lock().success(),
286               Err(ErrorOnlyBad) => {
287                 reqs.push(Box::pin(async {
288                   tokio::time::sleep(ic.http_retry).await;
289                   None
290                 }));
291               },
292             }
293           }
294         },
295
296         _ = tokio::time::sleep(c.ic.effective_http_timeout),
297         if rx_queue_space.is_err() =>
298         {
299           reporter.lock().filter(None, Err::<Void,_>(
300             anyhow!("rx queue full, blocked")
301           ));
302         },
303       }
304     }
305   }.await;
306
307   ipif.quitting(Some(&ic)).await;
308   trouble
309 }
310
311 #[tokio::main]
312 async fn main() {
313   let opts = Opts::from_args();
314   let (ics,()) = config::startup("hippotat", LinkEnd::Client,
315                                  &opts.config, &opts.log, |_|Ok(()));
316
317   let https = HttpsConnector::new();
318   let hclient = hyper::Client::builder()
319     .http1_preserve_header_case(true)
320     .build::<_, hyper::Body>(https);
321   let hclient = Arc::new(hclient);
322
323   info!("starting");
324   let () = future::select_all(
325     ics.into_iter().map(|ic| Box::pin(async {
326       let assocname = ic.to_string();
327       info!("{} starting", &assocname);
328       let hclient = hclient.clone();
329       let join = task::spawn(async {
330         run_client(ic, hclient).await.void_unwrap_err()
331       });
332       match join.await {
333         Ok(e) => {
334           error!("{} failed: {}", &assocname, e);
335         },
336         Err(je) => {
337           error!("{} panicked!", &assocname);
338           panic::resume_unwind(je.into_panic());
339         },
340       }
341     }))
342   ).await.0;
343
344   error!("quitting because one of your client connections crashed");
345   process::exit(16);
346 }