chiark / gitweb /
mime slip tests, currently failing
[hippotat.git] / src / bin / client.rs
1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: AGPL-3.0-or-later
3 // There is NO WARRANTY.
4
5 use hippotat::prelude::*;
6 use hippotat_macros::into_crlfs;
7
8 type OutstandingRequest<'r> = Pin<Box<
9     dyn Future<Output=Option<Bytes>> + Send + 'r
10     >>;
11
12 impl<T> HCC for T where
13         T: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
14 trait HCC: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
15
16 struct ClientContext<'c,C> {
17   ic: &'c InstanceConfig,
18   hclient: &'c Arc<hyper::Client<C>>,
19   reporter: &'c parking_lot::Mutex<Reporter<'c>>,
20 }
21
22 #[throws(AE)]
23 fn submit_request<'r, 'c:'r, C:HCC>(
24   c: &'c ClientContext<C>,
25   reqs: &mut Vec<OutstandingRequest<'r>>,
26   upbound: FramesData,
27 ) {
28   let show_timeout = c.ic.http_timeout
29     .saturating_add(Duration::from_nanos(999_999_999))
30     .as_secs();
31
32   let time_t = SystemTime::now()
33     .duration_since(UNIX_EPOCH)
34     .unwrap_or_else(|_| Duration::default()) // clock is being weird
35     .as_secs();
36   let time_t = format!("{:x}", time_t);
37   let hmac = token_hmac(c.ic.secret.0.as_bytes(), time_t.as_bytes());
38   let mut token = time_t;
39   write!(token, " ").unwrap();
40   base64::encode_config_buf(&hmac, BASE64_CONFIG, &mut token);
41
42   let prefix1 = format!(into_crlfs!(
43     r#"--b
44        Content-Type: text/plain; charset="utf-8"
45        Content-Disposition: form-data; name="m"
46
47        {}
48        {}
49        {}
50        {}"#),
51                        &c.ic.link.client,
52                        token,
53                        c.ic.target_requests_outstanding,
54                        show_timeout,
55   );
56
57   let prefix2 = format!(into_crlfs!(
58     r#"
59        --b
60        Content-Type: application/octet-stream
61        Content-Disposition: form-data; name="d"
62
63        "#),
64   );
65   let suffix = format!(into_crlfs!(
66     r#"
67        --b--
68        "#),
69   );
70
71   macro_rules! content { {
72     $out:ty,
73     $iter:ident,
74     $into:ident,
75   } => {
76     itertools::chain![
77       array::IntoIter::new([
78         prefix1.$into(),
79         prefix2.$into(),
80       ]).take(
81         if upbound.is_empty() { 1 } else { 2 }
82       ),
83       Itertools::intersperse(
84         upbound.$iter().map(|u| { let out: $out = u.$into(); out }),
85         SLIP_END_SLICE.$into()
86       ),
87       [ suffix.$into() ],
88     ]
89   }}
90
91   let body_len: usize = content!(
92     &[u8],
93     iter,
94     as_ref,
95   ).map(|b| b.len()).sum();
96
97   let body = hyper::body::Body::wrap_stream(
98     futures::stream::iter(
99       content!(
100         Bytes,
101         into_iter,
102         into,
103       ).map(Ok::<Bytes,Void>)
104     )
105   );
106
107   let req = hyper::Request::post(&c.ic.url)
108     .header("Content-Type", r#"multipart/form-data; boundary="b""#)
109     .header("Content-Length", body_len)
110     .body(body)
111     .context("construct request")?;
112
113   let resp = c.hclient.request(req);
114   let fut = Box::pin(async move {
115     let r = async { tokio::time::timeout( c.ic.http_timeout, async {
116       let resp = resp.await.context("make request")?;
117       let status = resp.status();
118       let resp = resp.into_body();
119       // xxx: some size limit to avoid mallocing the universe
120       let resp = hyper::body::to_bytes(resp).await
121         .context("HTTP error fetching response body")?;
122
123       if ! status.is_success() {
124         // xxx get body and log it
125         throw!(anyhow!("HTTP error status={} body={:?}",
126                        &status, String::from_utf8_lossy(&resp)));
127       }
128
129       Ok::<_,AE>(resp)
130     }).await? }.await;
131
132     let r = c.reporter.lock().report(r);
133
134     if r.is_none() {
135       tokio::time::sleep(c.ic.http_retry).await;
136     }
137     r
138   });
139   reqs.push(fut);
140 }
141
142 #[allow(unused_variables)] // xxx
143 async fn run_client<C:HCC>(
144   ic: InstanceConfig,
145   hclient: Arc<hyper::Client<C>>
146 ) -> Result<Void, AE>
147 {
148   debug!("{}: config: {:?}", &ic, &ic);
149
150   let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
151
152   let c = ClientContext {
153     reporter: &reporter,
154     hclient: &hclient,
155     ic: &ic,
156   };
157
158   let mut ipif = tokio::process::Command::new("sh")
159     .args(&["-c", &ic.ipif])
160     .stdin (process::Stdio::piped())
161     .stdout(process::Stdio::piped())
162     .stderr(process::Stdio::piped())
163     .kill_on_drop(true)
164     .spawn().context("spawn ipif")?;
165   
166   let stderr = ipif.stderr.take().unwrap();
167   let ic_name = ic.to_string();
168   let _ = task::spawn(async move {
169     let mut stderr = tokio::io::BufReader::new(stderr).lines();
170     while let Some(l) = stderr.next_line().await? {
171       error!("{}: ipif stderr: {}", &ic_name, l.trim_end());
172     }
173     Ok::<_,io::Error>(())
174   });
175
176   let tx_stream = ipif.stdout.take().unwrap();
177   let mut tx_stream = tokio::io::BufReader::new(tx_stream).split(SLIP_END);
178   let mut tx_defer = None;
179
180   let stream_for_rx = ipif.stdin .take().unwrap();
181
182   let mut reqs: Vec<OutstandingRequest>
183     = Vec::with_capacity(ic.max_requests_outstanding.sat());
184
185   // xxx check that ic settings are all honoured
186
187   async {
188     loop {
189       select! {
190         packet = async {
191           // cancellation safety: if this future is polled, we might
192           // move out of tx_defer, but then we will be immediately
193           // ready and yield it inot packet
194           if let Some(y) = tx_defer.take() {
195             Ok(Some(y))
196           } else {
197             tx_stream.next_segment().await
198           }
199         },
200         if tx_defer.is_none() &&
201            reqs.len() < ic.max_requests_outstanding.sat() =>
202         {
203           let mut upbound = Frames::default();
204           let mut to_process: Option<Result<Option<Vec<u8>>,_>>
205             = Some(packet);
206           while let Some(packet) = to_process.take() {
207             let mut packet =
208               packet.context("read from ipif")?
209               .ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
210 //            eprintln!("packet={:x?}", &packet);
211             if let Ok(()) = check_checkmtu_mimeswap
212               ::<true>(ic.mtu, &mut packet)
213             {
214               match upbound.add(ic.max_batch_up, packet) {
215                 Err(packet) => {
216                   tx_defer = Some(packet);
217                   break;
218                 }
219                 Ok(()) => { },
220               };
221               // we rely oin `next_segment` being cancellation-safe,
222               // which isn't documented as true but seems reasonably safe
223               pin!{ let next_segment = tx_stream.next_segment(); }
224               to_process = match poll!(next_segment) {
225                 Poll::Ready(p) => Some(p),
226                 Poll::Pending => None,
227               };
228             }
229           }
230           assert!( to_process.is_none() );
231           dbg!(&reqs.len(), &upbound);
232
233           //: impl futures::Stream<Cow<&[u8]>>
234           submit_request(&c, &mut reqs, upbound.into())?;
235         }
236
237         () = async { },
238         if reqs.len() < ic.target_requests_outstanding.sat() ||
239            (tx_defer.is_some() &&
240             reqs.len() < ic.max_requests_outstanding.sat()) =>
241         {
242           let upbound = tx_defer.take().into_iter().collect_vec();
243           submit_request(&c, &mut reqs, upbound)?;
244         }
245
246         (got, goti, _) = async { future::select_all(&mut reqs).await },
247           if ! reqs.is_empty() =>
248         {
249           reqs.swap_remove(goti);
250           if let Some(got) = got {
251             dbg!(&got.remaining()); // xxx
252           }
253         }
254       }
255     }
256   }.await
257 }
258
259 #[tokio::main]
260 async fn main() -> Result<(), AE> {
261   let ics = config::read(LinkEnd::Client)?;
262   if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
263
264   env_logger::init();
265
266   let https = HttpsConnector::new();
267   let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
268   let hclient = Arc::new(hclient);
269
270   info!("starting");
271   let () = future::select_all(
272     ics.into_iter().map(|ic| Box::pin(async {
273       let assocname = ic.to_string();
274       info!("{} starting", &assocname);
275       let hclient = hclient.clone();
276       let join = task::spawn(async {
277         run_client(ic, hclient).await.void_unwrap_err()
278       });
279       match join.await {
280         Ok(e) => {
281           error!("{} failed: {:?}", &assocname, e);
282         },
283         Err(je) => {
284           error!("{} panicked!", &assocname);
285           panic::resume_unwind(je.into_panic());
286         },
287       }
288     }))
289   ).await.0;
290
291   error!("quitting because one of your client connections crashed");
292   process::exit(16);
293 }