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