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