chiark / gitweb /
use proper client http timeout
[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                        &c.ic.link.client,
66                        token,
67                        c.ic.target_requests_outstanding,
68                        show_timeout,
69   );
70
71   let prefix2 = format!(into_crlfs!(
72     r#"
73        --b
74        Content-Type: application/octet-stream
75        Content-Disposition: form-data; name="d"
76
77        "#),
78   );
79   let suffix = format!(into_crlfs!(
80     r#"
81        --b--
82        "#),
83   );
84
85   macro_rules! content { {
86     $out:ty,
87     $iter:ident,
88     $into:ident,
89   } => {
90     itertools::chain![
91       array::IntoIter::new([
92         prefix1.$into(),
93         prefix2.$into(),
94       ]).take(
95         if upbound.is_empty() { 1 } else { 2 }
96       ),
97       Itertools::intersperse(
98         upbound.$iter().map(|u| { let out: $out = u.$into(); out }),
99         SLIP_END_SLICE.$into()
100       ),
101       [ suffix.$into() ],
102     ]
103   }}
104
105   let body_len: usize = content!(
106     &[u8],
107     iter,
108     as_ref,
109   ).map(|b| b.len()).sum();
110
111   trace!("{} #{}: frames={} bytes={}",
112          &c.ic, req_num, upbound.len(), body_len);
113
114   let body = hyper::body::Body::wrap_stream(
115     futures::stream::iter(
116       content!(
117         Bytes,
118         into_iter,
119         into,
120       ).map(Ok::<Bytes,Void>)
121     )
122   );
123
124   let req = hyper::Request::post(&c.ic.url)
125     .header("Content-Type", r#"multipart/form-data; boundary="b""#)
126     .header("Content-Length", body_len)
127     .body(body)
128     .context("construct request")?;
129
130   let resp = c.hclient.request(req);
131   let fut = Box::pin(async move {
132     let r = async { tokio::time::timeout( c.effective_http_timeout, async {
133       let resp = resp.await.context("make request")?;
134       let status = resp.status();
135       let resp = resp.into_body();
136       // xxx: some size limit to avoid mallocing the universe
137       let resp = hyper::body::to_bytes(resp).await
138         .context("HTTP error fetching response body")?;
139
140       if ! status.is_success() {
141         throw!(anyhow!("HTTP error status={} body={:?}",
142                        &status, String::from_utf8_lossy(&resp)));
143       }
144
145       Ok::<_,AE>(resp)
146     }).await? }.await;
147
148     let r = c.reporter.lock().filter(Some(req_num), r);
149
150     if r.is_none() {
151       tokio::time::sleep(c.ic.http_retry).await;
152     }
153     r
154   });
155   reqs.push(fut);
156 }
157
158 async fn run_client<C:HCC>(
159   ic: InstanceConfig,
160   hclient: Arc<hyper::Client<C>>
161 ) -> Result<Void, AE>
162 {
163   debug!("{}: config: {:?}", &ic, &ic);
164
165   let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
166
167   let c = ClientContext {
168     reporter: &reporter,
169     hclient: &hclient,
170     ic: &ic,
171     effective_http_timeout: ic.http_timeout.checked_add(ic.http_timeout_grace)
172       .ok_or_else(|| anyhow!("calculate effective http timeout ({:?} + {:?})",
173                              ic.http_timeout, ic.http_timeout_grace))?,
174   };
175
176   let mut ipif = tokio::process::Command::new("sh")
177     .args(&["-c", &ic.ipif])
178     .stdin (process::Stdio::piped())
179     .stdout(process::Stdio::piped())
180     .stderr(process::Stdio::piped())
181     .kill_on_drop(true)
182     .spawn().context("spawn ipif")?;
183   
184   let stderr = ipif.stderr.take().unwrap();
185   let ic_name = ic.to_string();
186   let _ = task::spawn(async move {
187     let mut stderr = tokio::io::BufReader::new(stderr).lines();
188     while let Some(l) = stderr.next_line().await? {
189       error!("{}: ipif stderr: {}", &ic_name, l.trim_end());
190     }
191     Ok::<_,io::Error>(())
192   });
193
194   let mut req_num: ReqNum = 0;
195
196   let tx_stream = ipif.stdout.take().unwrap();
197   let mut rx_stream = ipif.stdin .take().unwrap();
198
199   let mut tx_stream = tokio::io::BufReader::new(tx_stream).split(SLIP_END);
200   let mut packets: VecDeque<Box<[u8]>> = default();
201   let mut upbound = Frames::default();
202
203   let mut reqs: Vec<OutstandingRequest>
204     = Vec::with_capacity(ic.max_requests_outstanding.sat());
205
206   let mut rx_queue: FrameQueue = default();
207
208   // xxx check that ic settings are all honoured
209
210   async {
211     loop {
212       select! {
213         y = rx_stream.write_all_buf(&mut rx_queue),
214         if ! rx_queue.is_empty() =>
215         {
216           let () = y.context("write rx data to ipif")?;
217         },
218
219         data = tx_stream.next_segment(),
220         if packets.is_empty() =>
221         {
222           let data =
223             data.context("read from ipif")?
224             .ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
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(packet) => packets.push_back(packet),
233             Err(PE::Empty) => { },
234             Err(e@ PE::Src(_)) => debug!("{}: tx discarding: {}", &ic, e),
235             Err(e) => error!("{}: tx discarding: {}", &ic, e),
236           };
237         },
238
239         _ = async { },
240         if ! upbound.tried_full() &&
241            ! packets.is_empty() =>
242         {
243           while let Some(packet) = packets.pop_front() {
244             match upbound.add(ic.max_batch_up, packet.into()/*xxx*/) {
245               Err(packet) => { packets.push_front(packet.into()/*xxx*/); break; }
246               Ok(()) => { },
247             }
248           }
249         },
250
251         _ = async { },
252         if reporter.lock().filter(None, {
253           if rx_queue.remaining() < ic.max_batch_down.sat() * 3 /* xxx */ {
254             // xxx make this separate option ? docs say server only
255             Ok(())
256           } else {
257             Err(anyhow!("rx queue full"))
258           }
259         }).is_some() &&
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             reporter.lock().success();
276             //eprintln!("got={:?}", DumpHex(&got));
277             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           
283           }
284         }
285       }
286     }
287   }.await
288 }
289
290 #[tokio::main]
291 async fn main() -> Result<(), AE> {
292   let opts = Opts::from_args();
293
294   let ics = config::read(&opts.config, LinkEnd::Client)?;
295   if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
296
297   {
298     let env = env_logger::Env::new()
299       .filter("HIPPOTAT_LOG")
300       .write_style("HIPPOTAT_LOG_STYLE");
301   
302     let mut logb = env_logger::Builder::new();
303     logb.filter(Some("hippotat"),
304                 *[ log::LevelFilter::Info,
305                    log::LevelFilter::Debug ]
306                 .get(opts.debug)
307                 .unwrap_or(
308                   &log::LevelFilter::Trace
309                 ));
310     logb.parse_env(env);
311     logb.init();
312   }
313
314   let https = HttpsConnector::new();
315   let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
316   let hclient = Arc::new(hclient);
317
318   info!("starting");
319   let () = future::select_all(
320     ics.into_iter().map(|ic| Box::pin(async {
321       let assocname = ic.to_string();
322       info!("{} starting", &assocname);
323       let hclient = hclient.clone();
324       let join = task::spawn(async {
325         run_client(ic, hclient).await.void_unwrap_err()
326       });
327       match join.await {
328         Ok(e) => {
329           error!("{} failed: {:?}", &assocname, e);
330         },
331         Err(je) => {
332           error!("{} panicked!", &assocname);
333           panic::resume_unwind(je.into_panic());
334         },
335       }
336     }))
337   ).await.0;
338
339   error!("quitting because one of your client connections crashed");
340   process::exit(16);
341 }