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