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