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