chiark / gitweb /
make route_packet async
[hippotat.git] / src / bin / server.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
7 #[derive(StructOpt,Debug)]
8 pub struct Opts {
9   #[structopt(flatten)]
10   log: LogOpts,
11
12   #[structopt(flatten)]
13   config: config::Opts,
14 }
15
16 const METADATA_MAX_LEN: usize = MAX_OVERHEAD;
17
18 #[derive(Debug)]
19 pub struct Global {
20   config: config::InstanceConfigGlobal,
21   all_clients: HashMap<ClientName, Client>,
22 }
23
24 #[derive(Debug)]
25 pub struct Client {
26   ic: Arc<InstanceConfig>,
27   web: mpsc::Sender<WebRequest>,
28 }
29
30 pub type RoutedPacket = Box<[u8]>; // not MIME data
31
32 /// Sent from hyper worker pool task to client task
33 #[allow(dead_code)] // xxx
34 #[derive(Debug)]
35 struct WebRequest {
36   // initial part of body
37   // used up to and including first 2 lines of metadata
38   // end delimiter for the metadata not yet located, but in here somewhere
39   initial: Box<[u8]>,
40   initial_remaining: usize,
41   length_hint: usize,
42   body: hyper::body::Body,
43   boundary_finder: multipart::BoundaryFinder,
44   reply_to: oneshot::Sender<WebResponse>,
45   warnings: Warnings,
46   conn: Arc<String>,
47 }
48
49 /// Reply from client task to hyper worker pool task
50 #[allow(dead_code)] // xxx
51 #[derive(Debug)]
52 struct WebResponse {
53   warnings: Warnings,
54   data: Result<WebResponseData, AE>,
55 }
56
57 type WebResponseData = Vec<u8>;
58
59 #[throws(PacketError)]
60 pub async fn route_packet(global: &Global,
61                           conn: &str, link: &(dyn Display + Sync),
62                           packet: RoutedPacket, daddr: IpAddr)
63 {
64   let c = &global.config;
65   let trace = |how| trace!("{} {} route {} daddr={:?} len={}",
66                            conn, link, how, daddr, packet.len());
67
68   if daddr == c.vaddr || ! c.vnetwork.iter().any(|n| n.contains(&daddr)) {
69     trace("ipif inbound xxx discarding");
70   } else if daddr == c.vrelay {
71     trace("discard (relay)");
72   } else if let Some(_client) = global.all_clients.get(&ClientName(daddr)) {
73     trace("ipif route xxx discarding");
74   } else {
75     trace("discard (no client)");
76   }
77 }
78
79 async fn handle(
80   conn: Arc<String>,
81   global: Arc<Global>,
82   req: hyper::Request<hyper::Body>
83 ) -> Result<hyper::Response<hyper::Body>, hyper::http::Error> {
84   if req.method() == Method::GET {
85     let mut resp = hyper::Response::new(hyper::Body::from("hippotat\r\n"));
86     resp.headers_mut().insert(
87       "Content-Type",
88       "text/plain; charset=US-ASCII".try_into().unwrap()
89     );
90     return Ok(resp)
91   }
92
93   let mut warnings: Warnings = default();
94
95   async {
96
97     let get_header = |hn: &str| {
98       let mut values = req.headers().get_all(hn).iter();
99       let v = values.next().ok_or_else(|| anyhow!("missing {}", hn))?;
100       if values.next().is_some() { throw!(anyhow!("multiple {}!", hn)); }
101       let v = v.to_str().context(anyhow!("interpret {} as UTF-8", hn))?;
102       Ok::<_,AE>(v)
103     };
104
105     let mkboundary = |b: &'_ _| format!("\n--{}", b).into_bytes();
106     let boundary = match (||{
107       let t = get_header("Content-Type")?;
108       let t: mime::Mime = t.parse().context("parse Content-Type")?;
109       if t.type_() != "multipart" { throw!(anyhow!("not multipart/")) }
110       let b = mime::BOUNDARY;
111       let b = t.get_param(b).ok_or_else(|| anyhow!("missing boundary=..."))?;
112       if t.subtype() != "form-data" {
113         warnings.add(&"Content-Type not /form-data")?;
114       }
115       let b = mkboundary(b.as_str());
116       Ok::<_,AE>(b)
117     })() {
118       Ok(y) => y,
119       Err(e) => {
120         warnings.add(&e.wrap_err("guessing boundary"))?;
121         mkboundary("b")
122       },
123     };
124
125     let length_hint: usize = (||{
126       let clength = get_header("Content-Length")?;
127       let clength = clength.parse().context("parse Content-Length")?;
128       Ok::<_,AE>(clength)
129     })().unwrap_or_else(
130       |e| { let _ = warnings.add(&e.wrap_err("parsing Content-Length")); 0 }
131     );
132
133     let mut body = req.into_body();
134     let initial = match read_limited_bytes(
135       METADATA_MAX_LEN, default(), length_hint, &mut body
136     ).await {
137       Ok(all) => all,
138       Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
139       Err(ReadLimitedError::Hyper(e)) => throw!(e),
140     };
141
142     let boundary_finder = memmem::Finder::new(&boundary);
143     let mut boundary_iter = boundary_finder.find_iter(&initial);
144
145     let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
146     else if let Some(start) = boundary_iter.next() { start + boundary.len() }
147     else { throw!(anyhow!("initial boundary not found")) };
148
149     let comp = multipart::process_boundary
150       (&mut warnings, &initial[start..], PartName::m)?
151       .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
152
153     if comp.name != PartName::m { throw!(anyhow!(
154       r#"first multipart component must be name="m""#
155     )) }
156
157     let mut meta = MetadataFieldIterator::new(comp.payload);
158
159     let client: ClientName = meta.need_parse().context("client addr")?;
160
161     let mut hmac_got = [0; HMAC_L];
162     let (client_time, hmac_got_l) = (||{
163       let token: &str = meta.need_next().context(r#"find in "m""#)?;
164       let (time_t, hmac_b64) = token.split_once(' ')
165         .ok_or_else(|| anyhow!("split"))?;
166       let time_t = u64::from_str_radix(time_t, 16).context("parse time_t")?;
167       let l = io::copy(
168         &mut base64::read::DecoderReader::new(&mut hmac_b64.as_bytes(),
169                                               BASE64_CONFIG),
170         &mut &mut hmac_got[..]
171       ).context("parse b64 token")?;
172       let l = l.try_into()?;
173       Ok::<_,AE>((time_t, l))
174     })().context("token")?;
175     let hmac_got = &hmac_got[0..hmac_got_l];
176
177     let client_name = client;
178     let client = global.all_clients.get(&client_name);
179
180     // We attempt to hide whether the client exists we don't try to
181     // hide the hash lookup computationgs, but we do try to hide the
182     // HMAC computation by always doing it.  We hope that the compiler
183     // doesn't produce a specialised implementation for the dummy
184     // secret value.
185     let client_exists = subtle::Choice::from(client.is_some() as u8);
186     let secret = client.map(|c| c.ic.secret.0.as_bytes());
187     let secret = secret.unwrap_or(&[0x55; HMAC_B][..]);
188     let client_time_s = format!("{:x}", client_time);
189     let hmac_exp = token_hmac(secret, client_time_s.as_bytes());
190     // We also definitely want a consttime memeq for the hmac value
191     let hmac_ok = hmac_got.ct_eq(&hmac_exp);
192     //dbg!(DumpHex(&hmac_exp), client.is_some());
193     //dbg!(DumpHex(hmac_got), hmac_ok, client_exists);
194     if ! bool::from(hmac_ok & client_exists) {
195       debug!("{} rejected client {}", &conn, &client_name);
196       let body = hyper::Body::from("Not authorised\r\n");
197       return Ok(
198         hyper::Response::builder()
199           .status(hyper::StatusCode::FORBIDDEN)
200           .header("Content-Type", r#"text/plain; charset="utf-8""#)
201           .body(body)
202       )
203     }
204
205     let client = client.unwrap();
206     let now = time_t_now();
207     let chk_skew = |a: u64, b: u64, c_ahead_behind| {
208       if let Some(a_ahead) = a.checked_sub(b) {
209         if a_ahead > client.ic.max_clock_skew.as_secs() {
210           throw!(anyhow!("too much clock skew (client {} by {})",
211                          c_ahead_behind, a_ahead));
212         }
213       }
214       Ok::<_,AE>(())
215     };
216     chk_skew(client_time, now, "ahead")?;
217     chk_skew(now, client_time, "behind")?;
218
219     let initial_remaining = meta.remaining_bytes_len();
220
221     //eprintln!("boundary={:?} start={} name={:?} client={}",
222     // boundary, start, &comp.name, &client.ic);
223
224     let (reply_to, reply_recv) = oneshot::channel();
225     trace!("{} {} request, Content-Length={}",
226            &conn, &client_name, length_hint);
227     let wreq = WebRequest {
228       initial,
229       initial_remaining,
230       length_hint,
231       boundary_finder: boundary_finder.into_owned(),
232       body,
233       warnings: mem::take(&mut warnings),
234       reply_to,
235       conn: conn.clone(),
236     };
237
238     client.web.try_send(wreq)
239       .map_err(|_| anyhow!("client task shut down!"))?;
240
241     let reply: WebResponse = reply_recv.await?;
242     warnings = reply.warnings;
243     let data = reply.data?;
244
245     if warnings.warnings.is_empty() {
246       trace!("{} {} responding, {}",
247              &conn, &client_name, data.len());
248     } else {
249       debug!("{} {} responding, {} warnings={:?}",
250              &conn, &client_name, data.len(),
251              &warnings.warnings);
252     }
253
254     let data = hyper::Body::from(data);
255     Ok::<_,AE>(
256       hyper::Response::builder()
257         .header("Content-Type", r#"application/octet-stream"#)
258         .body(data)
259     )
260   }.await.unwrap_or_else(|e| {
261     debug!("{} error {}", &conn, &e);
262     let mut errmsg = format!("ERROR\n\n{:?}\n\n", &e);
263     for w in warnings.warnings {
264       write!(errmsg, "warning: {}\n", w).unwrap();
265     }
266     hyper::Response::builder()
267       .status(hyper::StatusCode::BAD_REQUEST)
268       .header("Content-Type", r#"text/plain; charset="utf-8""#)
269       .body(errmsg.into())
270   })
271 }
272
273 #[allow(unused_variables)] // xxx
274 #[allow(unused_mut)] // xxx
275 async fn run_client(global: Arc<Global>,
276                     ic: Arc<InstanceConfig>,
277                     mut web: mpsc::Receiver<WebRequest>)
278                     -> Result<Void, AE>
279 {
280   struct Outstanding {
281     reply_to: oneshot::Sender<WebResponse>,
282     oi: OutstandingInner,
283   }
284   #[derive(Debug)]
285   struct OutstandingInner {
286     target_requests_outstanding: u32,
287   }
288   let mut outstanding: VecDeque<Outstanding> = default();
289   let  downbound: VecDeque<(/*xxx*/)> = default();
290
291   let try_send_response = |
292     reply_to: oneshot::Sender<WebResponse>,
293     response: WebResponse
294   | {
295     reply_to.send(response)
296       .unwrap_or_else(|_: WebResponse| () /* oh dear */ /* xxx trace? */);
297   };
298
299   loop {
300     if let Some(ret) = {
301       if ! downbound.is_empty() {
302         outstanding.pop_front()
303       } else if let Some((i,_)) = outstanding.iter().enumerate().find({
304         |(_,o)| outstanding.len() > o.oi.target_requests_outstanding.sat()
305       }) {
306         Some(outstanding.remove(i).unwrap())
307       } else {
308         None
309       }
310     } {
311       let response = WebResponse {
312         data: Ok(vec![ /* xxx */ ]),
313         warnings: default(),
314       };
315
316       try_send_response(ret.reply_to, response);
317     }
318
319     select!{
320       req = web.recv() =>
321       {
322         let WebRequest {
323           initial, initial_remaining, length_hint, mut body,
324           boundary_finder,
325           reply_to, conn, mut warnings,
326         } = req.ok_or_else(|| anyhow!("webservers all shut down!"))?;
327
328         match async {
329
330           let initial_used = initial.len() - initial_remaining;
331
332           let whole_request = read_limited_bytes(
333             ic.max_batch_up.sat(),
334             initial,
335             length_hint,
336             &mut body
337           ).await.context("read request body")?;
338
339           let (meta, mut comps) =
340             multipart::ComponentIterator::resume_mid_component(
341               &whole_request[initial_used..],
342               boundary_finder
343             ).context("resume parsing body, after auth checks")?;
344
345           let mut meta = MetadataFieldIterator::new(&meta);
346
347           macro_rules! meta {
348             { $v:ident, ( $( $badcmp:tt )? ), $ret:expr,
349               let $server:ident, $client:ident $($code:tt)*
350             } => {
351               let $v = (||{
352                 let $server = ic.$v;
353                 let $client $($code)*
354                 $(
355                   if $client $badcmp $server {
356                     throw!(anyhow!("mismatch: client={:?} {} server={:?}",
357                                    $client, stringify!($badcmp), $server));
358                   }
359                 )?
360                 Ok::<_,AE>($ret)
361               })().context(stringify!($v))?;
362               //dbg!(&$v);
363             }
364           }
365
366           meta!{
367             target_requests_outstanding, ( != ), client,
368             let server, client: u32 = meta.need_parse()?;
369           }
370
371           meta!{
372             http_timeout, ( > ), client,
373             let server, client = Duration::from_secs(meta.need_parse()?);
374           }
375
376           meta!{
377             mtu, ( != ), client,
378             let server, client: u32 = meta.parse()?.unwrap_or(server);
379           }
380
381           meta!{
382             max_batch_down, (), min(client, server),
383             let server, client: u32 = meta.parse()?.unwrap_or(server);
384           }
385
386           meta!{
387             max_batch_up, ( > ), client,
388             let server, client = meta.parse()?.unwrap_or(server);
389           }
390
391           while let Some(comp) = comps.next(&mut warnings, PartName::d)? {
392             if comp.name != PartName::d {
393               warnings.add(&format_args!("unexpected part {:?}", comp.name))?;
394             }
395             checkn(Mime2Slip, mtu, comp.payload, |header| {
396               let saddr = ip_packet_addr::<false>(header)?;
397               if saddr != ic.link.client.0 { throw!(PE::Src(saddr)) }
398               let daddr = ip_packet_addr::<true>(header)?;
399               Ok(daddr)
400             }, |(daddr,packet)| route_packet(
401               &global, &conn, &ic.link.client, daddr,packet
402             ),
403               |e| Ok::<_,SlipFramesError<_>>({ warnings.add(&e)?; })
404             ).await?;
405           }
406
407           let oi = OutstandingInner {
408             target_requests_outstanding,
409           };
410           Ok::<_,AE>(oi)
411         }.await {
412           Ok(oi) => outstanding.push_back(Outstanding { reply_to, oi }),
413           Err(e) => {
414             try_send_response(reply_to, WebResponse {
415               data: Err(e),
416               warnings,
417             });
418           },
419         }
420       }
421     }
422   }
423   //Err(anyhow!("xxx"))
424 }
425
426 #[tokio::main]
427 async fn main() {
428   let opts = Opts::from_args();
429   let mut tasks: Vec<(
430     JoinHandle<AE>,
431     String,
432   )> = vec![];
433
434   let (global, ipif) = config::startup(
435     "hippotatd", LinkEnd::Server,
436     &opts.config, &opts.log, |ics|
437   {
438     let global_config = config::InstanceConfigGlobal::from(&ics);
439
440     let ipif = Ipif::start(&global_config.ipif, None)?;
441
442     let ics = ics.into_iter().map(Arc::new).collect_vec();
443     let (client_handles_send, client_handles_recv) = ics.iter()
444       .map(|_ic| mpsc::channel(
445         5 // xxx should me max_requests_outstanding but that's
446         // marked client-only so needs rework
447       )).unzip::<_,_,Vec<_>,Vec<_>>();
448
449     let all_clients = izip!(
450       &ics,
451       client_handles_send,
452     ).map(|(ic, web_send)| {
453       (ic.link.client,
454        Client {
455          ic: ic.clone(),
456          web: web_send,
457        })
458     }).collect();
459
460     let global = Arc::new(Global {
461       config: global_config,
462       all_clients,
463     });
464
465     for (ic, web_recv) in izip!(
466       ics,
467       client_handles_recv,
468     ) {
469       let global_ = global.clone();
470       let ic_ = ic.clone();
471       tasks.push((tokio::spawn(async move {
472         run_client(global_, ic_, web_recv).await.void_unwrap_err()
473       }), format!("client {}", &ic)));
474     }
475
476     for addr in &global.config.addrs {
477       let global_ = global.clone();
478       let make_service = hyper::service::make_service_fn(
479         move |conn: &hyper::server::conn::AddrStream| {
480           let global_ = global_.clone();
481           let conn = Arc::new(format!("[{}]", conn.remote_addr()));
482           async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
483             handle(conn.clone(), global_.clone(), req)
484           }) ) }
485         }
486       );
487
488       let addr = SocketAddr::new(*addr, global.config.port);
489       let server = hyper::Server::try_bind(&addr)
490         .context("bind")?
491         .http1_preserve_header_case(true)
492         .serve(make_service);
493       info!("listening on {}", &addr);
494       let task = tokio::task::spawn(async move {
495         match server.await {
496           Ok(()) => anyhow!("shut down?!"),
497           Err(e) => e.into(),
498         }
499       });
500       tasks.push((task, format!("http server {}", addr)));
501     }
502     
503     Ok((global, ipif))
504   });
505
506   let died = future::select_all(
507     tasks.iter_mut().map(|e| &mut e.0)
508   ).await;
509   error!("xxx {:?}", &died);
510
511   ipif.quitting(None).await;
512
513   dbg!(global);
514 }