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