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