chiark / gitweb /
pass SlipMime also as value
[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(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 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: VecDeque<Box<[u8]>> = default();
197   #[derive(Debug)]
198   enum RxState {
199     Frame(Cursor<Box<u8>>),
200     End,
201   }
202   let mut rx_current: Option<RxState> = None;
203
204   // xxx check that ic settings are all honoured
205
206   async {
207     loop {
208       select! {
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 reqs.len() < ic.target_requests_outstanding.sat() ||
243            (reqs.len() < ic.max_requests_outstanding.sat() &&
244             ! upbound.is_empty())
245           // xxx backpressure, if too much in rx_queue
246           =>
247         {
248           submit_request(&c, &mut req_num, &mut reqs,
249                          mem::take(&mut upbound).into())?;
250         },
251
252         (got, goti, _) = async { future::select_all(&mut reqs).await },
253           if ! reqs.is_empty() =>
254         {
255           reqs.swap_remove(goti);
256
257           if let Some(got) = got {
258             //eprintln!("got={:?}", DumpHex(&got));
259             checkn(SlipNoConv,ic.mtu, &got, &mut rx_queue, |header| {
260               let addr = ip_packet_addr::<true>(header)?;
261               if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
262               Ok(())
263             }, |e| error!("{} #{}: rx discarding: {}", &ic, req_num, e));
264           
265             dbg!(&rx_queue.len());
266             rx_queue = default(); // xxx
267           }
268         }
269       }
270     }
271   }.await
272 }
273
274 #[tokio::main]
275 async fn main() -> Result<(), AE> {
276   let ics = config::read(LinkEnd::Client)?;
277   if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
278
279   env_logger::init();
280
281   let https = HttpsConnector::new();
282   let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
283   let hclient = Arc::new(hclient);
284
285   info!("starting");
286   let () = future::select_all(
287     ics.into_iter().map(|ic| Box::pin(async {
288       let assocname = ic.to_string();
289       info!("{} starting", &assocname);
290       let hclient = hclient.clone();
291       let join = task::spawn(async {
292         run_client(ic, hclient).await.void_unwrap_err()
293       });
294       match join.await {
295         Ok(e) => {
296           error!("{} failed: {:?}", &assocname, e);
297         },
298         Err(je) => {
299           error!("{} panicked!", &assocname);
300           panic::resume_unwind(je.into_panic());
301         },
302       }
303     }))
304   ).await.0;
305
306   error!("quitting because one of your client connections crashed");
307   process::exit(16);
308 }