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