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