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