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