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