chiark / gitweb /
new max_batch_down protocol, define
[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   /// Increase debug level
11   #[structopt(long, short="D", parse(from_occurrences))]
12   debug: usize,
13
14   #[structopt(flatten)]
15   config: config::Opts,
16 }
17
18 type OutstandingRequest<'r> = Pin<Box<
19     dyn Future<Output=Option<Bytes>> + Send + 'r
20     >>;
21
22 impl<T> HCC for T where
23         T: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
24 trait HCC: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
25
26 struct ClientContext<'c,C> {
27   ic: &'c InstanceConfig,
28   effective_http_timeout: Duration,
29   hclient: &'c Arc<hyper::Client<C>>,
30   reporter: &'c parking_lot::Mutex<Reporter<'c>>,
31 }
32
33 #[throws(AE)]
34 fn submit_request<'r, 'c:'r, C:HCC>(
35   c: &'c ClientContext<C>,
36   req_num: &mut ReqNum,
37   reqs: &mut Vec<OutstandingRequest<'r>>,
38   upbound: FramesData,
39 ) {
40   let show_timeout = c.ic.http_timeout
41     .saturating_add(Duration::from_nanos(999_999_999))
42     .as_secs();
43
44   let time_t = SystemTime::now()
45     .duration_since(UNIX_EPOCH)
46     .unwrap_or_else(|_| Duration::default()) // clock is being weird
47     .as_secs();
48   let time_t = format!("{:x}", time_t);
49   let hmac = token_hmac(c.ic.secret.0.as_bytes(), time_t.as_bytes());
50   let mut token = time_t;
51   write!(token, " ").unwrap();
52   base64::encode_config_buf(&hmac, BASE64_CONFIG, &mut token);
53
54   let req_num = { *req_num += 1; *req_num };
55
56   let prefix1 = format!(into_crlfs!(
57     r#"--b
58        Content-Type: text/plain; charset="utf-8"
59        Content-Disposition: form-data; name="m"
60
61        {}
62        {}
63        {}
64        {}
65        {}"#),
66                        &c.ic.link.client,
67                        token,
68                        c.ic.target_requests_outstanding,
69                        show_timeout,
70                        c.ic.max_batch_down,
71   );
72
73   let prefix2 = format!(into_crlfs!(
74     r#"
75        --b
76        Content-Type: application/octet-stream
77        Content-Disposition: form-data; name="d"
78
79        "#),
80   );
81   let suffix = format!(into_crlfs!(
82     r#"
83        --b--
84        "#),
85   );
86
87   macro_rules! content { {
88     $out:ty,
89     $iter:ident,
90     $into:ident,
91   } => {
92     itertools::chain![
93       array::IntoIter::new([
94         prefix1.$into(),
95         prefix2.$into(),
96       ]).take(
97         if upbound.is_empty() { 1 } else { 2 }
98       ),
99       Itertools::intersperse(
100         upbound.$iter().map(|u| { let out: $out = u.$into(); out }),
101         SLIP_END_SLICE.$into()
102       ),
103       [ suffix.$into() ],
104     ]
105   }}
106
107   let body_len: usize = content!(
108     &[u8],
109     iter,
110     as_ref,
111   ).map(|b| b.len()).sum();
112
113   trace!("{} #{}: frames={} bytes={}",
114          &c.ic, req_num, upbound.len(), body_len);
115
116   let body = hyper::body::Body::wrap_stream(
117     futures::stream::iter(
118       content!(
119         Bytes,
120         into_iter,
121         into,
122       ).map(Ok::<Bytes,Void>)
123     )
124   );
125
126   let req = hyper::Request::post(&c.ic.url)
127     .header("Content-Type", r#"multipart/form-data; boundary="b""#)
128     .header("Content-Length", body_len)
129     .body(body)
130     .context("construct request")?;
131
132   let resp = c.hclient.request(req);
133   let fut = Box::pin(async move {
134     let r = async { tokio::time::timeout( c.effective_http_timeout, async {
135       let resp = resp.await.context("make request")?;
136       let status = resp.status();
137       let resp = resp.into_body();
138       // xxx: some size limit to avoid mallocing the universe
139       let resp = hyper::body::to_bytes(resp).await
140         .context("HTTP error fetching response body")?;
141
142       if ! status.is_success() {
143         throw!(anyhow!("HTTP error status={} body={:?}",
144                        &status, String::from_utf8_lossy(&resp)));
145       }
146
147       Ok::<_,AE>(resp)
148     }).await? }.await;
149
150     let r = c.reporter.lock().filter(Some(req_num), r);
151
152     if r.is_none() {
153       tokio::time::sleep(c.ic.http_retry).await;
154     }
155     r
156   });
157   reqs.push(fut);
158 }
159
160 async fn run_client<C:HCC>(
161   ic: InstanceConfig,
162   hclient: Arc<hyper::Client<C>>
163 ) -> Result<Void, AE>
164 {
165   debug!("{}: config: {:?}", &ic, &ic);
166
167   let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
168
169   let c = ClientContext {
170     reporter: &reporter,
171     hclient: &hclient,
172     ic: &ic,
173     effective_http_timeout: ic.http_timeout.checked_add(ic.http_timeout_grace)
174       .ok_or_else(|| anyhow!("calculate effective http timeout ({:?} + {:?})",
175                              ic.http_timeout, ic.http_timeout_grace))?,
176   };
177
178   let mut ipif = tokio::process::Command::new("sh")
179     .args(&["-c", &ic.ipif])
180     .stdin (process::Stdio::piped())
181     .stdout(process::Stdio::piped())
182     .stderr(process::Stdio::piped())
183     .kill_on_drop(true)
184     .spawn().context("spawn ipif")?;
185   
186   let stderr = ipif.stderr.take().unwrap();
187   let ic_name = ic.to_string();
188   let _ = task::spawn(async move {
189     let mut stderr = tokio::io::BufReader::new(stderr).lines();
190     while let Some(l) = stderr.next_line().await? {
191       error!("{}: ipif stderr: {}", &ic_name, l.trim_end());
192     }
193     Ok::<_,io::Error>(())
194   });
195
196   let mut req_num: ReqNum = 0;
197
198   let tx_stream = ipif.stdout.take().unwrap();
199   let mut rx_stream = ipif.stdin .take().unwrap();
200
201   let mut tx_stream = tokio::io::BufReader::new(tx_stream).split(SLIP_END);
202   let mut packets: VecDeque<Box<[u8]>> = default();
203   let mut upbound = Frames::default();
204
205   let mut reqs: Vec<OutstandingRequest>
206     = Vec::with_capacity(ic.max_requests_outstanding.sat());
207
208   let mut rx_queue: FrameQueue = default();
209
210   // xxx check that ic settings are all honoured
211
212   async {
213     loop {
214       select! {
215         y = rx_stream.write_all_buf(&mut rx_queue),
216         if ! rx_queue.is_empty() =>
217         {
218           let () = y.context("write rx data to ipif")?;
219         },
220
221         data = tx_stream.next_segment(),
222         if packets.is_empty() =>
223         {
224           let data =
225             data.context("read from ipif")?
226             .ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
227           //eprintln!("data={:?}", DumpHex(&data));
228
229           match check1(Slip2Mime, ic.mtu, &data, |header| {
230             let addr = ip_packet_addr::<false>(header)?;
231             if addr != ic.link.client.0 { throw!(PE::Src(addr)) }
232             Ok(())
233           }) {
234             Ok(packet) => packets.push_back(packet),
235             Err(PE::Empty) => { },
236             Err(e@ PE::Src(_)) => debug!("{}: tx discarding: {}", &ic, e),
237             Err(e) => error!("{}: tx discarding: {}", &ic, e),
238           };
239         },
240
241         _ = async { },
242         if ! upbound.tried_full() &&
243            ! packets.is_empty() =>
244         {
245           while let Some(packet) = packets.pop_front() {
246             match upbound.add(ic.max_batch_up, packet.into()/*xxx*/) {
247               Err(packet) => { packets.push_front(packet.into()/*xxx*/); break; }
248               Ok(()) => { },
249             }
250           }
251         },
252
253         _ = async { },
254         if reporter.lock().filter(None, {
255           if rx_queue.remaining() < ic.max_batch_down.sat() * 3 /* xxx */ {
256             // xxx make this separate option ? docs say server only
257             Ok(())
258           } else {
259             Err(anyhow!("rx queue full"))
260           }
261         }).is_some() &&
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             reporter.lock().success();
278             //eprintln!("got={:?}", DumpHex(&got));
279             checkn(SlipNoConv,ic.mtu, &got, &mut rx_queue, |header| {
280               let addr = ip_packet_addr::<true>(header)?;
281               if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
282               Ok(())
283             }, |e| error!("{} #{}: rx discarding: {}", &ic, req_num, e));
284           
285           }
286         }
287       }
288     }
289   }.await
290 }
291
292 #[tokio::main]
293 async fn main() -> Result<(), AE> {
294   let opts = Opts::from_args();
295
296   let ics = config::read(&opts.config, LinkEnd::Client)?;
297   if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
298
299   {
300     let env = env_logger::Env::new()
301       .filter("HIPPOTAT_LOG")
302       .write_style("HIPPOTAT_LOG_STYLE");
303   
304     let mut logb = env_logger::Builder::new();
305     logb.filter(Some("hippotat"),
306                 *[ log::LevelFilter::Info,
307                    log::LevelFilter::Debug ]
308                 .get(opts.debug)
309                 .unwrap_or(
310                   &log::LevelFilter::Trace
311                 ));
312     logb.parse_env(env);
313     logb.init();
314   }
315
316   let https = HttpsConnector::new();
317   let hclient = hyper::Client::builder().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 }