chiark / gitweb /
move effective_http_timeout into InstanceConfig
[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   /// Increase debug level
13   #[structopt(long, short="D", parse(from_occurrences))]
14   debug: usize,
15
16   #[structopt(flatten)]
17   config: config::Opts,
18 }
19
20 type OutstandingRequest<'r> = Pin<Box<
21     dyn Future<Output=Option<Box<[u8]>>> + Send + 'r
22     >>;
23
24 impl<T> HCC for T where
25         T: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
26 trait HCC: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
27
28 struct ClientContext<'c,C> {
29   ic: &'c InstanceConfig,
30   hclient: &'c Arc<hyper::Client<C>>,
31   reporter: &'c parking_lot::Mutex<Reporter<'c>>,
32 }
33
34 #[throws(AE)]
35 fn submit_request<'r, 'c:'r, C:HCC>(
36   c: &'c ClientContext<C>,
37   req_num: &mut ReqNum,
38   reqs: &mut Vec<OutstandingRequest<'r>>,
39   upbound: FramesData,
40 ) {
41   let show_timeout = c.ic.http_timeout
42     .saturating_add(Duration::from_nanos(999_999_999))
43     .as_secs();
44
45   let time_t = SystemTime::now()
46     .duration_since(UNIX_EPOCH)
47     .unwrap_or_else(|_| Duration::default()) // clock is being weird
48     .as_secs();
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                        &c.ic.link.client,
68                        token,
69                        c.ic.target_requests_outstanding,
70                        show_timeout,
71                        c.ic.max_batch_down,
72   );
73
74   let prefix2 = format!(into_crlfs!(
75     r#"
76        --b
77        Content-Type: application/octet-stream
78        Content-Disposition: form-data; name="d"
79
80        "#),
81   );
82   let suffix = format!(into_crlfs!(
83     r#"
84        --b--
85        "#),
86   );
87
88   macro_rules! content { {
89     $out:ty,
90     $iter:ident,
91     $into:ident,
92   } => {
93     itertools::chain![
94       array::IntoIter::new([
95         prefix1.$into(),
96         prefix2.$into(),
97       ]).take(
98         if upbound.is_empty() { 1 } else { 2 }
99       ),
100       Itertools::intersperse(
101         upbound.$iter().map(|u| { let out: $out = u.$into(); out }),
102         SLIP_END_SLICE.$into()
103       ),
104       [ suffix.$into() ],
105     ]
106   }}
107
108   let body_len: usize = content!(
109     &[u8],
110     iter,
111     as_ref,
112   ).map(|b| b.len()).sum();
113
114   trace!("{} #{}: req; tx bytes={} frames={}",
115          &c.ic, req_num, body_len, upbound.len());
116
117   let body = hyper::body::Body::wrap_stream(
118     futures::stream::iter(
119       content!(
120         Bytes,
121         into_iter,
122         into,
123       ).map(Ok::<Bytes,Void>)
124     )
125   );
126
127   let req = hyper::Request::post(&c.ic.url)
128     .header("Content-Type", r#"multipart/form-data; boundary="b""#)
129     .header("Content-Length", body_len)
130     .body(body)
131     .context("construct request")?;
132
133   let resp = c.hclient.request(req);
134   let fut = Box::pin(async move {
135     let r = async { tokio::time::timeout( c.ic.effective_http_timeout, async {
136       let resp = resp.await.context("make request")?;
137       let status = resp.status();
138       let resp = resp.into_body();
139       let max_body = c.ic.max_batch_down.sat() + MAX_BATCH_DOWN_RESP_OVERHEAD;
140       let resp = read_limited_body(max_body, resp).await?;
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 let Some(r) = &r {
153       trace!("{} #{}: rok; rx bytes={}", &c.ic, req_num, r.len());
154     } else {
155       tokio::time::sleep(c.ic.http_retry).await;
156     }
157     r
158   });
159   reqs.push(fut);
160 }
161
162 async fn run_client<C:HCC>(
163   ic: InstanceConfig,
164   hclient: Arc<hyper::Client<C>>
165 ) -> Result<Void, AE>
166 {
167   debug!("{}: config: {:?}", &ic, &ic);
168
169   let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
170
171   let c = ClientContext {
172     reporter: &reporter,
173     hclient: &hclient,
174     ic: &ic,
175   };
176
177   let mut ipif = tokio::process::Command::new("sh")
178     .args(&["-c", &ic.ipif])
179     .stdin (process::Stdio::piped())
180     .stdout(process::Stdio::piped())
181     .stderr(process::Stdio::piped())
182     .kill_on_drop(true)
183     .spawn().context("spawn ipif")?;
184   
185   let stderr = ipif.stderr.take().unwrap();
186   let ic_name = ic.to_string();
187   let _ = task::spawn(async move {
188     let mut stderr = tokio::io::BufReader::new(stderr).lines();
189     while let Some(l) = stderr.next_line().await? {
190       error!("{}: ipif stderr: {}", &ic_name, l.trim_end());
191     }
192     Ok::<_,io::Error>(())
193   });
194
195   let mut req_num: ReqNum = 0;
196
197   let tx_stream = ipif.stdout.take().unwrap();
198   let mut rx_stream = ipif.stdin .take().unwrap();
199
200   let mut tx_stream = tokio::io::BufReader::new(tx_stream).split(SLIP_END);
201   let mut packets: VecDeque<Box<[u8]>> = default();
202   let mut upbound = Frames::default();
203
204   let mut reqs: Vec<OutstandingRequest>
205     = Vec::with_capacity(ic.max_requests_outstanding.sat());
206
207   let mut rx_queue: FrameQueue = default();
208
209   // xxx check that ic settings are all honoured
210
211   async {
212     loop {
213       let rx_queue_space = 
214         if rx_queue.remaining() < ic.max_batch_down.sat() {
215           Ok(())
216         } else {
217           Err(())
218         };
219       
220       select! {
221         y = rx_stream.write_all_buf(&mut rx_queue),
222         if ! rx_queue.is_empty() =>
223         {
224           let () = y.context("write rx data to ipif")?;
225         },
226
227         data = tx_stream.next_segment(),
228         if packets.is_empty() =>
229         {
230           let data =
231             data.context("read from ipif")?
232             .ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
233           //eprintln!("data={:?}", DumpHex(&data));
234
235           match check1(Slip2Mime, ic.mtu, &data, |header| {
236             let addr = ip_packet_addr::<false>(header)?;
237             if addr != ic.link.client.0 { throw!(PE::Src(addr)) }
238             Ok(())
239           }) {
240             Ok(packet) => packets.push_back(packet),
241             Err(PE::Empty) => { },
242             Err(e@ PE::Src(_)) => debug!("{}: tx discarding: {}", &ic, e),
243             Err(e) => error!("{}: tx discarding: {}", &ic, e),
244           };
245         },
246
247         _ = async { },
248         if ! upbound.tried_full() &&
249            ! packets.is_empty() =>
250         {
251           while let Some(packet) = packets.pop_front() {
252             match upbound.add(ic.max_batch_up, packet.into()/*xxx*/) {
253               Err(packet) => { packets.push_front(packet.into()/*xxx*/); break; }
254               Ok(()) => { },
255             }
256           }
257         },
258
259         _ = async { },
260         if rx_queue_space.is_ok() &&
261           (reqs.len() < ic.target_requests_outstanding.sat() ||
262            (reqs.len() < ic.max_requests_outstanding.sat() &&
263             ! upbound.is_empty()))
264           =>
265         {
266           submit_request(&c, &mut req_num, &mut reqs,
267                          mem::take(&mut upbound).into())?;
268         },
269
270         (got, goti, _) = async { future::select_all(&mut reqs).await },
271           if ! reqs.is_empty() =>
272         {
273           reqs.swap_remove(goti);
274
275           if let Some(got) = got {
276             reporter.lock().success();
277             //eprintln!("got={:?}", DumpHex(&got));
278             checkn(SlipNoConv,ic.mtu, &got, &mut rx_queue, |header| {
279               let addr = ip_packet_addr::<true>(header)?;
280               if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
281               Ok(())
282             }, |e| error!("{} #{}: rx discarding: {}", &ic, req_num, e));
283           
284           }
285         },
286
287         _ = tokio::time::sleep(c.ic.effective_http_timeout),
288         if rx_queue_space.is_err() =>
289         {
290           reporter.lock().filter(None, Err::<Void,_>(
291             anyhow!("rx queue full, blocked")
292           ));
293         },
294       }
295     }
296   }.await
297 }
298
299 #[tokio::main]
300 async fn main() -> Result<(), AE> {
301   let opts = Opts::from_args();
302
303   let ics = config::read(&opts.config, LinkEnd::Client)?;
304   if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
305
306   {
307     let env = env_logger::Env::new()
308       .filter("HIPPOTAT_LOG")
309       .write_style("HIPPOTAT_LOG_STYLE");
310   
311     let mut logb = env_logger::Builder::new();
312     logb.filter(Some("hippotat"),
313                 *[ log::LevelFilter::Info,
314                    log::LevelFilter::Debug ]
315                 .get(opts.debug)
316                 .unwrap_or(
317                   &log::LevelFilter::Trace
318                 ));
319     logb.parse_env(env);
320     logb.init();
321   }
322
323   let https = HttpsConnector::new();
324   let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
325   let hclient = Arc::new(hclient);
326
327   info!("starting");
328   let () = future::select_all(
329     ics.into_iter().map(|ic| Box::pin(async {
330       let assocname = ic.to_string();
331       info!("{} starting", &assocname);
332       let hclient = hclient.clone();
333       let join = task::spawn(async {
334         run_client(ic, hclient).await.void_unwrap_err()
335       });
336       match join.await {
337         Ok(e) => {
338           error!("{} failed: {:?}", &assocname, e);
339         },
340         Err(je) => {
341           error!("{} panicked!", &assocname);
342           panic::resume_unwind(je.into_panic());
343         },
344       }
345     }))
346   ).await.0;
347
348   error!("quitting because one of your client connections crashed");
349   process::exit(16);
350 }