chiark / gitweb /
rename [Frame]QueueBuf
[hippotat.git] / client / 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 #[derive(StructOpt,Debug)]
9 pub struct Opts {
10   #[structopt(flatten)]
11   log: LogOpts,
12
13   #[structopt(flatten)]
14   config: config::Opts,
15 }
16
17 type OutstandingRequest<'r> = Pin<Box<
18     dyn Future<Output=Option<Box<[u8]>>> + Send + 'r
19     >>;
20
21 impl<T> HCC for T where
22         T: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
23 trait HCC: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
24
25 struct ClientContext<'c,C> {
26   ic: &'c InstanceConfig,
27   hclient: &'c Arc<hyper::Client<C>>,
28   reporter: &'c parking_lot::Mutex<Reporter<'c>>,
29 }
30
31 #[derive(Debug)]
32 struct TxQueued {
33   expires: Instant,
34   data: Box<[u8]>,
35 }
36
37 #[throws(AE)]
38 fn submit_request<'r, 'c:'r, C:HCC>(
39   c: &'c ClientContext<C>,
40   req_num: &mut ReqNum,
41   reqs: &mut Vec<OutstandingRequest<'r>>,
42   upbound: FramesData,
43 ) {
44   let show_timeout = c.ic.http_timeout
45     .saturating_add(Duration::from_nanos(999_999_999))
46     .as_secs();
47
48   let time_t = time_t_now();
49   let time_t = format!("{:x}", time_t);
50   let hmac = token_hmac(c.ic.secret.0.as_bytes(), time_t.as_bytes());
51   //dbg!(DumpHex(&hmac));
52   let mut token = time_t;
53   write!(token, " ").unwrap();
54   base64::encode_config_buf(&hmac, BASE64_CONFIG, &mut token);
55
56   let req_num = { *req_num += 1; *req_num };
57
58   let prefix1 = format!(into_crlfs!(
59     r#"--b
60        Content-Type: text/plain; charset="utf-8"
61        Content-Disposition: form-data; name="m"
62
63        {}
64        {}
65        {}
66        {}
67        {}
68        {}
69        {}"#),
70                        &c.ic.link.client,
71                        token,
72                        c.ic.target_requests_outstanding,
73                        show_timeout,
74                        c.ic.mtu,
75                        c.ic.max_batch_down,
76                        c.ic.max_batch_up,
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 body_len={} 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 mut resp = resp.into_body();
144       let max_body = c.ic.max_batch_down.sat() + MAX_OVERHEAD;
145       let resp = read_limited_bytes(
146         max_body, default(), default(), &mut resp
147       ).await
148         .discard_data().context("fetching response body")?;
149
150       if ! status.is_success() {
151         throw!(anyhow!("HTTP error status={} body={:?}",
152                        &status, String::from_utf8_lossy(&resp)));
153       }
154
155       Ok::<_,AE>(resp)
156     }).await? }.await;
157
158     let r = c.reporter.lock().filter(Some(req_num), r);
159
160     if let Some(r) = &r {
161       trace!("{} #{}: rok; rx bytes={}", &c.ic, req_num, r.len());
162     } else {
163       tokio::time::sleep(c.ic.http_retry).await;
164     }
165     r
166   });
167   reqs.push(fut);
168 }
169
170 async fn run_client<C:HCC>(
171   ic: InstanceConfig,
172   hclient: Arc<hyper::Client<C>>
173 ) -> Result<Void, AE>
174 {
175   debug!("{}: config: {:?}", &ic, &ic);
176
177   let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
178
179   let c = ClientContext {
180     reporter: &reporter,
181     hclient: &hclient,
182     ic: &ic,
183   };
184
185   let mut ipif = Ipif::start(&ic.ipif, Some(ic.to_string()))?;
186
187   let mut req_num: ReqNum = 0;
188
189   let mut tx_queue: VecDeque<TxQueued> = default();
190   let mut upbound = Frames::default();
191
192   let mut reqs: Vec<OutstandingRequest>
193     = Vec::with_capacity(ic.max_requests_outstanding.sat());
194
195   let mut rx_queue: FrameQueueBuf = default();
196
197   let trouble = async {
198     loop {
199       let rx_queue_space = 
200         if rx_queue.remaining() < ic.max_batch_down.sat() {
201           Ok(())
202         } else {
203           Err(())
204         };
205       
206       select! {
207         biased;
208
209         y = ipif.rx.write_all_buf(&mut rx_queue),
210         if ! rx_queue.is_empty() =>
211         {
212           let () = y.context("write rx data to ipif")?;
213         },
214
215         () = async {
216           let expires = tx_queue.front().unwrap().expires;
217           tokio::time::sleep_until(expires).await
218         },
219         if ! tx_queue.is_empty() =>
220         {
221           let _ = tx_queue.pop_front();
222         },
223
224         data = Ipif::next_frame(&mut ipif.tx),
225         if tx_queue.is_empty() =>
226         {
227           let data = data?;
228           //eprintln!("data={:?}", DumpHex(&data));
229
230           match slip::process1(Slip2Mime, ic.mtu, &data, |header| {
231             let saddr = ip_packet_addr::<false>(header)?;
232             if saddr != ic.link.client.0 { throw!(PE::Src(saddr)) }
233             Ok(())
234           }) {
235             Ok((data, ())) => tx_queue.push_back(TxQueued {
236               data,
237               expires: Instant::now() + ic.max_queue_time
238             }),
239             Err(PE::Empty) => { },
240             Err(e@ PE::Src(_)) => debug!("{}: tx discarding: {}", &ic, e),
241             Err(e) => error!("{}: tx discarding: {}", &ic, e),
242           };
243         },
244
245         _ = async { },
246         if ! upbound.tried_full() &&
247            ! tx_queue.is_empty() =>
248         {
249           while let Some(TxQueued { data, expires }) = tx_queue.pop_front() {
250             match upbound.add(ic.max_batch_up, data.into()/*todo:504*/) {
251               Err(data) => {
252                 tx_queue.push_front(TxQueued { data: data.into(), expires });
253                 break;
254               }
255               Ok(()) => { },
256             }
257           }
258         },
259
260         _ = async { },
261         if rx_queue_space.is_ok() &&
262           (reqs.len() < ic.target_requests_outstanding.sat() ||
263            (reqs.len() < ic.max_requests_outstanding.sat() &&
264             ! upbound.is_empty()))
265           =>
266         {
267           submit_request(&c, &mut req_num, &mut reqs,
268                          mem::take(&mut upbound).into())?;
269         },
270
271         (got, goti, _) = async { future::select_all(&mut reqs).await },
272           if ! reqs.is_empty() =>
273         {
274           reqs.swap_remove(goti);
275
276           if let Some(got) = got {
277             
278             //eprintln!("got={:?}", DumpHex(&got));
279             match slip::processn(SlipNoConv,ic.mtu, &got, |header| {
280               let addr = ip_packet_addr::<true>(header)?;
281               if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
282               Ok(())
283             },
284             |(o,())| future::ready(Ok({ rx_queue.push(o); })),
285             |e| Ok::<_,SlipFramesError<Void>>( {
286               error!("{} #{}: rx discarding: {}", &ic, req_num, e);
287             })).await
288             {
289               Ok(()) => reporter.lock().success(),
290               Err(SlipFramesError::ErrorOnlyBad) => {
291                 reqs.push(Box::pin(async {
292                   tokio::time::sleep(ic.http_retry).await;
293                   None
294                 }));
295               },
296               Err(SlipFramesError::Other(v)) => unreachable!(v),
297             }
298           }
299         },
300
301         _ = tokio::time::sleep(c.ic.effective_http_timeout),
302         if rx_queue_space.is_err() =>
303         {
304           reporter.lock().filter(None, Err::<Void,_>(
305             anyhow!("rx queue full, blocked")
306           ));
307         },
308       }
309     }
310   }.await;
311
312   ipif.quitting(Some(&ic)).await;
313   trouble
314 }
315
316 #[tokio::main]
317 async fn main() {
318   let opts = Opts::from_args();
319   let (ics,) = config::startup("hippotat", LinkEnd::Client,
320                                &opts.config, &opts.log, |ics|Ok((ics,)));
321
322   let https = HttpsConnector::new();
323   let hclient = hyper::Client::builder()
324     .http1_preserve_header_case(true)
325     .build::<_, hyper::Body>(https);
326   let hclient = Arc::new(hclient);
327
328   info!("starting");
329   let () = future::select_all(
330     ics.into_iter().map(|ic| Box::pin(async {
331       let assocname = ic.to_string();
332       info!("{} starting", &assocname);
333       let hclient = hclient.clone();
334       let join = task::spawn(async {
335         run_client(ic, hclient).await.void_unwrap_err()
336       });
337       match join.await {
338         Ok(e) => {
339           error!("{} failed: {}", &assocname, e);
340         },
341         Err(je) => {
342           error!("{} panicked!", &assocname);
343           panic::resume_unwind(je.into_panic());
344         },
345       }
346     }))
347   ).await.0;
348
349   error!("quitting because one of your client connections crashed");
350   process::exit(16);
351 }