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