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