chiark / gitweb /
wip refactor body, move type
[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   } => {
74     itertools::chain![
75       array::IntoIter::new([
76         Ok::<$out,Void>( prefix1.into() ),
77         Ok::<$out,Void>( prefix2.into() ),
78       ]).take(
79         if upbound.is_empty() { 1 } else { 2 }
80       ),
81       Itertools::intersperse(
82         upbound.into_iter().map(|u| { let out: $out = u.into(); out }),
83         SLIP_END_SLICE.into()
84       ).map(Ok::<$out,Void>),
85       [ Ok::<$out,Void>( suffix.into() ) ],
86     ]
87   }}
88
89   let body = hyper::body::Body::wrap_stream(
90     futures::stream::iter(
91       content!( Bytes )
92     )
93   );
94
95   let req = hyper::Request::post(&c.ic.url)
96     .header("Content-Type", r#"multipart/form-data; boundary="b""#)
97     .body(body)
98     .context("construct request")?;
99
100   let resp = c.hclient.request(req);
101   let fut = Box::pin(async move {
102     let r = async { tokio::time::timeout( c.ic.http_timeout, async {
103       let resp = resp.await.context("make request")?;
104       let status = resp.status();
105       let resp = resp.into_body();
106       // xxx: some size limit to avoid mallocing the universe
107       let resp = hyper::body::to_bytes(resp).await
108         .context("HTTP error fetching response body")?;
109
110       if ! status.is_success() {
111         // xxx get body and log it
112         throw!(anyhow!("HTTP error status={} body={:?}",
113                        &status, String::from_utf8_lossy(&resp)));
114       }
115
116       Ok::<_,AE>(resp)
117     }).await? }.await;
118
119     let r = c.reporter.lock().report(r);
120
121     if r.is_none() {
122       tokio::time::sleep(c.ic.http_retry).await;
123     }
124     r
125   });
126   reqs.push(fut);
127 }
128
129 #[allow(unused_variables)] // xxx
130 async fn run_client<C:HCC>(
131   ic: InstanceConfig,
132   hclient: Arc<hyper::Client<C>>
133 ) -> Result<Void, AE>
134 {
135   debug!("{}: config: {:?}", &ic, &ic);
136
137   let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
138
139   let c = ClientContext {
140     reporter: &reporter,
141     hclient: &hclient,
142     ic: &ic,
143   };
144
145   let mut ipif = tokio::process::Command::new("sh")
146     .args(&["-c", &ic.ipif])
147     .stdin (process::Stdio::piped())
148     .stdout(process::Stdio::piped())
149     .stderr(process::Stdio::piped())
150     .kill_on_drop(true)
151     .spawn().context("spawn ipif")?;
152   
153   let stderr = ipif.stderr.take().unwrap();
154   let ic_name = ic.to_string();
155   let _ = task::spawn(async move {
156     let mut stderr = tokio::io::BufReader::new(stderr).lines();
157     while let Some(l) = stderr.next_line().await? {
158       error!("{}: ipif stderr: {}", &ic_name, l.trim_end());
159     }
160     Ok::<_,io::Error>(())
161   });
162
163   let tx_stream = ipif.stdout.take().unwrap();
164   let mut tx_stream = tokio::io::BufReader::new(tx_stream).split(SLIP_ESC);
165   let mut tx_defer = None;
166
167   let stream_for_rx = ipif.stdin .take().unwrap();
168
169   let mut reqs: Vec<OutstandingRequest>
170     = Vec::with_capacity(ic.max_requests_outstanding.sat());
171
172   // xxx check that ic settings are all honoured
173
174   async {
175     loop {
176       select! {
177         packet = async {
178           // cancellation safety: if this future is polled, we might
179           // move out of tx_defer, but then we will be immediately
180           // ready and yield it inot packet
181           if let Some(y) = tx_defer.take() {
182             Ok(Some(y))
183           } else {
184             tx_stream.next_segment().await
185           }
186         },
187         if tx_defer.is_none() &&
188            reqs.len() < ic.max_requests_outstanding.sat() =>
189         {
190           let mut upbound = Frames::default();
191           let mut to_process: Option<Result<Option<Vec<u8>>,_>>
192             = Some(packet);
193           while let Some(packet) = to_process.take() {
194             let mut packet =
195               packet.context("read from ipif")?
196               .ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
197             if let Ok(()) = check_checkmtu_mimeswap
198               ::<true>(&ic, &mut packet)
199             {
200               match upbound.add(ic.max_batch_up, packet) {
201                 Err(packet) => {
202                   tx_defer = Some(packet);
203                   break;
204                 }
205                 Ok(()) => { },
206               };
207               // we rely oin `next_segment` being cancellation-safe,
208               // which isn't documented as true but seems reasonably safe
209               pin!{ let next_segment = tx_stream.next_segment(); }
210               to_process = match poll!(next_segment) {
211                 Poll::Ready(p) => Some(p),
212                 Poll::Pending => None,
213               };
214             }
215           }
216           assert!( to_process.is_none() );
217           dbg!(&reqs.len(), &upbound);
218
219           //: impl futures::Stream<Cow<&[u8]>>
220           submit_request(&c, &mut reqs, upbound.into())?;
221         }
222
223         () = async { },
224         if reqs.len() < ic.target_requests_outstanding.sat() ||
225            (tx_defer.is_some() &&
226             reqs.len() < ic.max_requests_outstanding.sat()) =>
227         {
228           let upbound = tx_defer.take().into_iter().collect_vec();
229           submit_request(&c, &mut reqs, upbound)?;
230         }
231
232         (got, goti, _) = async { future::select_all(&mut reqs).await },
233           if ! reqs.is_empty() =>
234         {
235           reqs.swap_remove(goti);
236           if let Some(got) = got {
237             dbg!(&got.remaining()); // xxx
238           }
239         }
240       }
241     }
242   }.await
243 }
244
245 #[tokio::main]
246 async fn main() -> Result<(), AE> {
247   let ics = config::read(LinkEnd::Client)?;
248   if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
249
250   env_logger::init();
251
252   let https = HttpsConnector::new();
253   let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
254   let hclient = Arc::new(hclient);
255
256   info!("starting");
257   let () = future::select_all(
258     ics.into_iter().map(|ic| Box::pin(async {
259       let assocname = ic.to_string();
260       info!("{} starting", &assocname);
261       let hclient = hclient.clone();
262       let join = task::spawn(async {
263         run_client(ic, hclient).await.void_unwrap_err()
264       });
265       match join.await {
266         Ok(e) => {
267           error!("{} failed: {:?}", &assocname, e);
268         },
269         Err(je) => {
270           error!("{} panicked!", &assocname);
271           panic::resume_unwind(je.into_panic());
272         },
273       }
274     }))
275   ).await.0;
276
277   error!("quitting because one of your client connections crashed");
278   process::exit(16);
279 }